Compare commits

..
99 Commits
Author SHA1 Message Date
Mark Qvist 45e39917b5 Updated dependencies 2024-03-19 13:54:09 +01:00
Mark Qvist 27ffea3ea9 Improved message transfer feedback 2024-03-19 13:45:55 +01:00
Mark Qvist d2b2ef54e8 Added outbound transfer progress monitoring 2024-03-19 11:03:12 +01:00
Mark Qvist 3fbe2e94da Append incoming to locally delivered transient IDs and check on arrival 2024-03-19 09:47:37 +01:00
Mark Qvist 21af6a4e5c Updated version 2024-03-17 00:40:15 +01:00
Mark Qvist 739349c2a1 Updated field codes 2024-03-17 00:35:54 +01:00
Mark Qvist 994bb07efd Updated timing 2024-03-17 00:35:45 +01:00
Mark Qvist 1e9fe969fd Updated version 2024-03-02 09:17:34 +01:00
Mark Qvist 1d651a9b53 Added transfer limit awareness to message sync. Added ability to retain messages on node. 2024-03-02 09:09:51 +01:00
Mark Qvist 22493005dc Overhead calculation for propagation transfer limits 2024-03-01 23:48:12 +01:00
Mark Qvist 7ecd3c0d5e Added incoming resource transfer size limits 2024-03-01 23:26:27 +01:00
Mark Qvist 64050d39bf Added propagation transfer limit options 2024-03-01 22:37:54 +01:00
Mark Qvist c7489dc0fa Added transfer limit handling to announce handler 2024-03-01 22:33:53 +01:00
Mark Qvist bb1b9e4163 Updated dependency version 2024-03-01 00:33:42 +01:00
Mark Qvist b3bc8e684e Updated dependency 2024-02-29 23:03:02 +01:00
Mark Qvist 696c78ecea Improved propagation node sync and memory consumption 2024-02-29 23:02:16 +01:00
Mark Qvist 7aea4ea209 Updated version 2024-02-29 20:15:03 +01:00
Mark Qvist 35dc771528 Don't keep links alive after sync 2024-02-29 20:12:54 +01:00
Mark Qvist c369c6fc26 Merge branch 'master' of github.com:markqvist/LXMF 2024-02-29 18:27:48 +01:00
Mark Qvist af2dd56707 Added issue templates 2024-02-29 18:27:19 +01:00
markqvist 1287cb9f11 Merge pull request #15 from qwertyuiopzxcvbnmlkjhgfdsa1/feature/dockerize
dockerize LXMF
2024-02-29 18:26:36 +01:00
Mark Qvist f0e9fa6659 Corrected inconsistent property, getter and setter use. Fixed #16. 2024-01-16 13:26:33 +01:00
Mark Qvist 7a1bcc134b Updated dependencies 2024-01-15 20:29:39 +01:00
Mark Qvist 87413b9355 Updated readme 2024-01-15 20:29:29 +01:00
Mark Qvist 6ed16916d6 Fixed get fields method 2024-01-07 16:51:30 +01:00
Mark Qvist 754ae969e1 Added code examples. Closes #8. 2024-01-03 12:45:18 +01:00
Mark Qvist 1ee0c83168 Updated version and dependencies 2023-11-08 20:41:51 +01:00
Mark Qvist 2812a07165 Cleanup 2023-11-02 18:29:46 +01:00
Mark Qvist 10be1383e5 Updated version and dependencies 2023-11-02 12:48:24 +01:00
Mark Qvist 4d356bcda8 Tweaked timing 2023-11-02 04:36:51 +01:00
Mark Qvist da6fb3d0f3 Added field specifiers 2023-10-30 02:26:24 +01:00
Mark Qvist 56cb637bfa Improved propagation node sync feedback. Added physical layer reception statistics. 2023-10-28 00:06:56 +02:00
Mark Qvist 2872c94394 Merge branch 'master' of github.com:markqvist/LXMF 2023-10-24 01:48:13 +02:00
Mark Qvist f307f33bf8 Updated version and dependencies 2023-10-24 01:47:45 +02:00
Mark Qvist a095ba7e40 Added physical layer link statistics to reception 2023-10-23 01:34:20 +02:00
markqvist 0dc1e13f9d Update README.md 2023-10-17 02:14:07 +02:00
Mark Qvist f83600430a Updated version 2023-10-16 01:50:37 +02:00
Mark Qvist 537123896b Increased max unreachable time to 14 days 2023-10-16 01:50:01 +02:00
Mark Qvist bc8863c3b1 Updated version 2023-10-15 20:28:55 +02:00
Mark Qvist b894c5a2a6 Fixed paper message generation sequence 2023-10-15 20:27:35 +02:00
Mark Qvist 0ac4660510 Updated version and dependencien 2023-10-07 16:43:33 +02:00
Mark Qvist 672054177c Updated version and dependencies 2023-09-19 11:36:13 +02:00
Petr Blaha 820c92d38b dockerize LXMF 2023-09-07 08:51:49 +02:00
Petr Blaha 9f051aea17 dockerize LXMF 2023-09-07 08:39:57 +02:00
Mark Qvist 55cf934475 Updated install section 2023-08-15 11:27:02 +02:00
Mark Qvist b690880332 Updated dependencies 2023-08-15 11:08:38 +02:00
Mark Qvist 7220a4d6f7 Updated install section 2023-08-15 11:07:24 +02:00
Mark Qvist 5abf01a88f Updated version and dependencies 2023-06-13 19:56:44 +02:00
Mark Qvist 51a4d19595 Updated dependencies 2023-02-17 22:19:12 +01:00
Mark Qvist ad8fb74d9e Cleanup 2023-02-17 19:36:20 +01:00
Mark Qvist 447a8a920c Implemented mechanisms to tend propagation node sync graph towards using faster links first 2023-02-17 17:10:31 +01:00
Mark Qvist 0ba3ea98cb Added metric for link establishment rate to peers 2023-02-17 12:29:00 +01:00
markqvist fc0b086cb1 Merge pull request #13 from jimt/patch-1
Fix typos
2023-02-10 09:12:27 +01:00
Jim Tittsler 7a40bd44e8 Fix typos 2023-02-10 16:07:16 +09:00
Mark Qvist afe6815637 Fixed hardcoded APP_NAME reference 2023-02-03 17:56:30 +01:00
Mark Qvist a64f3a58f7 Fixed verbosity and quitness being overridden by config file values 2023-01-27 17:00:29 +01:00
Mark Qvist 2bb34176b7 Merge branch 'master' of github.com:markqvist/LXMF 2023-01-27 16:37:15 +01:00
Mark Qvist 6f80c6941d Fixed a erroneous warning message about missing authentication identities. Fixed a missing check for announce intervals being unset in the configuration. Fixes #12. 2023-01-27 16:36:15 +01:00
markqvist 02d42747b7 Merge pull request #11 from Erethon/master
Update documentation to match reality
2023-01-26 09:57:03 +01:00
Dionysis Grigoropoulos 5b81ecce04 Update documentation to match reality 2023-01-26 02:56:20 +02:00
Mark Qvist 8c94118e07 Updated dependencies and version 2023-01-14 21:10:54 +01:00
Mark Qvist 390cac84e3 Updated RNS dependency 2022-12-23 23:49:20 +01:00
Mark Qvist ae6b5d9a6d Updated delivery timing 2022-12-23 23:49:01 +01:00
Mark Qvist ffb1bdff17 Updated processing timings 2022-12-22 21:23:29 +01:00
Mark Qvist 1440a0b162 Added sync backoff for unresponsive peers. Improved sync peer selection. 2022-12-20 23:58:09 +01:00
Mark Qvist b10755e34f Updated readme 2022-11-24 18:34:44 +01:00
Mark Qvist 683e9ee412 Added paper message info 2022-11-24 18:22:51 +01:00
Mark Qvist aa3886720f Added paper message info 2022-11-24 18:21:12 +01:00
Mark Qvist 7ee7c60e77 Added paper message info 2022-11-24 18:19:58 +01:00
Mark Qvist 0c52d3fcd4 Added paper message info 2022-11-24 18:19:01 +01:00
Mark Qvist 8f425e6dde Added paper message info 2022-11-24 18:17:21 +01:00
Mark Qvist a1c897a8ca Updated readme 2022-11-24 18:05:58 +01:00
Mark Qvist 9fa6a144d0 Updated readme 2022-11-24 18:04:51 +01:00
Mark Qvist 54005c148a Updated versions 2022-11-24 17:59:50 +01:00
Mark Qvist abe2e78283 Improved paper message packing 2022-11-22 19:53:25 +01:00
Mark Qvist edbb887d81 Implemented paper message handling 2022-11-19 20:07:00 +01:00
Mark Qvist 540aa1a496 Merge branch 'master' of https://git.unsigned.io/markqvist/LXMF 2022-11-19 17:54:51 +01:00
Mark Qvist 3d31620160 Added paper message generator 2022-11-19 17:54:29 +01:00
Mark Qvist 6b983872fa Updated readme 2022-11-17 13:16:22 +01:00
Mark Qvist bb7bbaf124 Updated readme 2022-11-17 12:57:33 +01:00
Mark Qvist dad21bcca7 Added roadmap 2022-11-17 12:55:04 +01:00
Mark Qvist f75ea842d9 Updated readme 2022-11-10 16:22:33 +01:00
Mark Qvist f7ee4c1d86 Updated readme 2022-11-10 16:21:33 +01:00
Mark Qvist 58c61a2557 Updated readme 2022-11-10 16:20:14 +01:00
Mark Qvist 730a611f7a Updated dependencies 2022-11-03 23:17:50 +01:00
Mark Qvist ab68c15d2d Updated version and dependencies 2022-11-03 12:18:54 +01:00
Mark Qvist 564cd9b18c Updated build scripts 2022-10-22 22:43:28 +02:00
Mark Qvist cacddfdf30 Save locally delivered transient id cache on sync completion 2022-10-22 22:35:07 +02:00
Mark Qvist adbbaa532b Added autopeer and authentication options to lxmd config 2022-10-22 22:12:14 +02:00
Mark Qvist 2d81b47b6a Added peering settings to lxmd 2022-10-22 21:25:15 +02:00
Mark Qvist 1c4928a29b Added external processing of received messages to lxmd 2022-10-22 21:07:27 +02:00
Mark Qvist 2181584f69 Added lxmd entry point 2022-10-22 20:26:24 +02:00
Mark Qvist 8bb21688e5 Added config parsing and announce jobs to lxmd 2022-10-22 20:12:54 +02:00
Mark Qvist 8cdf12e866 Added basic LXMF daemon utility 2022-10-22 14:35:44 +02:00
Mark Qvist a1dae1fc15 Updated versions 2022-10-22 14:35:24 +02:00
Mark Qvist 2f43d660d5 Updated version 2022-10-20 20:57:47 +02:00
Mark Qvist 920beaf6f5 Updated dependencies 2022-10-20 20:57:14 +02:00
Mark Qvist 6b28cd8698 Updated dependencies 2022-10-20 14:59:25 +02:00
Mark Qvist 323a968525 Update version and dependencies 2022-10-06 23:38:10 +02:00
20 changed files with 1474 additions and 195 deletions

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
blank_issues_enabled: false
contact_links:
- name: ✨ Feature Request or Idea
url: https://github.com/markqvist/Reticulum/discussions/new?category=ideas
about: Propose and discuss features and ideas
- name: 💬 Questions, Help & Discussion
about: Ask anything, or get help
url: https://github.com/markqvist/Reticulum/discussions/new/choose
- name: 📖 Read the Reticulum Manual
url: https://markqvist.github.io/Reticulum/manual/
about: The complete documentation for Reticulum
+35
View File
@@ -0,0 +1,35 @@
---
name: "\U0001F41B Bug Report"
about: Report a reproducible bug
title: ''
labels: ''
assignees: ''
---
**Read the Contribution Guidelines**
Before creating a bug report on this issue tracker, you **must** read the [Contribution Guidelines](https://github.com/markqvist/Reticulum/blob/master/Contributing.md). Issues that do not follow the contribution guidelines **will be deleted without comment**.
- The issue tracker is used by developers of this project. **Do not use it to ask general questions, or for support requests**.
- Ideas and feature requests can be made on the [Discussions](https://github.com/markqvist/Reticulum/discussions). **Only** feature requests accepted by maintainers and developers are tracked and included on the issue tracker. **Do not post feature requests here**.
- After reading the [Contribution Guidelines](https://github.com/markqvist/Reticulum/blob/master/Contributing.md), delete this section from your bug report.
**Describe the Bug**
A clear and concise description of what the bug is.
**To Reproduce**
Describe in detail how to reproduce the bug.
**Expected Behavior**
A clear and concise description of what you expected to happen.
**Logs & Screenshots**
Please include any relevant log output. If applicable, also add screenshots to help explain your problem.
**System Information**
- OS and version
- Python version
- Program version
**Additional context**
Add any other context about the problem here.
+1
View File
@@ -8,6 +8,7 @@ __pycache__/
*.so
# Distribution / packaging
LXMF/Utilities/LXMF
RNS
.Python
build/
+31
View File
@@ -0,0 +1,31 @@
FROM python:alpine
LABEL authors="Petr Blaha petr.blaha@cleverdata.cz"
USER root
RUN apk update
RUN apk add sdl2_ttf sdl2 build-base libc-dev pkgconfig gstreamer sdl2_mixer sdl2_image sdl2_pango linux-headers mesa-dev py3-virtualenv
RUN addgroup -S myuser && adduser -S -G myuser myuser
USER myuser
WORKDIR /home/myuser
RUN pip install --upgrade pip
ENV PATH="/home/myuser/.local/bin:${PATH}"
################### BEGIN LXMF ###########################################
COPY --chown=myuser:myuser requirements.txt requirements.txt
RUN pip install --user -r requirements.txt
COPY --chown=myuser:myuser . .
#Python create virtual environment
RUN virtualenv /home/myuser/LXMF/venv
RUN source /home/myuser/LXMF/venv/bin/activate
RUN make all
################### END LXMF ###########################################
+6
View File
@@ -0,0 +1,6 @@
# Run docker command one by one(all four), it will build LXMF artifact and copy to dist directory.
# No need to build locally and install dependencies
docker build -t lxmfdockerimage .
docker run -d -it --name lxmfdockercontainer lxmfdockerimage /bin/sh
docker cp lxmfdockercontainer:/home/myuser/dist .
docker rm -f lxmfdockercontainer
+11 -2
View File
@@ -34,11 +34,20 @@ class LXMFPropagationAnnounceHandler:
data = msgpack.unpackb(app_data)
if self.lxmrouter.propagation_node and self.lxmrouter.autopeer:
node_timebase = data[1]
propagation_transfer_limit = None
if len(data) >= 3:
try:
propagation_transfer_limit = float(data[2])
except:
propagation_transfer_limit = None
if data[0] == True:
if RNS.Transport.hops_to(destination_hash) <= self.lxmrouter.autopeer_maxdepth:
self.lxmrouter.peer(destination_hash, data[1])
self.lxmrouter.peer(destination_hash, node_timebase, propagation_transfer_limit)
elif data[0] == False:
self.lxmrouter.unpeer(destination_hash, data[1])
self.lxmrouter.unpeer(destination_hash, node_timebase)
except Exception as e:
RNS.log("Error while evaluating propagation node announce, ignoring announce.", RNS.LOG_DEBUG)
+17 -1
View File
@@ -1 +1,17 @@
APP_NAME = "lxmf"
APP_NAME = "lxmf"
# WARNING! These field specifiers are floating and not
# yet final! Consider highly experiemental, and expect
# them to change in the future! You have been warned :)
FIELD_EMBEDDED_LXMS = 0x01
FIELD_TELEMETRY = 0x02
FIELD_TELEMETRY_STREAM = 0x03
FIELD_ICON_APPEARANCE = 0x04
FIELD_FILE_ATTACHMENTS = 0x05
FIELD_IMAGE = 0x06
FIELD_AUDIO = 0x07
FIELD_THREAD = 0x08
FIELD_COMMANDS = 0x09
FIELD_RESULTS = 0x0A
FIELD_GROUP = 0x0B
+136 -59
View File
@@ -22,7 +22,18 @@ class LXMPeer:
# Maximum amount of time a peer can
# be unreachable before it is removed
MAX_UNREACHABLE = 4*24*60*60
MAX_UNREACHABLE = 14*24*60*60
# Everytime consecutive time a sync
# link fails to establish, add this
# amount off time to wait before the
# next sync is attempted.
SYNC_BACKOFF_STEP = 12*60
# How long to wait for an answer to
# peer path requests before deferring
# sync to later.
PATH_REQUEST_GRACE = 7.5
@staticmethod
def from_bytes(peer_bytes, router):
@@ -32,6 +43,18 @@ class LXMPeer:
peer.peering_timebase = dictionary["peering_timebase"]
peer.alive = dictionary["alive"]
peer.last_heard = dictionary["last_heard"]
if "link_establishment_rate" in dictionary:
peer.link_establishment_rate = dictionary["link_establishment_rate"]
else:
peer.link_establishment_rate = 0
if "propagation_transfer_limit" in dictionary:
try:
peer.propagation_transfer_limit = float(dictionary["propagation_transfer_limit"])
except Exception as e:
peer.propagation_transfer_limit = None
else:
peer.propagation_transfer_limit = None
for transient_id in dictionary["handled_ids"]:
if transient_id in router.propagation_entries:
@@ -49,6 +72,8 @@ class LXMPeer:
dictionary["alive"] = self.alive
dictionary["last_heard"] = self.last_heard
dictionary["destination_hash"] = self.destination_hash
dictionary["link_establishment_rate"] = self.link_establishment_rate
dictionary["propagation_transfer_limit"] = self.propagation_transfer_limit
handled_ids = []
for transient_id in self.handled_messages:
@@ -66,13 +91,19 @@ class LXMPeer:
def __init__(self, router, destination_hash):
self.alive = False
self.last_heard = 0
self.next_sync_attempt = 0
self.last_sync_attempt = 0
self.sync_backoff = 0
self.peering_timebase = 0
self.link_establishment_rate = 0
self.propagation_transfer_limit = None
self.link = None
self.state = LXMPeer.IDLE
self.unhandled_messages = {}
self.handled_messages = {}
self.last_offer = []
self.router = router
self.destination_hash = destination_hash
@@ -81,54 +112,89 @@ class LXMPeer:
def sync(self):
RNS.log("Initiating LXMF Propagation Node sync with peer "+RNS.prettyhexrep(self.destination_hash), RNS.LOG_DEBUG)
self.last_sync_attempt = time.time()
if not RNS.Transport.has_path(self.destination_hash):
RNS.log("No path to peer "+RNS.prettyhexrep(self.destination_hash)+" exists, requesting...", RNS.LOG_DEBUG)
RNS.Transport.request_path(self.destination_hash)
RNS.log("Path requested, retrying sync later", RNS.LOG_DEBUG)
else:
if self.identity == None:
self.identity = RNS.Identity.recall(destination_hash)
self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
if time.time() > self.next_sync_attempt:
if not RNS.Transport.has_path(self.destination_hash):
RNS.log("No path to peer "+RNS.prettyhexrep(self.destination_hash)+" exists, requesting...", RNS.LOG_DEBUG)
RNS.Transport.request_path(self.destination_hash)
time.sleep(LXMPeer.PATH_REQUEST_GRACE)
if self.identity != None:
if len(self.unhandled_messages) > 0:
if self.state == LXMPeer.IDLE:
RNS.log("Establishing link for sync to peer "+RNS.prettyhexrep(self.destination_hash)+"...", RNS.LOG_DEBUG)
self.link = RNS.Link(self.destination, established_callback = self.link_established, closed_callback = self.link_closed)
self.state = LXMPeer.LINK_ESTABLISHING
else:
if self.state == LXMPeer.LINK_READY:
self.alive = True
self.last_heard = time.time()
RNS.log("Synchronisation link to peer "+RNS.prettyhexrep(self.destination_hash)+" established, preparing request...", RNS.LOG_DEBUG)
unhandled_ids = []
purged_ids = []
for transient_id in self.unhandled_messages:
if transient_id in self.router.propagation_entries:
unhandled_ids.append(transient_id)
else:
purged_ids.append(transient_id)
for transient_id in purged_ids:
RNS.log("Dropping unhandled message "+RNS.prettyhexrep(transient_id)+" for peer "+RNS.prettyhexrep(self.destination_hash)+" since it no longer exists in the message store.", RNS.LOG_DEBUG)
self.unhandled_messages.pop(transient_id)
RNS.log("Sending sync request to peer "+str(self.destination), RNS.LOG_DEBUG)
self.link.request(LXMPeer.OFFER_REQUEST_PATH, unhandled_ids, response_callback=self.offer_response, failed_callback=self.request_failed)
self.state = LXMPeer.REQUEST_SENT
if not RNS.Transport.has_path(self.destination_hash):
RNS.log("Path request was not answered, retrying sync with peer "+RNS.prettyhexrep(self.destination_hash)+" later", RNS.LOG_DEBUG)
else:
RNS.log("Could not request sync to peer "+RNS.prettyhexrep(self.destination_hash)+" since its identity could not be recalled.", RNS.LOG_ERROR)
if self.identity == None:
self.identity = RNS.Identity.recall(destination_hash)
self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
if self.identity != None:
if len(self.unhandled_messages) > 0:
if self.state == LXMPeer.IDLE:
RNS.log("Establishing link for sync to peer "+RNS.prettyhexrep(self.destination_hash)+"...", RNS.LOG_DEBUG)
self.sync_backoff += LXMPeer.SYNC_BACKOFF_STEP
self.next_sync_attempt = time.time() + self.sync_backoff
self.link = RNS.Link(self.destination, established_callback = self.link_established, closed_callback = self.link_closed)
self.state = LXMPeer.LINK_ESTABLISHING
else:
if self.state == LXMPeer.LINK_READY:
self.alive = True
self.last_heard = time.time()
self.sync_backoff = 0
RNS.log("Synchronisation link to peer "+RNS.prettyhexrep(self.destination_hash)+" established, preparing request...", RNS.LOG_DEBUG)
unhandled_entries = []
unhandled_ids = []
purged_ids = []
for transient_id in self.unhandled_messages:
if transient_id in self.router.propagation_entries:
unhandled_entry = [
transient_id,
self.router.get_weight(transient_id),
self.router.get_size(transient_id),
]
unhandled_entries.append(unhandled_entry)
else:
purged_ids.append(transient_id)
for transient_id in purged_ids:
RNS.log("Dropping unhandled message "+RNS.prettyhexrep(transient_id)+" for peer "+RNS.prettyhexrep(self.destination_hash)+" since it no longer exists in the message store.", RNS.LOG_DEBUG)
self.unhandled_messages.pop(transient_id)
unhandled_entries.sort(key=lambda e: e[1], reverse=False)
per_message_overhead = 16 # Really only 2 bytes, but set a bit higher for now
cumulative_size = 24 # Initialised to highest reasonable binary structure overhead
for unhandled_entry in unhandled_entries:
transient_id = unhandled_entry[0]
weight = unhandled_entry[1]
lxm_size = unhandled_entry[2]
next_size = cumulative_size + (lxm_size+per_message_overhead)
if self.propagation_transfer_limit != None and next_size > (self.propagation_transfer_limit*1000):
pass
else:
cumulative_size += (lxm_size+per_message_overhead)
unhandled_ids.append(transient_id)
RNS.log("Sending sync request to peer "+str(self.destination), RNS.LOG_DEBUG)
self.last_offer = unhandled_ids
self.link.request(LXMPeer.OFFER_REQUEST_PATH, self.last_offer, response_callback=self.offer_response, failed_callback=self.request_failed)
self.state = LXMPeer.REQUEST_SENT
else:
RNS.log("Could not request sync to peer "+RNS.prettyhexrep(self.destination_hash)+" since its identity could not be recalled.", RNS.LOG_ERROR)
else:
RNS.log("Postponing sync with peer "+RNS.prettyhexrep(self.destination_hash)+" for "+RNS.prettytime(self.next_sync_attempt-time.time())+" due to previous failures", RNS.LOG_DEBUG)
if self.last_sync_attempt > self.last_heard:
self.alive = False
def request_failed(self, request_receipt):
RNS.log("Sync request to peer "+str(self.destination)+" failed", RNS.LOG_DEBUG)
if self.link != None:
self.link.teardown()
else:
self.state = LXMPeer.IDLE
self.state = LXMPeer.IDLE
def offer_response(self, request_receipt):
try:
@@ -141,33 +207,31 @@ class LXMPeer:
if response == LXMPeer.ERROR_NO_IDENTITY:
if self.link != None:
RNS.log("Remote peer indicated that no identification was received, retrying...", RNS.LOG_DEBUG)
self.link.indentify()
self.link.identify()
self.state = LXMPeer.LINK_READY
self.sync()
elif response == False:
# Peer already has all advertised messages
for transient_id in self.unhandled_messages:
message_entry = self.unhandled_messages[transient_id]
self.handled_messages[transient_id] = message_entry
self.unhandled_messages = {}
for transient_id in self.last_offer:
if transient_id in self.unhandled_messages:
self.handled_messages[transient_id] = self.unhandled_messages.pop(transient_id)
elif response == True:
# Peer wants all advertised messages
for transient_id in self.unhandled_messages:
for transient_id in self.last_offer:
wanted_messages.append(self.unhandled_messages[transient_id])
wanted_message_ids.append(transient_id)
else:
# Peer wants some advertised messages
peer_had_messages = []
for transient_id in self.unhandled_messages.copy():
for transient_id in self.last_offer.copy():
# If the peer did not want the message, it has
# already received it from another peer.
if not transient_id in response:
message_entry = self.unhandled_messages.pop(transient_id)
self.handled_messages[transient_id] = message_entry
if transient_id in self.unhandled_messages:
self.handled_messages[transient_id] = self.unhandled_messages.pop(transient_id)
for transient_id in response:
wanted_messages.append(self.unhandled_messages[transient_id])
@@ -190,7 +254,13 @@ class LXMPeer:
resource = RNS.Resource(data, self.link, callback = self.resource_concluded)
resource.transferred_messages = wanted_message_ids
self.state = LXMPeer.RESOURCE_TRANSFERRING
else:
RNS.log("Peer "+RNS.prettyhexrep(self.destination_hash)+" did not request any of the available messages, sync completed", RNS.LOG_DEBUG)
if self.link != None:
self.link.teardown()
self.link = None
self.state = LXMPeer.IDLE
except Exception as e:
@@ -203,29 +273,38 @@ class LXMPeer:
self.link = None
self.state = LXMPeer.IDLE
def resource_concluded(self, resource):
if resource.status == RNS.Resource.COMPLETE:
for transient_id in resource.transferred_messages:
message = self.unhandled_messages.pop(transient_id)
self.handled_messages[transient_id] = message
if self.link != None:
self.link.teardown()
self.link = None
self.state = LXMPeer.IDLE
self.link.teardown()
RNS.log("Sync to peer "+RNS.prettyhexrep(self.destination_hash)+" completed", RNS.LOG_DEBUG)
self.alive = True
self.last_heard = time.time()
else:
RNS.log("Resource transfer for LXMF peer sync failed to "+str(self.destination), RNS.LOG_DEBUG)
if self.link != None:
self.link.teardown()
else:
self.state = LXMPeer.IDLE
self.link = None
self.state = LXMPeer.IDLE
def link_established(self, link):
self.link.identify(self.router.identity)
link_establishment_rate = link.get_establishment_rate()
if link_establishment_rate != None:
self.link_establishment_rate = link_establishment_rate
self.state = LXMPeer.LINK_READY
self.next_sync_attempt = 0
self.sync()
def link_closed(self, link):
@@ -234,8 +313,6 @@ class LXMPeer:
def handle_message(self, transient_id):
if not transient_id in self.handled_messages and not transient_id in self.unhandled_messages:
# TODO: Remove at some point
RNS.log("The message "+RNS.prettyhexrep(transient_id)+" was added to distribution queue for "+RNS.prettyhexrep(self.destination_hash), RNS.LOG_EXTREME)
self.unhandled_messages[transient_id] = self.router.propagation_entries[transient_id]
def __str__(self):
+363 -91
View File
@@ -1,6 +1,7 @@
import os
import time
import random
import base64
import atexit
import threading
@@ -15,11 +16,12 @@ from .Handlers import LXMFDeliveryAnnounceHandler
from .Handlers import LXMFPropagationAnnounceHandler
class LXMRouter:
MAX_DELIVERY_ATTEMPTS = 4
PROCESSING_INTERVAL = 5
DELIVERY_RETRY_WAIT = 12
PATH_REQUEST_WAIT = 5
MAX_DELIVERY_ATTEMPTS = 5
PROCESSING_INTERVAL = 4
DELIVERY_RETRY_WAIT = 10
PATH_REQUEST_WAIT = 7
LINK_MAX_INACTIVITY = 10*60
P_LINK_MAX_INACTIVITY = 3*60
MESSAGE_EXPIRY = 30*24*60*60
@@ -27,27 +29,37 @@ class LXMRouter:
AUTOPEER = True
AUTOPEER_MAXDEPTH = 4
FASTEST_N_RANDOM_POOL = 2
PR_PATH_TIMEOUT = 10
PROPAGATION_LIMIT = 256
DELIVERY_LIMIT = 1000
PR_IDLE = 0x00
PR_PATH_REQUESTED = 0x01
PR_LINK_ESTABLISHING = 0x02
PR_LINK_ESTABLISHED = 0x03
PR_REQUEST_SENT = 0x04
PR_RECEIVING = 0x05
PR_RESPONSE_RECEIVED = 0x06
PR_COMPLETE = 0x07
PR_NO_IDENTITY_RCVD = 0xf0
PR_NO_ACCESS = 0xf1
PR_PATH_TIMEOUT = 10
PR_ALL_MESSAGES = 0x00
PR_IDLE = 0x00
PR_PATH_REQUESTED = 0x01
PR_LINK_ESTABLISHING = 0x02
PR_LINK_ESTABLISHED = 0x03
PR_REQUEST_SENT = 0x04
PR_RECEIVING = 0x05
PR_RESPONSE_RECEIVED = 0x06
PR_COMPLETE = 0x07
PR_NO_PATH = 0xf0
PR_LINK_FAILED = 0xf1
PR_TRANSFER_FAILED = 0xf2
PR_NO_IDENTITY_RCVD = 0xf3
PR_NO_ACCESS = 0xf4
PR_FAILED = 0xfe
PR_ALL_MESSAGES = 0x00
### Developer-facing API ##############################
#######################################################
def __init__(self, identity = None, storagepath = None, autopeer = AUTOPEER, autopeer_maxdepth = AUTOPEER_MAXDEPTH):
def __init__(self, identity = None, storagepath = None, autopeer = AUTOPEER, autopeer_maxdepth = None,
propagation_limit = PROPAGATION_LIMIT, delivery_limit = DELIVERY_LIMIT):
random.seed(os.urandom(10))
self.pending_inbound = []
@@ -60,6 +72,7 @@ class LXMRouter:
self.ignored_list = []
self.allowed_list = []
self.auth_required = False
self.retain_synced_on_node = False
self.processing_outbound = False
self.processing_inbound = False
@@ -77,6 +90,8 @@ class LXMRouter:
self.message_storage_limit = None
self.information_storage_limit = None
self.propagation_per_transfer_limit = propagation_limit
self.delivery_per_transfer_limit = delivery_limit
self.wants_download_on_path_available_from = None
self.wants_download_on_path_available_to = None
@@ -84,7 +99,9 @@ class LXMRouter:
self.propagation_transfer_progress = 0.0
self.propagation_transfer_last_result = None
self.propagation_transfer_max_messages = None
self.active_propagation_links = []
self.locally_delivered_transient_ids = {}
self.locally_processed_transient_ids = {}
if identity == None:
identity = RNS.Identity()
@@ -93,12 +110,18 @@ class LXMRouter:
self.lxmf_query_destination = RNS.Destination(None, RNS.Destination.IN, RNS.Destination.PLAIN, APP_NAME, "query")
self.propagation_destination = RNS.Destination(self.identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, "propagation")
self.autopeer = autopeer
self.autopeer_maxdepth = autopeer_maxdepth
if autopeer != None:
self.autopeer = autopeer
else:
self.autopeer = LXMRouter.AUTOPEER
if autopeer_maxdepth != None:
self.autopeer_maxdepth = autopeer_maxdepth
else:
self.autopeer_maxdepth = LXMRouter.AUTOPEER_MAXDEPTH
self.peers = {}
self.propagation_entries = {}
self.propagated_ids = {}
RNS.Transport.register_announce_handler(LXMFDeliveryAnnounceHandler(self))
RNS.Transport.register_announce_handler(LXMFPropagationAnnounceHandler(self))
@@ -111,7 +134,14 @@ class LXMRouter:
data = locally_delivered_file.read()
self.locally_delivered_transient_ids = msgpack.unpackb(data)
locally_delivered_file.close()
self.clean_transient_id_cache()
if os.path.isfile(self.storagepath+"/locally_processed"):
locally_processed_file = open(self.storagepath+"/locally_processed", "rb")
data = locally_processed_file.read()
self.locally_processed_transient_ids = msgpack.unpackb(data)
locally_processed_file.close()
self.clean_transient_id_caches()
except Exception as e:
RNS.log("Could not load locally delivered message ID cache from storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
@@ -130,7 +160,13 @@ class LXMRouter:
def announce_propagation_node(self):
def delayed_announce():
time.sleep(LXMRouter.NODE_ANNOUNCE_DELAY)
data = msgpack.packb([self.propagation_node, int(time.time())])
announce_data = [
self.propagation_node, # Boolean flag signalling propagation node state
int(time.time()), # Current node timebase
self.propagation_per_transfer_limit, # Per-transfer limit for message propagation in kilobytes
]
data = msgpack.packb(announce_data)
self.propagation_destination.announce(app_data=data)
da_thread = threading.Thread(target=delayed_announce)
@@ -138,7 +174,7 @@ class LXMRouter:
da_thread.start()
def register_delivery_identity(self, identity, display_name = None):
delivery_destination = RNS.Destination(identity, RNS.Destination.IN, RNS.Destination.SINGLE, "lxmf", "delivery")
delivery_destination = RNS.Destination(identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, "delivery")
delivery_destination.set_packet_callback(self.delivery_packet)
delivery_destination.set_link_established_callback(self.delivery_link_established)
delivery_destination.display_name = display_name
@@ -165,6 +201,12 @@ class LXMRouter:
def get_outbound_propagation_node(self):
return self.outbound_propagation_node
def set_retain_node_lxms(self, retain):
if retain == True:
self.retain_synced_on_node = True
else:
self.retain_synced_on_node = False
def set_authentication(self, required=None):
if required != None:
self.auth_required = required
@@ -204,15 +246,15 @@ class LXMRouter:
if max_messages == None:
max_messages = LXMRouter.PR_ALL_MESSAGES
self.propagation_transfer_progress = 0.0
self.propagation_transfer_max_messages = max_messages
if self.outbound_propagation_node != None:
self.propagation_transfer_progress = 0.0
if self.outbound_propagation_link != None and self.outbound_propagation_link.status == RNS.Link.ACTIVE:
self.propagation_transfer_state = LXMRouter.PR_LINK_ESTABLISHED
self.outbound_propagation_link.identify(identity)
self.outbound_propagation_link.request(
LXMPeer.MESSAGE_GET_PATH,
[None, None],
[None, None], # Set both want and have fields to None to get message list
response_callback=self.message_list_response,
failed_callback=self.message_get_failed
)
@@ -297,7 +339,10 @@ class LXMRouter:
peer = LXMPeer.from_bytes(serialised_peer, self)
if peer.identity != None:
self.peers[peer.destination_hash] = peer
RNS.log("Loaded peer "+RNS.prettyhexrep(peer.destination_hash)+" with "+str(len(peer.unhandled_messages))+" unhandled messages", RNS.LOG_DEBUG)
lim_str = ", no transfer limit"
if peer.propagation_transfer_limit != None:
lim_str = ", "+RNS.prettysize(peer.propagation_transfer_limit*1000)+" transfer limit"
RNS.log("Loaded peer "+RNS.prettyhexrep(peer.destination_hash)+" with "+str(len(peer.unhandled_messages))+" unhandled messages"+lim_str, RNS.LOG_DEBUG)
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)
@@ -417,7 +462,7 @@ class LXMRouter:
self.clean_links()
if self.processing_count % LXMRouter.JOB_TRANSIENT_INTERVAL == 0:
self.clean_transient_id_cache()
self.clean_transient_id_caches()
if self.processing_count % LXMRouter.JOB_STORE_INTERVAL == 0:
self.clean_message_store()
@@ -429,7 +474,12 @@ class LXMRouter:
while (True):
# TODO: Improve this to scheduling, so manual
# triggers can delay next run
self.jobs()
try:
self.jobs()
except Exception as e:
RNS.log("An error ocurred while running LXMF Router jobs.", RNS.LOG_ERROR)
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
time.sleep(LXMRouter.PROCESSING_INTERVAL)
def clean_links(self):
@@ -446,23 +496,77 @@ class LXMRouter:
cleaned_link = self.direct_links.pop(link_hash)
RNS.log("Cleaned link "+str(cleaned_link), RNS.LOG_DEBUG)
try:
inactive_links = []
for link in self.active_propagation_links:
if link.no_data_for() > LXMRouter.P_LINK_MAX_INACTIVITY:
inactive_links.append(link)
for link in inactive_links:
self.active_propagation_links.remove(link)
link.teardown()
except Exception as e:
RNS.log("An error occurred while cleaning inbound propagation links. The contained exception was: "+str(e), RNS.LOG_ERROR)
if self.outbound_propagation_link != None and self.outbound_propagation_link.status == RNS.Link.CLOSED:
self.outbound_propagation_link = None
self.acknowledge_sync_completion()
if self.propagation_transfer_state == LXMRouter.PR_COMPLETE:
self.acknowledge_sync_completion()
elif self.propagation_transfer_state < LXMRouter.PR_LINK_ESTABLISHED:
self.acknowledge_sync_completion(failure_state=LXMRouter.PR_LINK_FAILED)
elif self.propagation_transfer_state >= LXMRouter.PR_LINK_ESTABLISHED and self.propagation_transfer_state < LXMRouter.PR_COMPLETE:
self.acknowledge_sync_completion(failure_state=LXMRouter.PR_TRANSFER_FAILED)
else:
RNS.log(f"Unknown propagation transfer state on link cleaning: {self.propagation_transfer_state}", RNS.LOG_DEBUG)
self.acknowledge_sync_completion()
RNS.log("Cleaned outbound propagation link", RNS.LOG_DEBUG)
def clean_transient_id_cache(self):
def clean_transient_id_caches(self):
now = time.time()
removed_entries = []
for transient_id in self.locally_delivered_transient_ids:
timestamp = self.locally_delivered_transient_ids[transient_id]
if now > timestamp+LXMRouter.MESSAGE_EXPIRY*1.1:
if now > timestamp+LXMRouter.MESSAGE_EXPIRY*1.25:
removed_entries.append(transient_id)
for transient_id in removed_entries:
self.locally_delivered_transient_ids.pop(transient_id)
RNS.log("Cleaned "+RNS.prettyhexrep(transient_id)+" from local delivery cache", RNS.LOG_DEBUG)
removed_entries = []
for transient_id in self.locally_processed_transient_ids:
timestamp = self.locally_processed_transient_ids[transient_id]
if now > timestamp+LXMRouter.MESSAGE_EXPIRY*1.25:
removed_entries.append(transient_id)
for transient_id in removed_entries:
self.locally_processed_transient_ids.pop(transient_id)
RNS.log("Cleaned "+RNS.prettyhexrep(transient_id)+" from locally processed cache", RNS.LOG_DEBUG)
def get_weight(self, transient_id):
dst_hash = self.propagation_entries[transient_id][0]
lxm_rcvd = self.propagation_entries[transient_id][2]
lxm_size = self.propagation_entries[transient_id][3]
now = time.time()
age_weight = max(1, (now - lxm_rcvd)/60/60/24/4)
if dst_hash in self.prioritised_list:
priority_weight = 0.1
else:
priority_weight = 1.0
weight = priority_weight * age_weight * lxm_size
return weight
def get_size(self, transient_id):
lxm_size = self.propagation_entries[transient_id][3]
return lxm_size
def clean_message_store(self):
# Check and remove expired messages
now = time.time()
@@ -504,22 +608,13 @@ class LXMRouter:
bytes_needed = message_storage_size - self.message_storage_limit
bytes_cleaned = 0
now = time.time()
weighted_entries = []
for transient_id in self.propagation_entries:
entry = self.propagation_entries[transient_id]
dst_hash = entry[0]
lxm_rcvd = entry[2]
lxm_size = entry[3]
age_weight = max(1, (now - lxm_rcvd)/60/60/24/4)
if dst_hash in self.prioritised_list:
priority_weight = 0.1
else:
priority_weight = 1.0
weight = priority_weight * age_weight * lxm_size
weighted_entries.append([entry, weight, transient_id])
weighted_entries.append([
self.propagation_entries[transient_id],
self.get_weight(transient_id),
transient_id
])
weighted_entries.sort(key=lambda we: we[1], reverse=True)
@@ -545,13 +640,36 @@ class LXMRouter:
finally:
i += 1
RNS.log("LXMF message store size is now "+RNS.prettysize(self.message_storage_size()), RNS.LOG_EXTREME)
RNS.log("PE len "+str(len(self.propagation_entries)))
RNS.log("LXMF message store size is now "+RNS.prettysize(self.message_storage_size())+" for "+str(len(self.propagation_entries))+" items", RNS.LOG_EXTREME)
except Exception as e:
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):
try:
if not os.path.isdir(self.storagepath):
os.makedirs(self.storagepath)
locally_delivered_file = open(self.storagepath+"/local_deliveries", "wb")
locally_delivered_file.write(msgpack.packb(self.locally_delivered_transient_ids))
locally_delivered_file.close()
except Exception as e:
RNS.log("Could not save locally delivered message ID cache to storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
def save_locally_processed_transient_ids(self):
try:
if not os.path.isdir(self.storagepath):
os.makedirs(self.storagepath)
locally_processed_file = open(self.storagepath+"/locally_processed", "wb")
locally_processed_file.write(msgpack.packb(self.locally_processed_transient_ids))
locally_processed_file.close()
except Exception as e:
RNS.log("Could not save locally processed message ID cache to storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
def exit_handler(self):
if self.propagation_node:
try:
@@ -569,16 +687,8 @@ class LXMRouter:
except Exception as e:
RNS.log("Could not save propagation node peers to storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
try:
if not os.path.isdir(self.storagepath):
os.makedirs(self.storagepath)
locally_delivered_file = open(self.storagepath+"/local_deliveries", "wb")
locally_delivered_file.write(msgpack.packb(self.locally_delivered_transient_ids))
locally_delivered_file.close()
except Exception as e:
RNS.log("Could not save locally delivered message ID cache to storage. The contained exception was: "+str(e), RNS.LOG_ERROR)
self.save_locally_delivered_transient_ids()
self.save_locally_processed_transient_ids()
def __str__(self):
return "<LXMRouter "+RNS.hexrep(self.identity.hash, delimit=False)+">"
@@ -593,14 +703,15 @@ class LXMRouter:
job_thread.start()
def __request_messages_path_job(self):
while not RNS.Transport.has_path(self.wants_download_on_path_available_from) and time.time() < self.wants_download_on_path_available_timeout:
path_timeout = self.wants_download_on_path_available_timeout
while not RNS.Transport.has_path(self.wants_download_on_path_available_from) and time.time() < path_timeout:
time.sleep(0.1)
if RNS.Transport.has_path(self.wants_download_on_path_available_from):
self.request_messages_from_propagation_node(self.wants_download_on_path_available_to, self.propagation_transfer_max_messages)
else:
RNS.log("Propagation node path request timed out", RNS.LOG_DEBUG)
self.acknowledge_sync_completion()
self.acknowledge_sync_completion(failure_state=LXMRouter.PR_NO_PATH)
def identity_allowed(self, identity):
if self.auth_required:
@@ -660,6 +771,16 @@ class LXMRouter:
# Process wanted messages
response_messages = []
if data[0] != None and len(data[0]) > 0:
client_transfer_limit = None
if len(data) >= 3:
try:
client_transfer_limit = float(data[2])*1000
RNS.log("Client indicates transfer limit of "+RNS.prettysize(client_transfer_limit), RNS.LOG_DEBUG)
except:
pass
per_message_overhead = 16 # Really only 2 bytes, but set a bit higher for now
cumulative_size = 24 # Initialised to highest reasonable binary structure overhead
for transient_id in data[0]:
if transient_id in self.propagation_entries and self.propagation_entries[transient_id][0] == remote_destination.hash:
try:
@@ -668,9 +789,17 @@ class LXMRouter:
message_file = open(filepath, "rb")
lxmf_data = message_file.read()
response_messages.append(lxmf_data)
message_file.close()
lxm_size = len(lxmf_data)
next_size = cumulative_size + (lxm_size+per_message_overhead)
if client_transfer_limit != None and next_size > client_transfer_limit:
pass
else:
response_messages.append(lxmf_data)
cumulative_size += (lxm_size+per_message_overhead)
except Exception as e:
RNS.log("Error while processing message download request from "+RNS.prettyhexrep(remote_destination.hash)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
@@ -700,7 +829,7 @@ class LXMRouter:
wants = []
if len(request_receipt.response) > 0:
for transient_id in request_receipt.response:
if self.has_message(transient_id):
if not self.retain_synced_on_node and self.has_message(transient_id):
haves.append(transient_id)
else:
if self.propagation_transfer_max_messages == LXMRouter.PR_ALL_MESSAGES or len(wants) < self.propagation_transfer_max_messages:
@@ -708,7 +837,7 @@ class LXMRouter:
request_receipt.link.request(
LXMPeer.MESSAGE_GET_PATH,
[wants, haves],
[wants, haves, self.delivery_per_transfer_limit],
response_callback=self.message_get_response,
failed_callback=self.message_get_failed,
progress_callback=self.message_get_progress
@@ -723,6 +852,14 @@ class LXMRouter:
RNS.log("Propagation node indicated missing identification on get request, tearing down link.", RNS.LOG_DEBUG)
if self.outbound_propagation_link != None:
self.outbound_propagation_link.teardown()
self.propagation_transfer_state = LXMRouter.PR_NO_IDENTITY_RCVD
elif request_receipt.response == LXMPeer.ERROR_NO_ACCESS:
RNS.log("Propagation node did not allow get request, tearing down link.", RNS.LOG_DEBUG)
if self.outbound_propagation_link != None:
self.outbound_propagation_link.teardown()
self.propagation_transfer_state = LXMRouter.PR_NO_ACCESS
else:
if request_receipt.response != None and len(request_receipt.response) > 0:
haves = []
@@ -744,6 +881,7 @@ class LXMRouter:
self.propagation_transfer_state = LXMRouter.PR_COMPLETE
self.propagation_transfer_progress = 1.0
self.propagation_transfer_last_result = len(request_receipt.response)
self.save_locally_delivered_transient_ids()
def message_get_progress(self, request_receipt):
self.propagation_transfer_state = LXMRouter.PR_RECEIVING
@@ -754,12 +892,15 @@ class LXMRouter:
if self.outbound_propagation_link != None:
self.outbound_propagation_link.teardown()
def acknowledge_sync_completion(self, reset_state=False):
def acknowledge_sync_completion(self, reset_state=False, failure_state=None):
self.propagation_transfer_last_result = None
if reset_state or self.propagation_transfer_state <= LXMRouter.PR_COMPLETE:
self.propagation_transfer_state = LXMRouter.PR_IDLE
if failure_state == None:
self.propagation_transfer_state = LXMRouter.PR_IDLE
else:
self.propagation_transfer_state = failure_state
self.propagation_transfer_progress = 0.0
self.propagation_transfer_last_result = None
self.wants_download_on_path_available_from = None
self.wants_download_on_path_available_to = None
@@ -768,10 +909,6 @@ class LXMRouter:
return True
else:
return False
### Message Routing & Delivery ########################
#######################################################
def handle_outbound(self, lxmessage):
lxmessage.state = LXMessage.OUTBOUND
@@ -786,10 +923,26 @@ class LXMRouter:
self.pending_outbound.append(lxmessage)
self.process_outbound()
def lxmf_delivery(self, lxmf_data, destination_type = None):
def get_outbound_progress(self, lxm_hash):
for lxm in self.pending_outbound:
if lxm.hash == lxm_hash:
return lxm.progress
return None
### Message Routing & Delivery ########################
#######################################################
def lxmf_delivery(self, lxmf_data, destination_type = None, phy_stats = None):
try:
message = LXMessage.unpack_from_bytes(lxmf_data)
if phy_stats != None:
if "rssi" in phy_stats: message.rssi = phy_stats["rssi"]
if "snr" in phy_stats: message.snr = phy_stats["snr"]
if "q" in phy_stats: message.q = phy_stats["q"]
if destination_type == RNS.Destination.SINGLE:
message.transport_encrypted = True
message.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_EC
@@ -807,6 +960,12 @@ class LXMRouter:
RNS.log(str(self)+" ignored message from "+RNS.prettyhexrep(message.source_hash), RNS.LOG_DEBUG)
return False
if 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:
self.locally_delivered_transient_ids[message.hash] = time.time()
if self.__delivery_callback != None and callable(self.__delivery_callback):
try:
self.__delivery_callback(message)
@@ -829,7 +988,16 @@ class LXMRouter:
else:
lxmf_data = data
if self.lxmf_delivery(lxmf_data, packet.destination_type):
try:
reticulum = RNS.Reticulum.get_instance()
if packet.rssi == None: packet.rssi = reticulum.get_packet_rssi(packet.packet_hash)
if packet.snr == None: packet.snr = reticulum.get_packet_snr(packet.packet_hash)
if packet.q == None: packet.q = reticulum.get_packet_q(packet.packet_hash)
except Exception as e:
RNS.log("Error while retrieving physical link stats for LXMF delivery packet: "+str(e), RNS.LOG_ERROR)
phy_stats = {"rssi": packet.rssi, "snr": packet.snr, "q": packet.q}
if self.lxmf_delivery(lxmf_data, packet.destination_type, phy_stats=phy_stats):
packet.prove()
except Exception as e:
@@ -837,8 +1005,10 @@ class LXMRouter:
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
def delivery_link_established(self, link):
link.track_phy_stats(True)
link.set_packet_callback(self.delivery_packet)
link.set_resource_strategy(RNS.Link.ACCEPT_ALL)
link.set_resource_strategy(RNS.Link.ACCEPT_APP)
link.set_resource_callback(self.delivery_resource_advertised)
link.set_resource_started_callback(self.resource_transfer_began)
link.set_resource_concluded_callback(self.delivery_resource_concluded)
@@ -848,25 +1018,41 @@ class LXMRouter:
def resource_transfer_began(self, resource):
RNS.log("Transfer began for LXMF delivery resource "+str(resource), RNS.LOG_DEBUG)
def delivery_resource_advertised(self, resource):
size = resource.get_data_size()
limit = self.delivery_per_transfer_limit*1000
if limit != None and size > limit:
RNS.log("Rejecting "+RNS.prettysize(size)+" incoming LXMF delivery resource, since it exceeds the limit of "+RNS.prettysize(limit), RNS.LOG_DEBUG)
return False
else:
return True
def delivery_resource_concluded(self, resource):
RNS.log("Transfer concluded for LXMF delivery resource "+str(resource), RNS.LOG_DEBUG)
if resource.status == RNS.Resource.COMPLETE:
self.lxmf_delivery(resource.data.read(), resource.link.type)
phy_stats = {"rssi": resource.link.rssi, "snr": resource.link.snr, "q": resource.link.q}
self.lxmf_delivery(resource.data.read(), resource.link.type, phy_stats=phy_stats)
### Peer Sync & Propagation ###########################
#######################################################
def peer(self, destination_hash, timestamp):
def peer(self, destination_hash, timestamp, propagation_transfer_limit):
if destination_hash in self.peers:
peer = self.peers[destination_hash]
peer.alive = True
peer.peering_timebase = timestamp
peer.last_heard = time.time()
if timestamp > peer.peering_timebase:
peer.alive = True
peer.sync_backoff = 0
peer.next_sync_attempt = 0
peer.peering_timebase = timestamp
peer.last_heard = time.time()
peer.propagation_transfer_limit = propagation_transfer_limit
else:
peer = LXMPeer(self, destination_hash)
peer.alive = True
peer.last_heard = time.time()
peer.propagation_transfer_limit = propagation_transfer_limit
self.peers[destination_hash] = peer
RNS.log("Peered with "+str(peer.destination))
@@ -884,18 +1070,50 @@ class LXMRouter:
def sync_peers(self):
culled_peers = []
waiting_peers = []
unresponsive_peers = []
for peer_id in self.peers:
peer = self.peers[peer_id]
if time.time() > peer.last_heard + LXMPeer.MAX_UNREACHABLE:
culled_peers.append(peer_id)
else:
if peer.state == LXMPeer.IDLE and len(peer.unhandled_messages) > 0:
waiting_peers.append(peer)
if peer.alive:
waiting_peers.append(peer)
else:
if hasattr(peer, "next_sync_attempt") and time.time() > peer.next_sync_attempt:
unresponsive_peers.append(peer)
else:
pass
# RNS.log("Not adding peer "+str(peer)+" since it is in sync backoff", RNS.LOG_DEBUG)
peer_pool = []
if len(waiting_peers) > 0:
RNS.log("Randomly selecting peer to sync from "+str(len(waiting_peers))+" waiting peers.", RNS.LOG_DEBUG)
selected_index = random.randint(0,len(waiting_peers)-1)
selected_peer = waiting_peers[selected_index]
fastest_peers = sorted(
waiting_peers,
key=lambda p: p.link_establishment_rate,
reverse=True
)[0:min(LXMRouter.FASTEST_N_RANDOM_POOL, len(waiting_peers))]
peer_pool.extend(fastest_peers)
unknown_speed_peers = [p for p in waiting_peers if p.link_establishment_rate == 0]
if len(unknown_speed_peers) > 0:
peer_pool.extend(
unknown_speed_peers[
0:min(
len(unknown_speed_peers),
len(fastest_peers)
)]
)
RNS.log("Selecting peer to sync from "+str(len(waiting_peers))+" waiting peers.", RNS.LOG_DEBUG)
elif len(unresponsive_peers) > 0:
RNS.log("No active peers available, randomly selecting peer to sync from "+str(len(unresponsive_peers))+" unresponsive peers.", RNS.LOG_DEBUG)
peer_pool = unresponsive_peers
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)
selected_peer.sync()
@@ -909,9 +1127,20 @@ class LXMRouter:
def propagation_link_established(self, link):
link.set_packet_callback(self.propagation_packet)
link.set_resource_strategy(RNS.Link.ACCEPT_ALL)
link.set_resource_strategy(RNS.Link.ACCEPT_APP)
link.set_resource_callback(self.propagation_resource_advertised)
link.set_resource_started_callback(self.resource_transfer_began)
link.set_resource_concluded_callback(self.propagation_resource_concluded)
self.active_propagation_links.append(link)
def propagation_resource_advertised(self, resource):
size = resource.get_data_size()
limit = self.propagation_per_transfer_limit*1000
if limit != None and size > limit:
RNS.log("Rejecting "+RNS.prettysize(size)+" incoming LXMF propagation resource, since it exceeds the limit of "+RNS.prettysize(limit), RNS.LOG_DEBUG)
return False
else:
return True
def propagation_packet(self, data, packet):
try:
@@ -931,7 +1160,7 @@ class LXMRouter:
RNS.log("Exception occurred while parsing incoming LXMF propagation data.", RNS.LOG_ERROR)
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
def offer_request(self, path, data, request_id, remote_identity, requested_at):
def offer_request(self, path, data, request_id, link_id, remote_identity, requested_at):
if remote_identity == None:
return LXMPeer.ERROR_NO_IDENTITY
else:
@@ -960,7 +1189,7 @@ class LXMRouter:
RNS.log("Transfer concluded for incoming propagation resource "+str(resource), RNS.LOG_DEBUG)
if resource.status == RNS.Resource.COMPLETE:
# TODO: The peer this was received from should
# have the transient id added to it's list of
# have the transient id added to its list of
# already handled messages.
try:
data = msgpack.unpackb(resource.data.read())
@@ -976,7 +1205,8 @@ class LXMRouter:
remote_hash = remote_destination.hash
if not remote_hash in self.peers:
self.peer(remote_hash, remote_timebase)
if self.autopeer and RNS.Transport.hops_to(remote_hash) <= self.autopeer_maxdepth:
self.peer(remote_hash, remote_timebase)
messages = data[1]
for lxmf_data in messages:
@@ -992,15 +1222,18 @@ class LXMRouter:
except Exception as e:
RNS.log("Error while unpacking received propagation resource", RNS.LOG_DEBUG)
def lxmf_propagation(self, lxmf_data):
def lxmf_propagation(self, lxmf_data, signal_local_delivery=None, signal_duplicate=None):
try:
if len(lxmf_data) >= LXMessage.LXMF_OVERHEAD:
transient_id = RNS.Identity.full_hash(lxmf_data)
if not transient_id in self.propagation_entries and not transient_id in self.propagated_ids:
if not transient_id in self.propagation_entries and not transient_id in self.locally_processed_transient_ids:
received = time.time()
propagation_entry = [transient_id, received, lxmf_data]
destination_hash = lxmf_data[:LXMessage.DESTINATION_LENGTH]
self.locally_processed_transient_ids[transient_id] = received
if destination_hash in self.delivery_destinations:
delivery_destination = self.delivery_destinations[destination_hash]
encrypted_lxmf_data = lxmf_data[LXMessage.DESTINATION_LENGTH:]
@@ -1009,6 +1242,9 @@ class LXMRouter:
self.lxmf_delivery(delivery_data, delivery_destination.type)
self.locally_delivered_transient_ids[transient_id] = time.time()
if signal_local_delivery != None:
return signal_local_delivery
else:
if self.propagation_node:
file_path = self.messagepath+"/"+RNS.hexrep(transient_id, delimit=False)+"_"+str(received)
@@ -1023,8 +1259,19 @@ class LXMRouter:
peer = self.peers[peer_id]
peer.handle_message(transient_id)
else:
# TODO: Add message to sneakernet queues when implemented
RNS.log("Received propagated LXMF message "+RNS.prettyhexrep(transient_id)+", but this instance is not hosting a propagation node, discarding message.", RNS.LOG_DEBUG)
return True
else:
if signal_duplicate != None:
return signal_duplicate
else:
return False
return False
except Exception as e:
@@ -1032,6 +1279,28 @@ class LXMRouter:
RNS.log("The contained exception was: "+str(e), RNS.LOG_DEBUG)
return False
def ingest_lxm_uri(self, uri, signal_local_delivery=None, signal_duplicate=None):
try:
if not uri.lower().startswith(LXMessage.URI_SCHEMA+"://"):
RNS.log("Cannot ingest LXM, invalid URI provided.", RNS.LOG_ERROR)
return False
else:
lxmf_data = base64.urlsafe_b64decode(uri.replace(LXMessage.URI_SCHEMA+"://", "").replace("/", "")+"==")
transient_id = RNS.Identity.full_hash(lxmf_data)
router_propagation_result = self.lxmf_propagation(lxmf_data, signal_local_delivery=signal_local_delivery, signal_duplicate=signal_duplicate)
if router_propagation_result != False:
RNS.log("LXM with transient ID "+RNS.prettyhexrep(transient_id)+" was ingested.", RNS.LOG_DEBUG)
return router_propagation_result
else:
RNS.log("No valid LXM could be ingested from the provided URI", RNS.LOG_DEBUG)
return False
except Exception as e:
RNS.log("Error while decoding URI-encoded LXMF message. The contained exception was: "+str(e), RNS.LOG_ERROR)
return False
def fail_message(self, lxmessage):
RNS.log(str(lxmessage)+" failed to send", RNS.LOG_DEBUG)
@@ -1056,7 +1325,7 @@ class LXMRouter:
else:
RNS.log("Starting outbound processing for "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
# Outbound handling for opportunistic messages
if lxmessage.method == LXMessage.OPPORTUNISTIC:
if lxmessage.method == LXMessage.OPPORTUNISTIC:
if lxmessage.delivery_attempts <= LXMRouter.MAX_DELIVERY_ATTEMPTS:
if not hasattr(lxmessage, "next_delivery_attempt") or time.time() > lxmessage.next_delivery_attempt:
lxmessage.delivery_attempts += 1
@@ -1078,6 +1347,8 @@ class LXMRouter:
# to deliver the message
direct_link = self.direct_links[delivery_destination_hash]
if direct_link.status == RNS.Link.ACTIVE:
if lxmessage.progress == None or lxmessage.progress < 0.05:
lxmessage.progress = 0.05
if lxmessage.state != LXMessage.SENDING:
RNS.log("Starting transfer of "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
lxmessage.set_delivery_destination(direct_link)
@@ -1104,8 +1375,7 @@ class LXMRouter:
self.direct_links.pop(delivery_destination_hash)
lxmessage.next_delivery_attempt = time.time() + LXMRouter.DELIVERY_RETRY_WAIT
else:
# Simply wait for the link to become
# active or close
# Simply wait for the link to become active or close
RNS.log("The link to "+RNS.prettyhexrep(lxmessage.get_destination().hash)+" is pending, waiting for link to become active", RNS.LOG_DEBUG)
else:
# No link exists, so we'll try to establish one, but
@@ -1121,10 +1391,12 @@ class LXMRouter:
delivery_link = RNS.Link(lxmessage.get_destination())
delivery_link.set_link_established_callback(self.process_outbound)
self.direct_links[delivery_destination_hash] = delivery_link
lxmessage.progress = 0.03
else:
RNS.log("No path known for delivery attempt "+str(lxmessage.delivery_attempts)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash)+". Requesting path...", RNS.LOG_DEBUG)
RNS.Transport.request_path(lxmessage.get_destination().hash)
lxmessage.next_delivery_attempt = time.time() + LXMRouter.PATH_REQUEST_WAIT
lxmessage.progress = 0.00
else:
RNS.log("Max delivery attempts reached for direct "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
self.fail_message(lxmessage)
@@ -1160,7 +1432,7 @@ class LXMRouter:
else:
# Simply wait for the link to become
# active or close
RNS.log("The propagation link to "+RNS.prettyhexrep(self.outbound_propagation_node)+" is pending, waiting for link to become active: "+str(self.outbound_propagation_link.status), RNS.LOG_DEBUG)
RNS.log("The propagation link to "+RNS.prettyhexrep(self.outbound_propagation_node)+" is pending, waiting for link to become active", RNS.LOG_DEBUG)
else:
# No link exists, so we'll try to establish one, but
# only if we've never tried before, or the retry wait
+137 -21
View File
@@ -2,6 +2,7 @@ import RNS
import RNS.vendor.umsgpack as msgpack
import time
import base64
from .LXMF import APP_NAME
@@ -22,7 +23,8 @@ class LXMessage:
OPPORTUNISTIC = 0x01
DIRECT = 0x02
PROPAGATED = 0x03
valid_methods = [OPPORTUNISTIC, DIRECT, PROPAGATED]
PAPER = 0x05
valid_methods = [OPPORTUNISTIC, DIRECT, PROPAGATED, PAPER]
SOURCE_UNKNOWN = 0x01
SIGNATURE_INVALID = 0x02
@@ -31,9 +33,9 @@ class LXMessage:
DESTINATION_LENGTH = RNS.Identity.TRUNCATED_HASHLENGTH//8
SIGNATURE_LENGTH = RNS.Identity.SIGLENGTH//8
# LXMF overhead is 99 bytes per message:
# 10 bytes for destination hash
# 10 bytes for source hash
# LXMF overhead is 111 bytes per message:
# 16 bytes for destination hash
# 16 bytes for source hash
# 64 bytes for Ed25519 signature
# 8 bytes for timestamp
# 7 bytes for msgpack structure
@@ -51,7 +53,7 @@ class LXMessage:
# field of the packet, therefore we also add the length
# of a destination hash to the calculation. With default
# RNS and LXMF parameters, the largest single-packet
# LXMF message we can send is 294 bytes. If a message
# LXMF message we can send is 288 bytes. If a message
# is larger than that, a Reticulum link will be used.
ENCRYPTED_PACKET_MAX_CONTENT = ENCRYPTED_PACKET_MDU - LXMF_OVERHEAD + DESTINATION_LENGTH
@@ -61,13 +63,13 @@ class LXMessage:
LINK_PACKET_MDU = RNS.Link.MDU
# Which means that we can deliver single-packet LXMF
# messages with content of up to 332 bytes over a link.
# messages with content of up to 320 bytes over a link.
# If a message is larger than that, LXMF will sequence
# and transfer it as a RNS resource over the link instead.
LINK_PACKET_MAX_CONTENT = LINK_PACKET_MDU - LXMF_OVERHEAD
# For plain packets without encryption, we can
# fit up to 388 bytes of content.
# fit up to 369 bytes of content.
PLAIN_PACKET_MDU = RNS.Packet.PLAIN_MDU
PLAIN_PACKET_MAX_CONTENT = PLAIN_PACKET_MDU - LXMF_OVERHEAD + DESTINATION_LENGTH
@@ -76,6 +78,12 @@ class LXMessage:
ENCRYPTION_DESCRIPTION_EC = "Curve25519"
ENCRYPTION_DESCRIPTION_UNENCRYPTED = "Unencrypted"
# Constants for QR/URI encoding LXMs
URI_SCHEMA = "lxm"
QR_ERROR_CORRECTION = "ERROR_CORRECT_L"
QR_MAX_STORAGE = 2953
PAPER_MDU = ((QR_MAX_STORAGE-(len(URI_SCHEMA)+len("://")))*6)//8
def __str__(self):
if self.hash != None:
return "<LXMessage "+RNS.hexrep(self.hash, delimit=False)+">"
@@ -103,7 +111,6 @@ class LXMessage:
self.set_title_from_string(title)
self.set_content_from_string(content)
self.set_fields(fields)
self.payload = None
@@ -111,9 +118,15 @@ class LXMessage:
self.signature = None
self.hash = None
self.packed = None
self.progress = None
self.progress = 0.0
self.state = LXMessage.DRAFT
self.method = LXMessage.UNKNOWN
self.rssi = None
self.snr = None
self.q = None
self.propagation_packed = None
self.paper_packed = None
self.incoming = False
self.signature_validated = False
@@ -150,12 +163,23 @@ class LXMessage:
def set_fields(self, fields):
if isinstance(fields, dict) or fields == None:
self.fields = fields
self.fields = fields or {}
else:
raise ValueError("LXMessage property \"fields\" can only be dict or None")
def get_fields(self):
return self.__fields
return self.fields
@property
def destination(self):
return self.__destination
@destination.setter
def destination(self, destination):
self.set_destination(destination)
def get_destination(self):
return self.destination
def set_destination(self, destination):
if self.destination == None:
@@ -166,8 +190,16 @@ class LXMessage:
else:
raise ValueError("Cannot reassign destination on LXMessage")
def get_destination(self):
return self.__destination
@property
def source(self):
return self.__source
@source.setter
def source(self, source):
self.set_source(source)
def get_source(self):
return self.source
def set_source(self, source):
if self.source == None:
@@ -178,9 +210,6 @@ class LXMessage:
else:
raise ValueError("Cannot reassign source on LXMessage")
def get_source(self):
return self.__source
def set_delivery_destination(self, delivery_destination):
self.__delivery_destination = delivery_destination
@@ -196,6 +225,7 @@ class LXMessage:
self.timestamp = time.time()
self.propagation_packed = None
self.paper_packed = None
self.payload = [self.timestamp, self.title, self.content, self.fields]
@@ -263,6 +293,19 @@ class LXMessage:
self.method = self.desired_method
self.representation = LXMessage.RESOURCE
elif self.desired_method == LXMessage.PAPER:
paper_content_limit = LXMessage.PAPER_MDU
encrypted_data = self.__destination.encrypt(self.packed[LXMessage.DESTINATION_LENGTH:])
self.paper_packed = self.packed[:LXMessage.DESTINATION_LENGTH]+encrypted_data
content_size = len(self.paper_packed)
if content_size <= paper_content_limit:
self.method = self.desired_method
self.representation = LXMessage.PAPER
else:
raise TypeError("LXMessage desired paper delivery method, but content exceeds paper message maximum size.")
else:
raise ValueError("Attempt to re-pack LXMessage "+str(self)+" that was already packed")
@@ -281,12 +324,14 @@ class LXMessage:
if receipt:
receipt.set_delivery_callback(self.__mark_delivered)
receipt.set_timeout_callback(self.__link_packet_timed_out)
self.progress = 0.50
else:
if self.__delivery_destination:
self.__delivery_destination.teardown()
elif self.representation == LXMessage.RESOURCE:
self.resource_representation = self.__as_resource()
self.progress = 0.10
elif self.method == LXMessage.PROPAGATED:
self.state = LXMessage.SENDING
@@ -296,11 +341,13 @@ class LXMessage:
if receipt:
receipt.set_delivery_callback(self.__mark_propagated)
receipt.set_timeout_callback(self.__link_packet_timed_out)
self.progress = 0.50
else:
self.__delivery_destination.teardown()
elif self.representation == LXMessage.RESOURCE:
self.resource_representation = self.__as_resource()
self.progress = 0.10
def determine_transport_encryption(self):
@@ -327,6 +374,16 @@ class LXMessage:
else:
self.transport_encrypted = False
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_UNENCRYPTED
elif self.method == LXMessage.PAPER:
if self.__destination.type == RNS.Destination.SINGLE:
self.transport_encrypted = True
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_EC
elif self.__destination.type == RNS.Destination.GROUP:
self.transport_encrypted = True
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_AES
else:
self.transport_encrypted = False
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_UNENCRYPTED
else:
self.transport_encrypted = False
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_UNENCRYPTED
@@ -334,6 +391,7 @@ class LXMessage:
def __mark_delivered(self, receipt = None):
RNS.log("Received delivery notification for "+str(self), RNS.LOG_DEBUG)
self.state = LXMessage.DELIVERED
self.progress = 1.0
if self.__delivery_callback != None and callable(self.__delivery_callback):
try:
@@ -344,6 +402,18 @@ class LXMessage:
def __mark_propagated(self, receipt = None):
RNS.log("Received propagation success notification for "+str(self), RNS.LOG_DEBUG)
self.state = LXMessage.SENT
self.progress = 1.0
if self.__delivery_callback != None and callable(self.__delivery_callback):
try:
self.__delivery_callback(self)
except Exception as e:
RNS.log("An error occurred in the external delivery callback for "+str(message), RNS.LOG_ERROR)
def __mark_paper_generated(self, receipt = None):
RNS.log("Paper message generation succeeded for "+str(self), RNS.LOG_DEBUG)
self.state = LXMessage.PAPER
self.progress = 1.0
if self.__delivery_callback != None and callable(self.__delivery_callback):
try:
@@ -373,7 +443,7 @@ class LXMessage:
def __update_transfer_progress(self, resource):
self.progress = resource.get_progress()
self.progress = 0.10 + (resource.get_progress()*0.90)
def __as_packet(self):
if not self.packed:
@@ -402,8 +472,6 @@ class LXMessage:
if not self.__delivery_destination.status == RNS.Link.ACTIVE:
raise ConnectionError("Tried to synthesize resource for LXMF message on a link that was not active")
self.progress = 0.0
if self.method == LXMessage.DIRECT:
return RNS.Resource(self.packed, self.__delivery_destination, callback = self.__resource_concluded, progress_callback = self.__update_transfer_progress)
elif self.method == LXMessage.PROPAGATED:
@@ -441,9 +509,56 @@ class LXMessage:
RNS.log("Error while writing LXMF message to file \""+str(file_path)+"\". The contained exception was: "+str(e), RNS.LOG_ERROR)
return None
def as_uri(self, finalise=True):
if not self.packed:
self.pack()
if self.desired_method == LXMessage.PAPER and self.paper_packed != None:
# Encode packed LXM with URL-safe base64 and remove padding
encoded_bytes = base64.urlsafe_b64encode(self.paper_packed)
# Add protocol specifier and return
lxm_uri = LXMessage.URI_SCHEMA+"://"+encoded_bytes.decode("utf-8").replace("=","")
if finalise:
self.determine_transport_encryption()
self.__mark_paper_generated()
return lxm_uri
else:
raise TypeError("Attempt to represent LXM with non-paper delivery method as URI")
def as_qr(self):
if not self.packed:
self.pack()
if self.desired_method == LXMessage.PAPER and self.paper_packed != None:
import importlib
if importlib.util.find_spec('qrcode') != None:
import qrcode
qr = qrcode.make(
error_correction = qrcode.constants.__dict__[LXMessage.QR_ERROR_CORRECTION],
border = 1,
data = self.as_uri(finalise=False),
)
self.determine_transport_encryption()
self.__mark_paper_generated()
return qr
else:
RNS.log("Generating QR-code representanions of LXMs requires the \"qrcode\" module to be installed.", RNS.LOG_CRITICAL)
RNS.log("You can install it with the command: python3 -m pip install qrcode", RNS.LOG_CRITICAL)
return None
else:
raise TypeError("Attempt to represent LXM with non-paper delivery method as QR-code")
@staticmethod
def unpack_from_bytes(lxmf_bytes):
def unpack_from_bytes(lxmf_bytes, original_method = None):
destination_hash = lxmf_bytes[:LXMessage.DESTINATION_LENGTH]
source_hash = lxmf_bytes[LXMessage.DESTINATION_LENGTH:2*LXMessage.DESTINATION_LENGTH]
signature = lxmf_bytes[2*LXMessage.DESTINATION_LENGTH:2*LXMessage.DESTINATION_LENGTH+LXMessage.SIGNATURE_LENGTH]
@@ -476,7 +591,8 @@ class LXMessage:
title = "",
fields = fields,
destination_hash = destination_hash,
source_hash = source_hash)
source_hash = source_hash,
desired_method = original_method)
message.hash = message_hash
message.signature = signature
+557
View File
@@ -0,0 +1,557 @@
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2016-2022 Mark Qvist / unsigned.io
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
DEFFERED_JOBS_DELAY = 10
JOBS_INTERVAL = 5
import RNS
import LXMF
import argparse
import threading
import subprocess
import shlex
import time
import os
from LXMF._version import __version__
from RNS.vendor.configobj import ConfigObj
configpath = None
ignoredpath = None
identitypath = None
storagedir = None
lxmdir = None
targetloglevel = None
identity = None
lxmd_config = None
message_router = None
lxmf_destination = None
active_configuration = {}
last_peer_announce = None
last_node_announce = None
def create_default_config(configpath):
lxmd_config = ConfigObj(__default_lxmd_config__.splitlines())
lxmd_config.filename = configpath
lxmd_config.write()
def apply_config():
global active_configuration, targetloglevel
try:
# Load peer settings
if "lxmf" in lxmd_config and "display_name" in lxmd_config["lxmf"]:
active_configuration["display_name"] = lxmd_config["lxmf"]["display_name"]
else:
active_configuration["display_name"] = "Anonymous Peer"
if "lxmf" in lxmd_config and "announce_at_start" in lxmd_config["lxmf"]:
active_configuration["peer_announce_at_start"] = lxmd_config["lxmf"].as_bool("announce_at_start")
else:
active_configuration["peer_announce_at_start"] = False
if "lxmf" in lxmd_config and "announce_interval" in lxmd_config["lxmf"]:
active_configuration["peer_announce_interval"] = lxmd_config["lxmf"].as_int("announce_interval")*60
else:
active_configuration["peer_announce_interval"] = None
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")
if active_configuration["delivery_transfer_max_accepted_size"] < 0.38:
active_configuration["delivery_transfer_max_accepted_size"] = 0.38
else:
active_configuration["delivery_transfer_max_accepted_size"] = 1000
if "lxmf" in lxmd_config and "on_inbound" in lxmd_config["lxmf"]:
active_configuration["on_inbound"] = lxmd_config["lxmf"]["on_inbound"]
else:
active_configuration["on_inbound"] = None
# Load propagation node settings
if "propagation" in lxmd_config and "enable_node" in lxmd_config["propagation"]:
active_configuration["enable_propagation_node"] = lxmd_config["propagation"].as_bool("enable_node")
else:
active_configuration["enable_propagation_node"] = False
if "propagation" in lxmd_config and "auth_required" in lxmd_config["propagation"]:
active_configuration["auth_required"] = lxmd_config["propagation"].as_bool("auth_required")
else:
active_configuration["auth_required"] = False
if "propagation" in lxmd_config and "announce_at_start" in lxmd_config["propagation"]:
active_configuration["node_announce_at_start"] = lxmd_config["propagation"].as_bool("announce_at_start")
else:
active_configuration["node_announce_at_start"] = False
if "propagation" in lxmd_config and "autopeer" in lxmd_config["propagation"]:
active_configuration["autopeer"] = lxmd_config["propagation"].as_bool("autopeer")
else:
active_configuration["autopeer"] = True
if "propagation" in lxmd_config and "autopeer_maxdepth" in lxmd_config["propagation"]:
active_configuration["autopeer_maxdepth"] = lxmd_config["propagation"].as_int("autopeer_maxdepth")
else:
active_configuration["autopeer_maxdepth"] = None
if "propagation" in lxmd_config and "announce_interval" in lxmd_config["propagation"]:
active_configuration["node_announce_interval"] = lxmd_config["propagation"].as_int("announce_interval")*60
else:
active_configuration["node_announce_interval"] = None
if "propagation" in lxmd_config and "message_storage_limit" in lxmd_config["propagation"]:
active_configuration["message_storage_limit"] = lxmd_config["propagation"].as_float("message_storage_limit")
if active_configuration["message_storage_limit"] < 0.005:
active_configuration["message_storage_limit"] = 0.005
else:
active_configuration["message_storage_limit"] = 2000
if "propagation" in lxmd_config and "propagation_transfer_max_accepted_size" in lxmd_config["propagation"]:
active_configuration["propagation_transfer_max_accepted_size"] = lxmd_config["propagation"].as_float("propagation_transfer_max_accepted_size")
if active_configuration["propagation_transfer_max_accepted_size"] < 0.38:
active_configuration["propagation_transfer_max_accepted_size"] = 0.38
else:
active_configuration["propagation_transfer_max_accepted_size"] = 256
if "propagation" in lxmd_config and "prioritise_destinations" in lxmd_config["propagation"]:
active_configuration["prioritised_lxmf_destinations"] = lxmd_config["propagation"].as_list("prioritise_destinations")
else:
active_configuration["prioritised_lxmf_destinations"] = []
# Load various settings
if "logging" in lxmd_config and "loglevel" in lxmd_config["logging"]:
targetloglevel = lxmd_config["logging"].as_int("loglevel")
active_configuration["ignored_lxmf_destinations"] = []
if os.path.isfile(ignoredpath):
try:
fh = open(ignoredpath, "rb")
ignored_input = fh.read()
fh.close()
ignored_hash_strs = ignored_input.splitlines()
for hash_str in ignored_hash_strs:
if len(hash_str) == RNS.Identity.TRUNCATED_HASHLENGTH//8*2:
try:
ignored_hash = bytes.fromhex(hash_str.decode("utf-8"))
active_configuration["ignored_lxmf_destinations"].append(ignored_hash)
except Exception as e:
RNS.log("Could not decode hash from: "+str(hash_str), RNS.LOG_DEBUG)
RNS.log("The contained exception was: "+str(e), RNS.LOG_DEBUG)
except Exception as e:
RNS.log("Error while loading list of ignored destinations: "+str(e), RNS.LOG_ERROR)
active_configuration["allowed_identities"] = []
if os.path.isfile(allowedpath):
try:
fh = open(allowedpath, "rb")
allowed_input = fh.read()
fh.close()
allowed_hash_strs = allowed_input.splitlines()
for hash_str in allowed_hash_strs:
if len(hash_str) == RNS.Identity.TRUNCATED_HASHLENGTH//8*2:
try:
allowed_hash = bytes.fromhex(hash_str.decode("utf-8"))
active_configuration["allowed_identities"].append(allowed_hash)
except Exception as e:
RNS.log("Could not decode hash from: "+str(hash_str), RNS.LOG_DEBUG)
RNS.log("The contained exception was: "+str(e), RNS.LOG_DEBUG)
except Exception as e:
RNS.log("Error while loading list of allowed identities: "+str(e), RNS.LOG_ERROR)
except Exception as e:
RNS.log("Could not apply LXM Daemon configuration. The contained exception was: "+str(e), RNS.LOG_ERROR)
raise e
exit(3)
def lxmf_delivery(lxm):
global active_configuration, lxmdir
try:
written_path = lxm.write_to_directory(lxmdir)
RNS.log("Received "+str(lxm)+" written to "+str(written_path), RNS.LOG_DEBUG)
if active_configuration["on_inbound"]:
RNS.log("Calling external program to handle message", RNS.LOG_DEBUG)
command = active_configuration["on_inbound"]
processing_command = command+" \""+written_path+"\""
return_code = subprocess.call(shlex.split(processing_command), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
else:
RNS.log("No action defined for inbound messages, ignoring", RNS.LOG_DEBUG)
except Exception as e:
RNS.log("Error occurred while processing received message "+str(lxm)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
def program_setup(configdir = None, rnsconfigdir = None, run_pn = False, on_inbound = None, verbosity = 0, quietness = 0, service = False):
global configpath, ignoredpath, identitypath, allowedpath, storagedir, lxmdir
global lxmd_config, active_configuration, targetloglevel
global message_router, lxmf_destination
if service:
targetlogdest = RNS.LOG_FILE
targetloglevel = None
else:
targetlogdest = RNS.LOG_STDOUT
# Get configuration
if configdir == None:
if os.path.isdir("/etc/lxmd") and os.path.isfile("/etc/lxmd/config"):
configdir = "/etc/lxmd"
elif os.path.isdir(RNS.Reticulum.userdir+"/.config/lxmd") and os.path.isfile(Reticulum.userdir+"/.config/lxmd/config"):
configdir = RNS.Reticulum.userdir+"/.config/lxmd"
else:
configdir = RNS.Reticulum.userdir+"/.lxmd"
configpath = configdir+"/config"
ignoredpath = configdir+"/ignored"
allowedpath = configdir+"/allowed"
identitypath = configdir+"/identity"
storagedir = configdir+"/storage"
lxmdir = storagedir+"/messages"
if not os.path.isdir(storagedir):
os.makedirs(storagedir)
if not os.path.isdir(lxmdir):
os.makedirs(lxmdir)
if not os.path.isfile(configpath):
RNS.log("Could not load config file, creating default configuration file...")
create_default_config(configpath)
RNS.log("Default config file created. Make any necessary changes in "+configpath+" and restart lxmd if needed.")
time.sleep(1.5)
if os.path.isfile(configpath):
try:
lxmd_config = ConfigObj(configpath)
except Exception as e:
RNS.log("Could not parse the configuration at "+configpath, RNS.LOG_ERROR)
RNS.log("Check your configuration file for errors!", RNS.LOG_ERROR)
RNS.panic()
apply_config()
RNS.log("Configuration loaded from "+configpath, RNS.LOG_VERBOSE)
if targetloglevel == None:
targetloglevel = 3
if verbosity != 0 or quietness != 0:
targetloglevel = targetloglevel+verbosity-quietness
# Start Reticulum
RNS.log("Substantiating Reticulum...")
reticulum = RNS.Reticulum(configdir=rnsconfigdir, loglevel=targetloglevel, logdest=targetlogdest)
# Generate or load primary identity
if os.path.isfile(identitypath):
try:
identity = RNS.Identity.from_file(identitypath)
if identity != None:
RNS.log("Loaded Primary Identity %s" % (str(identity)))
else:
RNS.log("Could not load the Primary Identity from "+identitypath, RNS.LOG_ERROR)
exit(4)
except Exception as e:
RNS.log("Could not load the Primary Identity from "+identitypath, RNS.LOG_ERROR)
RNS.log("The contained exception was: %s" % (str(e)), RNS.LOG_ERROR)
exit(1)
else:
try:
RNS.log("No Primary Identity file found, creating new...")
identity = RNS.Identity()
identity.to_file(identitypath)
RNS.log("Created new Primary Identity %s" % (str(identity)))
except Exception as e:
RNS.log("Could not create and save a new Primary Identity", RNS.LOG_ERROR)
RNS.log("The contained exception was: %s" % (str(e)), RNS.LOG_ERROR)
exit(2)
# Start LXMF
message_router = LXMF.LXMRouter(
identity = identity,
storagepath = storagedir,
autopeer = active_configuration["autopeer"],
autopeer_maxdepth = active_configuration["autopeer_maxdepth"],
propagation_limit = active_configuration["propagation_transfer_max_accepted_size"],
delivery_limit = active_configuration["delivery_transfer_max_accepted_size"],
)
message_router.register_delivery_callback(lxmf_delivery)
for destination_hash in active_configuration["ignored_lxmf_destinations"]:
message_router.ignore_destination(destination_hash)
lxmf_destination = message_router.register_delivery_identity(identity, display_name=active_configuration["display_name"])
RNS.Identity.remember(
packet_hash=None,
destination_hash=lxmf_destination.hash,
public_key=identity.get_public_key(),
app_data=None
)
# Set up authentication
if active_configuration["auth_required"]:
message_router.set_authentication(required=True)
if len(active_configuration["allowed_identities"]) == 0:
RNS.log("Clint authentication was enabled, but no identity hashes could be loaded from "+str(allowedpath)+". Nobody will be able to sync messages from this propagation node.", RNS.LOG_WARNING)
for identity_hash in active_configuration["allowed_identities"]:
message_router.allow(identity_hash)
RNS.log("LXMF Router ready to receive on "+RNS.prettyhexrep(lxmf_destination.hash))
if run_pn or active_configuration["enable_propagation_node"]:
message_router.set_message_storage_limit(megabytes=active_configuration["message_storage_limit"])
for dest_str in active_configuration["prioritised_lxmf_destinations"]:
try:
dest_hash = bytes.fromhex(dest_str)
if len(dest_hash) == RNS.Reticulum.TRUNCATED_HASHLENGTH//8:
message_router.prioritise(dest_hash)
except Exception as e:
RNS.log("Cannot prioritise "+str(dest_str)+", it is not a valid destination hash", RNS.LOG_ERROR)
message_router.enable_propagation()
RNS.log("LXMF Propagation Node started on "+RNS.prettyhexrep(message_router.propagation_destination.hash))
RNS.log("Started lxmd version {version}".format(version=__version__), RNS.LOG_NOTICE)
threading.Thread(target=deferred_start_jobs, daemon=True).start()
while True:
time.sleep(1)
def jobs():
global active_configuration, last_peer_announce, last_node_announce
global message_router, lxmf_destination
while True:
try:
if "peer_announce_interval" in active_configuration and active_configuration["peer_announce_interval"] != None:
if time.time() > last_peer_announce + active_configuration["peer_announce_interval"]:
RNS.log("Sending announce for LXMF delivery destination", RNS.LOG_EXTREME)
message_router.announce(lxmf_destination.hash)
last_peer_announce = time.time()
if "node_announce_interval" in active_configuration and active_configuration["node_announce_interval"] != None:
if time.time() > last_node_announce + active_configuration["node_announce_interval"]:
RNS.log("Sending announce for LXMF Propagation Node", RNS.LOG_EXTREME)
message_router.announce_propagation_node()
last_node_announce = time.time()
except Exception as e:
RNS.log("An error occurred while running periodic jobs. The contained exception was: "+str(e), RNS.LOG_ERROR)
time.sleep(JOBS_INTERVAL)
def deferred_start_jobs():
global active_configuration, last_peer_announce, last_node_announce
global message_router, lxmf_destination
time.sleep(DEFFERED_JOBS_DELAY)
RNS.log("Running deferred start jobs")
if active_configuration["peer_announce_at_start"]:
RNS.log("Sending announce for LXMF delivery destination", RNS.LOG_EXTREME)
message_router.announce(lxmf_destination.hash)
if active_configuration["node_announce_at_start"]:
RNS.log("Sending announce for LXMF Propagation Node", RNS.LOG_EXTREME)
message_router.announce_propagation_node()
last_peer_announce = time.time()
last_node_announce = time.time()
threading.Thread(target=jobs, daemon=True).start()
def main():
try:
parser = argparse.ArgumentParser(description="Lightweight Extensible Messaging Daemon")
parser.add_argument("--config", action="store", default=None, help="path to alternative lxmd config directory", type=str)
parser.add_argument("--rnsconfig", action="store", default=None, help="path to alternative Reticulum config directory", type=str)
parser.add_argument("-p", "--propagation-node", action="store_true", default=False, help="run an LXMF Propagation Node")
parser.add_argument("-i", "--on-inbound", action="store", metavar="PATH", default=None, help="executable to run when a message is received", type=str)
parser.add_argument("-v", "--verbose", action="count", default=0)
parser.add_argument("-q", "--quiet", action="count", default=0)
parser.add_argument("-s", "--service", action="store_true", default=False, help="lxmd is running as a service and should log to file")
parser.add_argument("--exampleconfig", action="store_true", default=False, help="print verbose configuration example to stdout and exit")
parser.add_argument("--version", action="version", version="lxmd {version}".format(version=__version__))
args = parser.parse_args()
if args.exampleconfig:
print(__default_lxmd_config__)
exit()
program_setup(
configdir = args.config,
rnsconfigdir=args.rnsconfig,
run_pn=args.propagation_node,
on_inbound=args.on_inbound,
verbosity=args.verbose,
quietness=args.quiet,
service=args.service
)
except KeyboardInterrupt:
print("")
exit()
__default_lxmd_config__ = """# This is an example LXM Daemon config file.
# You should probably edit it to suit your
# intended usage.
[propagation]
# Whether to enable propagation node
enable_node = no
# Automatic announce interval in minutes.
# 6 hours by default.
announce_interval = 360
# Whether to announce when the node starts.
announce_at_start = yes
# Wheter to automatically peer with other
# propagation nodes on the network.
autopeer = yes
# The maximum peering depth (in hops) for
# automatically peered nodes.
autopeer_maxdepth = 4
# The maximum accepted transfer size per in-
# coming propagation transfer, in kilobytes.
# This also sets the upper limit for the size
# of single messages accepted onto this node.
#
# If a node wants to propagate a larger number
# of messages to this node, than what can fit
# within this limit, it will prioritise sending
# the smallest messages first, and try again
# with any remaining messages at a later point.
propagation_transfer_max_accepted_size = 256
# The maximum amount of storage to use for
# the LXMF Propagation Node message store,
# specified in megabytes. When this limit
# is reached, LXMF will periodically remove
# messages in its message store. By default,
# LXMF prioritises keeping messages that are
# new and small. Large and old messages will
# be removed first. This setting is optional
# and defaults to 2 gigabytes.
# message_storage_limit = 2000
# You can tell the LXMF message router to
# prioritise storage for one or more
# destinations. If the message store reaches
# the specified limit, LXMF will prioritise
# keeping messages for destinations specified
# with this option. This setting is optional,
# and generally you do not need to use it.
# prioritise_destinations = 41d20c727598a3fbbdf9106133a3a0ed, d924b81822ca24e68e2effea99bcb8cf
# By default, any destination is allowed to
# connect and download messages, but you can
# optionally restrict this. If you enable
# authentication, you must provide a list of
# allowed identity hashes in the a file named
# "allowed" in the lxmd config directory.
auth_required = no
[lxmf]
# The LXM Daemon will create an LXMF destination
# that it can receive messages on. This option sets
# the announced display name for this destination.
display_name = Anonymous Peer
# It is possible to announce the internal LXMF
# destination when the LXM Daemon starts up.
announce_at_start = no
# You can also announce the delivery destination
# at a specified interval. This is not enabled by
# default.
# announce_interval = 360
# The maximum accepted unpacked size for mes-
# sages received directly from other peers,
# specified in kilobytes. Messages larger than
# this will be rejected before the transfer
# begins.
delivery_transfer_max_accepted_size = 1000
# You can configure an external program to be run
# every time a message is received. The program
# will receive as an argument the full path to the
# message saved as a file. The example below will
# simply result in the message getting deleted as
# soon as it has been received.
# on_inbound = rm
[logging]
# Valid log levels are 0 through 7:
# 0: Log only critical information
# 1: Log errors and lower log levels
# 2: Log warnings and lower log levels
# 3: Log notices and lower log levels
# 4: Log info and lower (this is the default)
# 5: Verbose logging
# 6: Debug logging
# 7: Extreme logging
loglevel = 4
"""
if __name__ == "__main__":
main()
+1
View File
@@ -2,6 +2,7 @@ import os
import glob
from .LXMessage import LXMessage
from .LXMRouter import LXMRouter
from .LXMF import *
from ._version import __version__
+1 -1
View File
@@ -1 +1 @@
__version__ = "0.1.9"
__version__ = "0.4.2"
+2
View File
@@ -8,10 +8,12 @@ clean:
remove_symlinks:
@echo Removing symlinks for build...
-rm ./RNS
-rm ./LXMF/Utilities/LXMF
create_symlinks:
@echo Creating symlinks...
-ln -s ../Reticulum/RNS ./
-ln -s ../../LXMF ./LXMF/Utilities/LXMF
build_wheel:
python3 setup.py sdist bdist_wheel
+78 -17
View File
@@ -1,13 +1,27 @@
Lightweight Extensible Message Format
==========
# Lightweight Extensible Message Format
LXMF is a simple and flexible messaging format and delivery protocol that allows a wide variety of implementations, while using as little bandwidth as possible. It is built on top of [Reticulum](https://github.com/markqvist/reticulum) and offers zero-conf message routing, end-to-end encryption and Forward Secrecy by default.
LXMF is a simple and flexible messaging format and delivery protocol that allows a wide variety of implementations, while using as little bandwidth as possible. It is built on top of [Reticulum](https://reticulum.network) and offers zero-conf message routing, end-to-end encryption and Forward Secrecy, and can be transported over any kind of medium that Reticulum supports.
LXMF is efficient enough that it can deliver messages over extremely low-bandwidth systems such as packet radio or LoRa. Encrypted LXMF messages can also be encoded as QR-codes or text-based URIs, allowing completely analog *paper message* transport.
User-facing clients built on LXMF include:
- [Sideband](https://unsigned.io/sideband)
- [Nomad Network](https://unsigned.io/nomadnet)
Community-provided tools and utilities for LXMF include:
- [LXMF-Bot](https://github.com/randogoth/lxmf-bot)
- [LXMF Messageboard](https://github.com/chengtripp/lxmf_messageboard)
- [LXMEvent](https://github.com/faragher/LXMEvent)
- [RangeMap](https://github.com/faragher/RangeMap)
- [LXMF Tools](https://github.com/SebastianObi/LXMF-Tools)
## Structure
LXMF messages are stored in a simple and efficient format, that's easy to parse and write.
##### The format follows this general structure:
### The format follows this general structure:
- Destination
- Source
@@ -18,14 +32,14 @@ LXMF messages are stored in a simple and efficient format, that's easy to parse
- Title
- Fields
##### And these rules:
### And these rules:
1. A LXMF message is identified by its __message-id__, which is a SHA-256 hash of the __Destination__, __Source__ and __Payload__. The message-id is never included directly in the message, since it can always be inferred from the message itself.
In some cases the actual message-id cannot be inferred, for example when a Propagation Node is storing an encrypted message for an offline user. In theses cases a _transient-id_ is used to identify the message while in storage or transit.
In some cases the actual message-id cannot be inferred, for example when a Propagation Node is storing an encrypted message for an offline user. In these cases a _transient-id_ is used to identify the message while in storage or transit.
2. __Destination__, __Source__, __Signature__ and __Payload__ parts are mandatory, as is the __Timestamp__ part of the payload.
- The __Destination__ and __Source__ fields are 10-byte Reticulum destination hashes
- The __Destination__ and __Source__ fields are 16-byte Reticulum destination hashes
- The __Signature__ field is a 64-byte Ed25519 signature of the __Destination__, __Source__, __Payload__ and __message-id__
- The __Payload__ part is a [msgpacked](https://msgpack.org) list containing four items:
1. The __Timestamp__ is a double-precision floating point number representing the number of seconds since the UNIX epoch.
@@ -39,7 +53,7 @@ LXMF messages are stored in a simple and efficient format, that's easy to parse
## Usage Examples
LXMF offers flexibility to implement many different messaging schemes, ranging from human communication to machine control and sensor monitoring. Here's a few examples:
LXMF offers flexibility to implement many different messaging schemes, ranging from human communication to machine control and sensor monitoring. Here are a few examples:
- A messaging system for passing short, simple messages between human users, akin to SMS can be implemented using only the __Content__ field, and leaving all other optional fields empty.
@@ -76,33 +90,80 @@ The LXM Router then handles the heavy lifting, such as message packing, encrypti
## Transport Encryption
LXMF uses encryption provided by [Reticulum](https://github.com/markqvist/reticulum), and thus uses end-to-end encryption by default. The delivery method of a message will influence which transport encryption scheme is used.
LXMF uses encryption provided by [Reticulum](https://reticulum.network), and thus uses end-to-end encryption by default. The delivery method of a message will influence which transport encryption scheme is used.
- A message can be delivered opportunistically, embedded in a single Reticulum packet. In this cases the message will be opportunistically routed through the network, and will be encrypted with _ephemeral_ keys derived with _ECDH_ on _Curve25519_. This mode offers Perfect Forward Secrecy.
- If a message is delivered over a Reticulum link (which is the default method), the message will be encrypted with ephemeral AES-128 keys derived with ECDH on Curve25519. This mode offers forward secrecy.
- If a message is delivered to the Reticulum GROUP destination type, the message will be transported using _AES-128_ encryption.
- A message can be delivered opportunistically, embedded in a single Reticulum packet. In this cases the message will be opportunistically routed through the network, and will be encrypted with per-packet AES-128 keys derived with ECDH on Curve25519.
- If a message is delivered over a Reticulum link (which is the default method), the message will be encrypted with _ephemeral_ keys derived with _ECDH_ on _Curve25519_. This mode offers Perfect Forward Secrecy.
- If a message is delivered to the Reticulum GROUP destination type, the message will be encrypted using the symmetric AES-128 key of the GROUP destination.
## Wire Format & Overhead
Assuming the default Reticulum configuration, the binary wire-format is as follows:
- 10 bytes destination hash
- 10 bytes source hash
- 16 bytes destination hash
- 16 bytes source hash
- 64 bytes Ed25519 signature
- Remaining bytes of [msgpack](https://msgpack.org) payload data, in accordance with the structure defined above
The complete message overhead for LXMF is only 99 bytes, which in return gives you timestamped, digitally signed, infinitely extensible, end-to-end encrypted, zero-conf routed, minimal-infrastructure messaging that's easy to use and build applications with.
The complete message overhead for LXMF is only 111 bytes, which in return gives you timestamped, digitally signed, infinitely extensible, end-to-end encrypted, zero-conf routed, minimal-infrastructure messaging that's easy to use and build applications with.
## Code Examples
Before writing your own programs using LXMF, you need to have a basic understanding of how the [Reticulum](https://reticulum.network) protocol and API works. Please see the [Reticulum Manual](https://reticulum.network/manual/). For a few simple examples of how to send and receive messages with LXMF, please see the [receiver example](./docs/example_receiver.py) and the [sender example](./docs/example_sender.py) included in this repository.
## Example Paper Message
You can try out the paper messaging functionality by using the following QR code. It is a paper message sent to the LXMF address `6b3362bd2c1dbf87b66a85f79a8d8c75`. To be able to decrypt and read the message, you will need to import the following Reticulum Identity to an LXMF messaging app:
`3BPTDTQCRZPKJT3TXAJCMQFMOYWIM3OCLKPWMG4HCF2T4CH3YZHVNHNRDU6QAZWV2KBHMWBNT2C62TQEVC5GLFM4MN25VLZFSK3ADRQ=`
The [Sideband](https://unsigned.io/sideband) application allows you to do this easily. After you have imported the identity into an app of your choice, you can scan the following QR code and open it in the app, where it will be decrypted and added as a message.
<p align="center"><img width="50%" src="./docs/paper_msg_test.png"/></p>
You can also find the entire message in <a href="lxm://azNivSwdv4e2aoX3mo2MdTAozuI7BlzrLlHULmnVgpz3dNT9CMPVwgywzCJP8FVogj5j_kU7j7ywuvBNcr45kRTrd19c3iHenmnSDe4VEd6FuGsAiT0Khzl7T81YZHPTDhRNp0FdhDE9AJ7uphw7zKMyqhHHxOxqrYeBeKF66gpPxDceqjsOApvsSwggjcuHBx9OxOBy05XmnJxA1unCKgvNfOFYc1T47luxoY3c0dLOJnJPwZuFRytx2TXlQNZzOJ28yTEygIfkDqEO9mZi5lgev7XZJ0DvgioQxMIyoCm7lBUzfq66zW3SQj6vHHph7bhr36dLOCFgk4fZA6yia2MlTT9KV66Tn2l8mPNDlvuSAJhwDA_xx2PN9zKadCjo9sItkAp8r-Ss1CzoUWZUAyT1oDw7ly6RrzGBG-e3eM3CL6u1juIeFiHby7_3cON-6VTUuk4xR5nwKlFTu5vsYMVXe5H3VahiDSS4Q1aqX7I">this link</a>:
`lxm://azNivSwdv4e2aoX3mo2MdTAozuI7BlzrLlHULmnVgpz3dNT9CMPVwgywzCJP8FVogj5j_kU7j7ywuvBNcr45kRTrd19c3iHenmnSDe4VEd6FuGsAiT0Khzl7T81YZHPTDhRNp0FdhDE9AJ7uphw7zKMyqhHHxOxqrYeBeKF66gpPxDceqjsOApvsSwggjcuHBx9OxOBy05XmnJxA1unCKgvNfOFYc1T47luxoY3c0dLOJnJPwZuFRytx2TXlQNZzOJ28yTEygIfkDqEO9mZi5lgev7XZJ0DvgioQxMIyoCm7lBUzfq66zW3SQj6vHHph7bhr36dLOCFgk4fZA6yia2MlTT9KV66Tn2l8mPNDlvuSAJhwDA_xx2PN9zKadCjo9sItkAp8r-Ss1CzoUWZUAyT1oDw7ly6RrzGBG-e3eM3CL6u1juIeFiHby7_3cON-6VTUuk4xR5nwKlFTu5vsYMVXe5H3VahiDSS4Q1aqX7I`
On operating systems that allow for registering custom URI-handlers, you can click the link, and it will be decoded directly in your LXMF client. This works with Sideband on Android.
## Caveat Emptor
LXMF is beta software, and should be considered experimental. While it has been built with cryptography best-practices very foremost in mind, it _has not_ been externally security audited, and there could very well be privacy-breaking bugs. If you want to help out, or help sponsor an audit, please do get in touch.
LXMF is beta software, and should be considered experimental. While it has been built with cryptography best practices very foremost in mind, it _has not_ been externally security audited, and there could very well be privacy-breaking bugs. If you want to help out, or help sponsor an audit, please do get in touch.
## Installation
If you want to try out LXMF, you can install it with pip:
```bash
pip3 install lxmf
pip install lxmf
```
If you are using an operating system that blocks normal user package installation via `pip`,
you can return `pip` to normal behaviour by editing the `~/.config/pip/pip.conf` file,
and adding the following directive in the `[global]` section:
```text
[global]
break-system-packages = true
```
Alternatively, you can use the `pipx` tool to install Reticulum in an isolated environment:
```bash
pipx install lxmf
```
## Development Roadmap
LXMF is actively being developed, and the following improvements and features are currently planned for implementation:
- Write and release full API and protocol documentation
- Update examples in readme to actually work
- Content Destinations, and easy to use API for group messaging and discussion threads
- Sneakernet and physical transport functionality
- Documenting and possibly expanding LXMF limits and priorities
- Sync affinity based on link speeds and distances, for more intelligently choosing peer sync order
- Markets on LXMF
+37
View File
@@ -0,0 +1,37 @@
import RNS
import LXMF
import time
def delivery_callback(message):
time_string = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(message.timestamp))
signature_string = "Signature is invalid, reason undetermined"
if message.signature_validated:
signature_string = "Validated"
else:
if message.unverified_reason == LXMF.LXMessage.SIGNATURE_INVALID:
signature_string = "Invalid signature"
if message.unverified_reason == LXMF.LXMessage.SOURCE_UNKNOWN:
signature_string = "Cannot verify, source is unknown"
RNS.log("\t+--- LXMF Delivery ---------------------------------------------")
RNS.log("\t| Source hash : "+RNS.prettyhexrep(message.source_hash))
RNS.log("\t| Source instance : "+str(message.get_source()))
RNS.log("\t| Destination hash : "+RNS.prettyhexrep(message.destination_hash))
RNS.log("\t| Destination instance : "+str(message.get_destination()))
RNS.log("\t| Transport Encryption : "+str(message.transport_encryption))
RNS.log("\t| Timestamp : "+time_string)
RNS.log("\t| Title : "+message.title_as_string())
RNS.log("\t| Content : "+message.content_as_string())
RNS.log("\t| Fields : "+str(message.fields))
RNS.log("\t| Message signature : "+signature_string)
RNS.log("\t+---------------------------------------------------------------")
r = RNS.Reticulum()
router = LXMF.LXMRouter(storagepath="./tmp1")
identity = RNS.Identity()
my_lxmf_destination = router.register_delivery_identity(identity)
router.register_delivery_callback(delivery_callback)
RNS.log("Ready to receive on: "+RNS.prettyhexrep(my_lxmf_destination.hash))
input()
+39
View File
@@ -0,0 +1,39 @@
import LXMF
import RNS
import time
import random
random_names = ["Tom", "Delilah", "Nancey", "Williams", "Neomi", "Curtis", "Alexa", "Theodora", "Ted", "Dinorah", "Nicol", "Drusilla", "Annalisa", "Verlene", "Latesha", "Tina", "Mia", "Brock", "Timothy", "Philip", "Willian", "Reyna", "Simona", "Mimi", "Stanford", "Ferne", "Catalina", "Lucie", "Jaye", "Natasha", "Willetta", "Isabel", "Esperanza", "Ciara", "Eusebio", "William", "Elma", "Angelica", "Coreen", "Melani", "Jonathan", "Maryland", "Caroline", "Gregg", "Ora", "Jacqui", "Letty", "Roselle", "Oralee", "Angla"]
random_titles = ["Long time", "Hi again", "Re: Hi there", "Test message", "", "", "Something different"]
random_msgs = ["If wishes were horses then beggars might fly. Stuff like that. It's enough to drive you crazy.", "'My ident cards were stolen,' Jason said. 'That fivehundred-dollar bill is yours if you can get me to someone who can replace them. If you're going to do it, do it right now; I'm not going to wait.' Wait to be picked up by a pol or a nat, he thought. Caught here in this rundown dingy hotel.", "A six, no matter what the external circumstances, will always prevail. Because that's the way they genetically defined us.", "'Should be there in an hour,' he called back over his shoulder to Chuck. Then he added, in an afterthought, 'Wonder if the computer’s finished its run. It was due about now.'. Chuck didn’t reply, so George swung round in his saddle. He could just see Chuck’s face, a white oval turned toward the sky."]
def delivery_callback(message):
pass
r = RNS.Reticulum()
router = LXMF.LXMRouter(storagepath="./tmp2")
router.register_delivery_callback(delivery_callback)
ident = RNS.Identity()
source = router.register_delivery_identity(ident, display_name=random_names[random.randint(0,len(random_names)-1)])
router.announce(source.hash)
RNS.log("Source announced")
print("Recipient: ", end=" ")
recipient_hexhash = input()
recipient_hash = bytes.fromhex(recipient_hexhash)
if not RNS.Transport.has_path(recipient_hash):
RNS.log("Destination is not yet known. Requesting path and waiting for announce to arrive...")
RNS.Transport.request_path(recipient_hash)
while not RNS.Transport.has_path(recipient_hash):
time.sleep(0.1)
# Recall the server identity
recipient_identity = RNS.Identity.recall(recipient_hash)
dest = RNS.Destination(recipient_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, "lxmf", "delivery")
while True:
lxm = LXMF.LXMessage(dest, source, random_msgs[random.randint(0,len(random_msgs)-1)], random_titles[random.randint(0,len(random_titles)-1)], desired_method=LXMF.LXMessage.DIRECT)
router.handle_outbound(lxm)
input()
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

+3
View File
@@ -0,0 +1,3 @@
qrcode==7.4.2
rns==0.5.7
setuptools==68.0.0
+8 -3
View File
@@ -14,12 +14,17 @@ setuptools.setup(
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/markqvist/lxmf",
packages=setuptools.find_packages(),
packages=["LXMF", "LXMF.Utilities"],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
install_requires=['rns>=0.3.13'],
python_requires='>=3.6',
entry_points= {
'console_scripts': [
'lxmd=LXMF.Utilities.lxmd:main',
]
},
install_requires=['rns>=0.7.3'],
python_requires='>=3.7',
)