mirror of
https://github.com/markqvist/LXMF
synced 2026-11-22 23:10:36 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ad82b68bd | ||
|
|
ba2c6b833e | ||
|
|
2b7ba9558b | ||
|
|
ef2e1234a5 | ||
|
|
7c9bdd7fa2 | ||
|
|
72853fcf77 | ||
|
|
97f8c105af | ||
|
|
6ecd271e48 | ||
|
|
694f2413ea | ||
|
|
a6f5a56a38 | ||
|
|
f4c805ea35 | ||
|
|
7c71eb1df4 | ||
|
|
bc7522b63d | ||
|
|
39e398be65 | ||
|
|
ee15e9f0b6 | ||
|
|
00ffbc09fe | ||
|
|
dca6cc2adc | ||
|
|
62038573f1 | ||
|
|
fa2d78c351 | ||
|
|
f18ce9ea99 | ||
|
|
d7a2979dd0 | ||
|
|
0b067914ea | ||
|
|
bc3f4ecff5 | ||
|
|
99830b6e8b | ||
|
|
1b5dc419b5 | ||
|
|
9c5fa4a066 | ||
|
|
383d953e06 | ||
|
|
557887d13f | ||
|
|
e1905b85d7 | ||
|
|
8e3ffb0d2a | ||
|
|
f383450b37 | ||
|
|
747ddbddd5 | ||
|
|
d0f3385f75 | ||
|
|
401328fa16 | ||
|
|
4350a239e4 | ||
|
|
9dc998f149 | ||
|
|
fa9fd2ae01 | ||
|
|
0cebd5886d | ||
|
|
b35b9213a6 | ||
|
|
df6271a026 | ||
|
|
4afb92bf3e | ||
|
|
0a5edb2895 | ||
|
|
704b37dc16 | ||
|
|
606a723e31 | ||
|
|
a44c1f368a | ||
|
|
434267784d | ||
|
|
9c646aead7 | ||
|
|
ebc8bb33c2 | ||
|
|
60bf99d151 | ||
|
|
c84aea745a | ||
|
|
a62ffa12b1 | ||
|
|
6446db4f11 | ||
|
|
81a6d503a3 | ||
|
|
c28d3b1432 | ||
|
|
d8b25e092f | ||
|
|
aca5bf9c14 | ||
|
|
bd6fe9f9d1 | ||
|
|
0f2d3b06c2 | ||
|
|
3f91e44a6d | ||
|
|
8f54d40abf | ||
|
|
9beeafb0c8 | ||
|
|
b572723a5e | ||
|
|
6cf7852271 | ||
|
|
e17263d25a | ||
|
|
16dfbc22cd | ||
|
|
98347d3ad9 | ||
|
|
61b75526d2 | ||
|
|
85d8f4f583 | ||
|
|
5b9f121593 | ||
|
|
416ccf294f | ||
|
|
787cd069dc | ||
|
|
c2207d1eb7 | ||
|
|
a9622e3a33 | ||
|
|
499fe4cc53 | ||
|
|
37e99910ec | ||
|
|
005d71707c | ||
|
|
1bdcf6ad53 | ||
|
|
e6021b8fed | ||
|
|
326c0eed8f | ||
|
|
336792c07a | ||
|
|
570d2c6846 | ||
|
|
1ef4665073 | ||
|
|
d5540b927f | ||
|
|
a6cf585109 | ||
|
|
c0a8f3be49 | ||
|
|
7b4780cfb7 | ||
|
|
b94a712bb6 | ||
|
|
f42ccfc4e9 | ||
|
|
9eca747757 | ||
|
|
b7b6753640 | ||
|
|
40d0b9a5de | ||
|
|
40fc75f559 | ||
|
|
f1d060a92e | ||
|
|
e0e901291e | ||
|
|
886ac69a82 | ||
|
|
e0163e100a | ||
|
|
26a10cce8f | ||
|
|
cec903a4dc | ||
|
|
962d9c90d1 | ||
|
|
6d2eb4f973 | ||
|
|
a8cc5f41cf | ||
|
|
aa57b16cf5 | ||
|
|
cdea838a6c | ||
|
|
fb4bf9b0b9 | ||
|
|
a3e3868f92 | ||
|
|
70186cf8d9 | ||
|
|
fe59b265c5 | ||
|
|
a87458d25f | ||
|
|
35dd70c59e | ||
|
|
a198e96064 | ||
|
|
e3be7e0cfd | ||
|
|
460645cea2 | ||
|
|
f683e03891 | ||
|
|
2c71cea7a0 | ||
|
|
61b1ecce27 | ||
|
|
68257a441f | ||
|
|
e69da2ed2a | ||
|
|
c2a08ef355 | ||
|
|
1430b1ce90 | ||
|
|
1c9c744107 | ||
|
|
bfed126a7c | ||
|
|
44d1d992f8 | ||
|
|
7701f326d9 | ||
|
|
356cb6412f | ||
|
|
7bd3cf986d | ||
|
|
3948c9a187 | ||
|
|
d6b1b9c94d | ||
|
|
a676954116 | ||
|
|
d97c4f292e | ||
|
|
2d175a331f | ||
|
|
976305b791 | ||
|
|
a6a42eff80 | ||
|
|
96dddf1b3a | ||
|
|
c426c93cc5 | ||
|
|
1a43d93da2 | ||
|
|
575fbc9ffe | ||
|
|
c21da895b6 | ||
|
|
b172c7fcd4 | ||
|
|
61331b58d7 | ||
|
|
9ff76c0473 | ||
|
|
c9272c9218 | ||
|
|
36f0c17c8b | ||
|
|
aa406d1552 | ||
|
|
0cb771439f | ||
|
|
672d754238 | ||
|
|
0178fb0d4f | ||
|
|
19d8909b10 | ||
|
|
19f0fa7724 | ||
|
|
eefb1c8349 | ||
|
|
0e0d01a0b2 | ||
|
|
ac2c9c3a9b | ||
|
|
05f144ae50 | ||
|
|
a461fd415a | ||
|
|
ef1c3331ad | ||
|
|
e1a56be5c1 | ||
|
|
cf6fc4a510 | ||
|
|
67d21deff9 | ||
|
|
efc15bde26 | ||
|
|
b5d6ed3d9b | ||
|
|
7789e0bc26 | ||
|
|
0e2f0fb090 | ||
|
|
19696d206d | ||
|
|
9193aa5e02 | ||
|
|
bbf1eda3b0 | ||
|
|
d8e2e2a45f | ||
|
|
0fc15e6054 | ||
|
|
717240c8d4 | ||
|
|
453772859d | ||
|
|
98eea1171e | ||
|
|
ea49d22bce | ||
|
|
058186dfdc | ||
|
|
8134672436 | ||
|
|
ae0952455b | ||
|
|
a20f380284 | ||
|
|
6d83b019e1 | ||
|
|
40eb014c91 | ||
|
|
62f5a9eead | ||
|
|
74cbd11473 | ||
|
|
0d76eee6cd | ||
|
|
4b5e27a5e2 | ||
|
|
dcb0a18cd7 | ||
|
|
015dcc5631 | ||
|
|
537f1823b6 | ||
|
|
fc99010a3d | ||
|
|
fe14f8744d | ||
|
|
4dca031441 | ||
|
|
5366f895b2 | ||
|
|
95ba8cba60 | ||
|
|
775ac7ff68 | ||
|
|
a9fe086bcf | ||
|
|
e0f763caee | ||
|
|
c24e99a92b | ||
|
|
c1a327c5b2 | ||
|
|
68892091ec | ||
|
|
e87c6c6d28 | ||
|
|
0be569ccd6 | ||
|
|
8e686b10e8 | ||
|
|
ae203291b9 | ||
|
|
8b8008478d | ||
|
|
b4ba9d628b | ||
|
|
4520507869 | ||
|
|
e5a960b2df | ||
|
|
a35e522e75 | ||
|
|
a810be316f | ||
|
|
741b66aab2 | ||
|
|
d767d40c5f | ||
|
|
2b3fa796a1 | ||
|
|
f6cc9fd1cf | ||
|
|
4b13d7188c | ||
|
|
45e39917b5 | ||
|
|
27ffea3ea9 | ||
|
|
d2b2ef54e8 | ||
|
|
3fbe2e94da | ||
|
|
21af6a4e5c | ||
|
|
739349c2a1 | ||
|
|
994bb07efd | ||
|
|
1e9fe969fd | ||
|
|
1d651a9b53 | ||
|
|
22493005dc | ||
|
|
7ecd3c0d5e | ||
|
|
64050d39bf | ||
|
|
c7489dc0fa | ||
|
|
bb1b9e4163 | ||
|
|
b3bc8e684e | ||
|
|
696c78ecea | ||
|
|
7aea4ea209 | ||
|
|
35dc771528 | ||
|
|
c369c6fc26 | ||
|
|
af2dd56707 | ||
|
|
1287cb9f11 | ||
|
|
f0e9fa6659 | ||
|
|
7a1bcc134b | ||
|
|
87413b9355 | ||
|
|
6ed16916d6 | ||
|
|
754ae969e1 | ||
|
|
1ee0c83168 | ||
|
|
2812a07165 | ||
|
|
10be1383e5 | ||
|
|
4d356bcda8 | ||
|
|
da6fb3d0f3 | ||
|
|
56cb637bfa | ||
|
|
2872c94394 | ||
|
|
f307f33bf8 | ||
|
|
a095ba7e40 | ||
|
|
0dc1e13f9d | ||
|
|
f83600430a | ||
|
|
537123896b | ||
|
|
bc8863c3b1 | ||
|
|
b894c5a2a6 | ||
|
|
0ac4660510 | ||
|
|
672054177c | ||
|
|
820c92d38b | ||
|
|
9f051aea17 | ||
|
|
55cf934475 | ||
|
|
b690880332 | ||
|
|
7220a4d6f7 | ||
|
|
5abf01a88f | ||
|
|
51a4d19595 | ||
|
|
ad8fb74d9e | ||
|
|
447a8a920c | ||
|
|
0ba3ea98cb | ||
|
|
fc0b086cb1 | ||
|
|
7a40bd44e8 | ||
|
|
afe6815637 | ||
|
|
a64f3a58f7 | ||
|
|
2bb34176b7 | ||
|
|
6f80c6941d | ||
|
|
02d42747b7 | ||
|
|
5b81ecce04 | ||
|
|
8c94118e07 | ||
|
|
390cac84e3 | ||
|
|
ae6b5d9a6d | ||
|
|
ffb1bdff17 | ||
|
|
1440a0b162 | ||
|
|
b10755e34f | ||
|
|
683e9ee412 | ||
|
|
aa3886720f | ||
|
|
7ee7c60e77 | ||
|
|
0c52d3fcd4 | ||
|
|
8f425e6dde | ||
|
|
a1c897a8ca | ||
|
|
9fa6a144d0 | ||
|
|
54005c148a | ||
|
|
abe2e78283 | ||
|
|
edbb887d81 | ||
|
|
540aa1a496 | ||
|
|
3d31620160 | ||
|
|
6b983872fa | ||
|
|
bb7bbaf124 | ||
|
|
dad21bcca7 | ||
|
|
f75ea842d9 | ||
|
|
f7ee4c1d86 | ||
|
|
58c61a2557 | ||
|
|
730a611f7a | ||
|
|
ab68c15d2d | ||
|
|
564cd9b18c | ||
|
|
cacddfdf30 | ||
|
|
adbbaa532b | ||
|
|
2d81b47b6a | ||
|
|
1c4928a29b | ||
|
|
2181584f69 | ||
|
|
8bb21688e5 | ||
|
|
8cdf12e866 | ||
|
|
a1dae1fc15 | ||
|
|
2f43d660d5 | ||
|
|
920beaf6f5 | ||
|
|
6b28cd8698 | ||
|
|
323a968525 | ||
|
|
a26dfe3b7b | ||
|
|
ce91cab7ef | ||
|
|
ff48661f60 | ||
|
|
afe529fa0a | ||
|
|
5bb187a502 | ||
|
|
e5204423b0 | ||
|
|
8be54bcc5f | ||
|
|
3dfb05a25c | ||
|
|
ca84f4c8fe | ||
|
|
039df2bd46 | ||
|
|
0a84d9da76 | ||
|
|
33e41caf4a | ||
|
|
b2aba3f6db | ||
|
|
ece55d10d6 | ||
|
|
323241a4b8 | ||
|
|
bd3ace0885 | ||
|
|
ed4effdab7 | ||
|
|
2d1828513f | ||
|
|
505176b6ee | ||
|
|
853e70dcbe | ||
|
|
38cc471eaf | ||
|
|
704930f91a |
No files matched your search
@@ -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
|
||||
@@ -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 only** (*"Read the Contribution Guidelines"*) from your bug report, **and fill in all the other sections**.
|
||||
|
||||
**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.
|
||||
@@ -8,6 +8,7 @@ __pycache__/
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
LXMF/Utilities/LXMF
|
||||
RNS
|
||||
.Python
|
||||
build/
|
||||
|
||||
+31
@@ -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 ###########################################
|
||||
@@ -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
|
||||
@@ -0,0 +1,3 @@
|
||||
liberapay: Reticulum
|
||||
ko_fi: markqvist
|
||||
custom: "https://unsigned.io/donate"
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
Reticulum License
|
||||
|
||||
Copyright (c) 2020 Mark Qvist / unsigned.io
|
||||
Copyright (c) 2020-2025 Mark Qvist
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
@@ -9,8 +9,16 @@ 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 shall not be used in any kind of system which includes amongst
|
||||
its functions the ability to purposefully do harm to human beings.
|
||||
|
||||
- The Software shall not be used, directly or indirectly, in the creation of
|
||||
an artificial intelligence, machine learning or language model training
|
||||
dataset, including but not limited to any use that contributes to the
|
||||
training or development of such a model or algorithm.
|
||||
|
||||
- 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,
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import time
|
||||
import threading
|
||||
import RNS
|
||||
import RNS.vendor.umsgpack as msgpack
|
||||
|
||||
from .LXMF import APP_NAME, stamp_cost_from_app_data, pn_announce_data_is_valid
|
||||
from .LXMessage import LXMessage
|
||||
|
||||
class LXMFDeliveryAnnounceHandler:
|
||||
def __init__(self, lxmrouter):
|
||||
self.aspect_filter = APP_NAME+".delivery"
|
||||
self.receive_path_responses = True
|
||||
self.lxmrouter = lxmrouter
|
||||
|
||||
def received_announce(self, destination_hash, announced_identity, app_data):
|
||||
try:
|
||||
stamp_cost = stamp_cost_from_app_data(app_data)
|
||||
self.lxmrouter.update_stamp_cost(destination_hash, stamp_cost)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"An error occurred while trying to decode announced stamp cost. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||
|
||||
for lxmessage in self.lxmrouter.pending_outbound:
|
||||
if destination_hash == lxmessage.destination_hash:
|
||||
if lxmessage.method == LXMessage.DIRECT or lxmessage.method == LXMessage.OPPORTUNISTIC:
|
||||
lxmessage.next_delivery_attempt = time.time()
|
||||
|
||||
def outbound_trigger():
|
||||
while self.lxmrouter.outbound_processing_lock.locked(): time.sleep(0.1)
|
||||
self.lxmrouter.process_outbound()
|
||||
|
||||
threading.Thread(target=outbound_trigger, daemon=True).start()
|
||||
|
||||
|
||||
class LXMFPropagationAnnounceHandler:
|
||||
def __init__(self, lxmrouter):
|
||||
self.aspect_filter = APP_NAME+".propagation"
|
||||
self.receive_path_responses = True
|
||||
self.lxmrouter = lxmrouter
|
||||
|
||||
def received_announce(self, destination_hash, announced_identity, app_data, announce_packet_hash, is_path_response):
|
||||
try:
|
||||
if type(app_data) == bytes:
|
||||
if self.lxmrouter.propagation_node:
|
||||
if pn_announce_data_is_valid(app_data):
|
||||
data = msgpack.unpackb(app_data)
|
||||
node_timebase = int(data[1])
|
||||
propagation_enabled = data[2]
|
||||
propagation_transfer_limit = int(data[3])
|
||||
propagation_sync_limit = int(data[4])
|
||||
propagation_stamp_cost = int(data[5][0])
|
||||
propagation_stamp_cost_flexibility = int(data[5][1])
|
||||
peering_cost = int(data[5][2])
|
||||
metadata = data[6]
|
||||
|
||||
if destination_hash in self.lxmrouter.static_peers:
|
||||
static_peer = self.lxmrouter.peers[destination_hash]
|
||||
if not is_path_response or static_peer.last_heard == 0:
|
||||
self.lxmrouter.peer(destination_hash=destination_hash,
|
||||
timestamp=node_timebase,
|
||||
propagation_transfer_limit=propagation_transfer_limit,
|
||||
propagation_sync_limit=propagation_sync_limit,
|
||||
propagation_stamp_cost=propagation_stamp_cost,
|
||||
propagation_stamp_cost_flexibility=propagation_stamp_cost_flexibility,
|
||||
peering_cost=peering_cost,
|
||||
metadata=metadata)
|
||||
|
||||
else:
|
||||
if self.lxmrouter.autopeer and not is_path_response:
|
||||
if propagation_enabled == True:
|
||||
if RNS.Transport.hops_to(destination_hash) <= self.lxmrouter.autopeer_maxdepth:
|
||||
self.lxmrouter.peer(destination_hash=destination_hash,
|
||||
timestamp=node_timebase,
|
||||
propagation_transfer_limit=propagation_transfer_limit,
|
||||
propagation_sync_limit=propagation_sync_limit,
|
||||
propagation_stamp_cost=propagation_stamp_cost,
|
||||
propagation_stamp_cost_flexibility=propagation_stamp_cost_flexibility,
|
||||
peering_cost=peering_cost,
|
||||
metadata=metadata)
|
||||
|
||||
else:
|
||||
if destination_hash in self.lxmrouter.peers:
|
||||
RNS.log(f"Peer {self.lxmrouter.peers[destination_hash]} moved outside auto-peering range, breaking peering...")
|
||||
self.lxmrouter.unpeer(destination_hash, node_timebase)
|
||||
|
||||
elif propagation_enabled == False:
|
||||
self.lxmrouter.unpeer(destination_hash, node_timebase)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Error while evaluating propagation node announce, ignoring announce.", RNS.LOG_DEBUG)
|
||||
RNS.log(f"The contained exception was: {str(e)}", RNS.LOG_DEBUG)
|
||||
+170
-1706
File diff suppressed because it is too large.
Load diff
+642
@@ -0,0 +1,642 @@
|
||||
import os
|
||||
import time
|
||||
import threading
|
||||
|
||||
import RNS
|
||||
import RNS.vendor.umsgpack as msgpack
|
||||
import LXMF.LXStamper as LXStamper
|
||||
|
||||
from collections import deque
|
||||
from .LXMF import APP_NAME
|
||||
from .LXMF import PN_META_NAME
|
||||
|
||||
class LXMPeer:
|
||||
OFFER_REQUEST_PATH = "/offer"
|
||||
MESSAGE_GET_PATH = "/get"
|
||||
|
||||
IDLE = 0x00
|
||||
LINK_ESTABLISHING = 0x01
|
||||
LINK_READY = 0x02
|
||||
REQUEST_SENT = 0x03
|
||||
RESPONSE_RECEIVED = 0x04
|
||||
RESOURCE_TRANSFERRING = 0x05
|
||||
|
||||
ERROR_NO_IDENTITY = 0xf0
|
||||
ERROR_NO_ACCESS = 0xf1
|
||||
ERROR_INVALID_KEY = 0xf3
|
||||
ERROR_INVALID_DATA = 0xf4
|
||||
ERROR_INVALID_STAMP = 0xf5
|
||||
ERROR_THROTTLED = 0xf6
|
||||
ERROR_NOT_FOUND = 0xfd
|
||||
ERROR_TIMEOUT = 0xfe
|
||||
|
||||
STRATEGY_LAZY = 0x01
|
||||
STRATEGY_PERSISTENT = 0x02
|
||||
DEFAULT_SYNC_STRATEGY = STRATEGY_PERSISTENT
|
||||
|
||||
# Maximum amount of time a peer can
|
||||
# be unreachable before it is removed
|
||||
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):
|
||||
dictionary = msgpack.unpackb(peer_bytes)
|
||||
peer_destination_hash = dictionary["destination_hash"]
|
||||
peer_peering_timebase = dictionary["peering_timebase"]
|
||||
peer_alive = dictionary["alive"]
|
||||
peer_last_heard = dictionary["last_heard"]
|
||||
|
||||
peer = LXMPeer(router, peer_destination_hash)
|
||||
peer.peering_timebase = peer_peering_timebase
|
||||
peer.alive = peer_alive
|
||||
peer.last_heard = peer_last_heard
|
||||
|
||||
if "link_establishment_rate" in dictionary: peer.link_establishment_rate = dictionary["link_establishment_rate"]
|
||||
else: peer.link_establishment_rate = 0
|
||||
|
||||
if "sync_transfer_rate" in dictionary: peer.sync_transfer_rate = dictionary["sync_transfer_rate"]
|
||||
else: peer.sync_transfer_rate = 0
|
||||
|
||||
if "propagation_transfer_limit" in dictionary:
|
||||
try: peer.propagation_transfer_limit = float(dictionary["propagation_transfer_limit"])
|
||||
except Exception as e: peer.propagation_transfer_limit = None
|
||||
else: peer.propagation_transfer_limit = None
|
||||
|
||||
if "propagation_sync_limit" in dictionary:
|
||||
try: peer.propagation_sync_limit = int(dictionary["propagation_sync_limit"])
|
||||
except: peer.propagation_sync_limit = peer.propagation_transfer_limit
|
||||
else: peer.propagation_sync_limit = peer.propagation_transfer_limit
|
||||
|
||||
if "propagation_stamp_cost" in dictionary:
|
||||
try: peer.propagation_stamp_cost = int(dictionary["propagation_stamp_cost"])
|
||||
except: peer.propagation_stamp_cost = None
|
||||
else: peer.propagation_stamp_cost = None
|
||||
|
||||
if "propagation_stamp_cost_flexibility" in dictionary:
|
||||
try: peer.propagation_stamp_cost_flexibility = int(dictionary["propagation_stamp_cost_flexibility"])
|
||||
except: peer.propagation_stamp_cost_flexibility = None
|
||||
else: peer.propagation_stamp_cost_flexibility = None
|
||||
|
||||
if "peering_cost" in dictionary:
|
||||
try: peer.peering_cost = int(dictionary["peering_cost"])
|
||||
except: peer.peering_cost = None
|
||||
else: peer.peering_cost = None
|
||||
|
||||
if "sync_strategy" in dictionary:
|
||||
try: peer.sync_strategy = int(dictionary["sync_strategy"])
|
||||
except: peer.sync_strategy = LXMPeer.DEFAULT_SYNC_STRATEGY
|
||||
else: peer.sync_strategy = LXMPeer.DEFAULT_SYNC_STRATEGY
|
||||
|
||||
if "offered" in dictionary: peer.offered = dictionary["offered"]
|
||||
else: peer.offered = 0
|
||||
if "outgoing" in dictionary: peer.outgoing = dictionary["outgoing"]
|
||||
else: peer.outgoing = 0
|
||||
if "incoming" in dictionary: peer.incoming = dictionary["incoming"]
|
||||
else: peer.incoming = 0
|
||||
if "rx_bytes" in dictionary: peer.rx_bytes = dictionary["rx_bytes"]
|
||||
else: peer.rx_bytes = 0
|
||||
if "tx_bytes" in dictionary: peer.tx_bytes = dictionary["tx_bytes"]
|
||||
else: peer.tx_bytes = 0
|
||||
if "last_sync_attempt" in dictionary: peer.last_sync_attempt = dictionary["last_sync_attempt"]
|
||||
else: peer.last_sync_attempt = 0
|
||||
if "peering_key" in dictionary: peer.peering_key = dictionary["peering_key"]
|
||||
else: peer.peering_key = None
|
||||
if "metadata" in dictionary: peer.metadata = dictionary["metadata"]
|
||||
else: peer.metadata = None
|
||||
|
||||
hm_count = 0
|
||||
for transient_id in dictionary["handled_ids"]:
|
||||
if transient_id in router.propagation_entries:
|
||||
peer.add_handled_message(transient_id)
|
||||
hm_count += 1
|
||||
|
||||
um_count = 0
|
||||
for transient_id in dictionary["unhandled_ids"]:
|
||||
if transient_id in router.propagation_entries:
|
||||
peer.add_unhandled_message(transient_id)
|
||||
um_count += 1
|
||||
|
||||
peer._hm_count = hm_count
|
||||
peer._um_count = um_count
|
||||
peer._hm_counts_synced = True
|
||||
peer._um_counts_synced = True
|
||||
|
||||
del dictionary
|
||||
return peer
|
||||
|
||||
def to_bytes(self):
|
||||
dictionary = {}
|
||||
dictionary["peering_timebase"] = self.peering_timebase
|
||||
dictionary["alive"] = self.alive
|
||||
dictionary["metadata"] = self.metadata
|
||||
dictionary["last_heard"] = self.last_heard
|
||||
dictionary["sync_strategy"] = self.sync_strategy
|
||||
dictionary["peering_key"] = self.peering_key
|
||||
dictionary["destination_hash"] = self.destination_hash
|
||||
dictionary["link_establishment_rate"] = self.link_establishment_rate
|
||||
dictionary["sync_transfer_rate"] = self.sync_transfer_rate
|
||||
dictionary["propagation_transfer_limit"] = self.propagation_transfer_limit
|
||||
dictionary["propagation_sync_limit"] = self.propagation_sync_limit
|
||||
dictionary["propagation_stamp_cost"] = self.propagation_stamp_cost
|
||||
dictionary["propagation_stamp_cost_flexibility"] = self.propagation_stamp_cost_flexibility
|
||||
dictionary["peering_cost"] = self.peering_cost
|
||||
dictionary["last_sync_attempt"] = self.last_sync_attempt
|
||||
dictionary["offered"] = self.offered
|
||||
dictionary["outgoing"] = self.outgoing
|
||||
dictionary["incoming"] = self.incoming
|
||||
dictionary["rx_bytes"] = self.rx_bytes
|
||||
dictionary["tx_bytes"] = self.tx_bytes
|
||||
|
||||
handled_ids = []
|
||||
for transient_id in self.handled_messages:
|
||||
handled_ids.append(transient_id)
|
||||
|
||||
unhandled_ids = []
|
||||
for transient_id in self.unhandled_messages:
|
||||
unhandled_ids.append(transient_id)
|
||||
|
||||
dictionary["handled_ids"] = handled_ids
|
||||
dictionary["unhandled_ids"] = unhandled_ids
|
||||
|
||||
peer_bytes = msgpack.packb(dictionary)
|
||||
del dictionary
|
||||
|
||||
return peer_bytes
|
||||
|
||||
def __init__(self, router, destination_hash, sync_strategy=DEFAULT_SYNC_STRATEGY):
|
||||
self.alive = False
|
||||
self.last_heard = 0
|
||||
self.sync_strategy = sync_strategy
|
||||
self.peering_key = None
|
||||
self.peering_cost = None
|
||||
self.metadata = None
|
||||
|
||||
self.next_sync_attempt = 0
|
||||
self.last_sync_attempt = 0
|
||||
self.sync_backoff = 0
|
||||
self.peering_timebase = 0
|
||||
self.link_establishment_rate = 0
|
||||
self.sync_transfer_rate = 0
|
||||
|
||||
self.propagation_transfer_limit = None
|
||||
self.propagation_sync_limit = None
|
||||
self.propagation_stamp_cost = None
|
||||
self.propagation_stamp_cost_flexibility = None
|
||||
self.currently_transferring_messages = None
|
||||
self.handled_messages_queue = deque()
|
||||
self.unhandled_messages_queue = deque()
|
||||
|
||||
self.offered = 0 # Messages offered to this peer
|
||||
self.outgoing = 0 # Messages transferred to this peer
|
||||
self.incoming = 0 # Messages received from this peer
|
||||
self.rx_bytes = 0 # Bytes received from this peer
|
||||
self.tx_bytes = 0 # Bytes sent to this peer
|
||||
|
||||
self._hm_count = 0
|
||||
self._um_count = 0
|
||||
self._hm_counts_synced = False
|
||||
self._um_counts_synced = False
|
||||
|
||||
self._peering_key_lock = threading.Lock()
|
||||
|
||||
self.link = None
|
||||
self.state = LXMPeer.IDLE
|
||||
|
||||
self.last_offer = []
|
||||
|
||||
self.router = router
|
||||
self.destination_hash = destination_hash
|
||||
self.identity = RNS.Identity.recall(destination_hash)
|
||||
if self.identity != None:
|
||||
self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
|
||||
else:
|
||||
self.destination = None
|
||||
RNS.log(f"Could not recall identity for LXMF propagation peer {RNS.prettyhexrep(self.destination_hash)}, will retry identity resolution on next sync", RNS.LOG_WARNING)
|
||||
|
||||
def peering_key_ready(self):
|
||||
if not self.peering_cost: return False
|
||||
if type(self.peering_key) == list and len(self.peering_key) == 2:
|
||||
value = self.peering_key[1]
|
||||
if value >= self.peering_cost: return True
|
||||
else:
|
||||
RNS.log(f"Peering key value mismatch for {self}. Current value is {value}, but peer requires {self.peering_cost}. Scheduling regeneration...", RNS.LOG_WARNING)
|
||||
self.peering_key = None
|
||||
|
||||
return False
|
||||
|
||||
def peering_key_value(self):
|
||||
if type(self.peering_key) == list and len(self.peering_key) == 2: return self.peering_key[1]
|
||||
else: return None
|
||||
|
||||
def generate_peering_key(self):
|
||||
if self.peering_cost == None: return False
|
||||
with self._peering_key_lock:
|
||||
if self.peering_key != None: return True
|
||||
else:
|
||||
RNS.log(f"Generating peering key for {self}", RNS.LOG_NOTICE)
|
||||
if self.router.identity == None:
|
||||
RNS.log(f"Could not update peering key for {self} since the local LXMF router identity is not configured", RNS.LOG_ERROR)
|
||||
return False
|
||||
|
||||
if self.identity == None:
|
||||
self.identity = RNS.Identity.recall(destination_hash)
|
||||
if self.identity == None:
|
||||
RNS.log(f"Could not update peering key for {self} since its identity could not be recalled", RNS.LOG_ERROR)
|
||||
return False
|
||||
|
||||
key_material = self.identity.hash+self.router.identity.hash
|
||||
peering_key, value = LXStamper.generate_stamp(key_material, self.peering_cost, expand_rounds=LXStamper.WORKBLOCK_EXPAND_ROUNDS_PEERING)
|
||||
if value >= self.peering_cost:
|
||||
self.peering_key = [peering_key, value]
|
||||
RNS.log(f"Peering key successfully generated for {self}", RNS.LOG_NOTICE)
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
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()
|
||||
|
||||
sync_time_reached = time.time() > self.next_sync_attempt
|
||||
stamp_costs_known = self.propagation_stamp_cost != None and self.propagation_stamp_cost_flexibility != None and self.peering_cost != None
|
||||
peering_key_ready = self.peering_key_ready()
|
||||
sync_checks = sync_time_reached and stamp_costs_known and peering_key_ready
|
||||
|
||||
if not sync_checks:
|
||||
try:
|
||||
if not sync_time_reached:
|
||||
postpone_reason = " due to previous failures"
|
||||
if self.last_sync_attempt > self.last_heard: self.alive = False
|
||||
elif not stamp_costs_known:
|
||||
postpone_reason = " since its required stamp costs are not yet known"
|
||||
elif not peering_key_ready:
|
||||
postpone_reason = " since a peering key has not been generated yet"
|
||||
def job(): self.generate_peering_key()
|
||||
threading.Thread(target=job, daemon=True).start()
|
||||
|
||||
delay = self.next_sync_attempt-time.time()
|
||||
postpone_delay = f" for {RNS.prettytime(delay)}" if delay > 0 else ""
|
||||
RNS.log(f"Postponing sync with peer {RNS.prettyhexrep(self.destination_hash)}{postpone_delay}{postpone_reason}", RNS.LOG_DEBUG)
|
||||
except Exception as e:
|
||||
RNS.trace_exception(e)
|
||||
|
||||
else:
|
||||
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 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:
|
||||
if self.identity == None:
|
||||
self.identity = RNS.Identity.recall(destination_hash)
|
||||
if self.identity != None:
|
||||
self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
|
||||
|
||||
if self.destination != None:
|
||||
if len(self.unhandled_messages) == 0:
|
||||
RNS.log(f"Sync requested for {self}, but no unhandled messages exist for peer. Sync complete.", RNS.LOG_DEBUG)
|
||||
return
|
||||
|
||||
if len(self.unhandled_messages) > 0:
|
||||
if self.currently_transferring_messages != None:
|
||||
RNS.log(f"Sync requested for {self}, but current message transfer index was not clear. Aborting.", RNS.LOG_ERROR)
|
||||
return
|
||||
|
||||
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
|
||||
min_accepted_cost = min(0, self.propagation_stamp_cost-self.propagation_stamp_cost_flexibility)
|
||||
|
||||
RNS.log("Synchronisation link to peer "+RNS.prettyhexrep(self.destination_hash)+" established, preparing sync offer...", RNS.LOG_DEBUG)
|
||||
unhandled_entries = []
|
||||
unhandled_ids = []
|
||||
purged_ids = []
|
||||
low_value_ids = []
|
||||
for transient_id in self.unhandled_messages:
|
||||
if transient_id in self.router.propagation_entries:
|
||||
if self.router.get_stamp_value(transient_id) < min_accepted_cost: low_value_ids.append(transient_id)
|
||||
else:
|
||||
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(f"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.remove_unhandled_message(transient_id)
|
||||
|
||||
for transient_id in low_value_ids:
|
||||
RNS.log(f"Dropping unhandled message {RNS.prettyhexrep(transient_id)} for peer {RNS.prettyhexrep(self.destination_hash)} since its stamp value is lower than peer requirement of {min_accepted_cost}.", RNS.LOG_DEBUG)
|
||||
self.remove_unhandled_message(transient_id)
|
||||
|
||||
unhandled_entries.sort(key=lambda e: e[1], reverse=False)
|
||||
per_message_overhead = 16 # Really only 2 bytes, but set a bit higher for now
|
||||
cumulative_size = 24 # Initialised to highest reasonable binary structure overhead
|
||||
RNS.log(f"Syncing to peer with per-message limit {RNS.prettysize(self.propagation_transfer_limit*1000)} and sync limit {RNS.prettysize(self.propagation_sync_limit*1000)}") # TODO: Remove debug
|
||||
|
||||
for unhandled_entry in unhandled_entries:
|
||||
transient_id = unhandled_entry[0]
|
||||
weight = unhandled_entry[1]
|
||||
lxm_size = unhandled_entry[2]
|
||||
lxm_transfer_size = lxm_size+per_message_overhead
|
||||
next_size = cumulative_size + lxm_transfer_size
|
||||
|
||||
if self.propagation_transfer_limit != None and lxm_transfer_size > (self.propagation_transfer_limit*1000):
|
||||
self.remove_unhandled_message(transient_id)
|
||||
self.add_handled_message(transient_id)
|
||||
continue
|
||||
|
||||
if self.propagation_sync_limit != None and next_size >= (self.propagation_sync_limit*1000):
|
||||
continue
|
||||
|
||||
cumulative_size += lxm_transfer_size
|
||||
unhandled_ids.append(transient_id)
|
||||
|
||||
offer = [self.peering_key[0], unhandled_ids]
|
||||
|
||||
RNS.log(f"Offering {len(unhandled_ids)} messages to peer {RNS.prettyhexrep(self.destination.hash)} ({RNS.prettysize(len(msgpack.packb(unhandled_ids)))})", RNS.LOG_VERBOSE)
|
||||
self.last_offer = unhandled_ids
|
||||
self.link.request(LXMPeer.OFFER_REQUEST_PATH, offer, response_callback=self.offer_response, failed_callback=self.request_failed)
|
||||
self.state = LXMPeer.REQUEST_SENT
|
||||
|
||||
else:
|
||||
RNS.log(f"Could not request sync to peer {RNS.prettyhexrep(self.destination_hash)} since its identity could not be recalled.", RNS.LOG_ERROR)
|
||||
|
||||
def request_failed(self, request_receipt):
|
||||
RNS.log(f"Sync request to peer {self.destination} failed", RNS.LOG_DEBUG)
|
||||
if self.link != None: self.link.teardown()
|
||||
self.state = LXMPeer.IDLE
|
||||
|
||||
def offer_response(self, request_receipt):
|
||||
try:
|
||||
self.state = LXMPeer.RESPONSE_RECEIVED
|
||||
response = request_receipt.response
|
||||
|
||||
wanted_messages = []
|
||||
wanted_message_ids = []
|
||||
|
||||
if response == LXMPeer.ERROR_NO_IDENTITY:
|
||||
if self.link != None:
|
||||
RNS.log("Remote peer indicated that no identification was received, retrying...", RNS.LOG_VERBOSE)
|
||||
self.link.identify()
|
||||
self.state = LXMPeer.LINK_READY
|
||||
self.sync()
|
||||
return
|
||||
|
||||
elif response == LXMPeer.ERROR_NO_ACCESS:
|
||||
RNS.log("Remote indicated that access was denied, breaking peering", RNS.LOG_VERBOSE)
|
||||
self.router.unpeer(self.destination_hash)
|
||||
return
|
||||
|
||||
elif response == LXMPeer.ERROR_THROTTLED:
|
||||
throttle_time = self.router.PN_STAMP_THROTTLE
|
||||
RNS.log(f"Remote indicated that we're throttled, postponing sync for {RNS.prettytime(throttle_time)}", RNS.LOG_VERBOSE)
|
||||
self.next_sync_attempt = time.time()+throttle_time
|
||||
return
|
||||
|
||||
elif response == False:
|
||||
# Peer already has all advertised messages
|
||||
for transient_id in self.last_offer:
|
||||
if transient_id in self.unhandled_messages:
|
||||
self.add_handled_message(transient_id)
|
||||
self.remove_unhandled_message(transient_id)
|
||||
|
||||
|
||||
elif response == True:
|
||||
# Peer wants all advertised messages
|
||||
for transient_id in self.last_offer:
|
||||
wanted_messages.append(self.router.propagation_entries[transient_id])
|
||||
wanted_message_ids.append(transient_id)
|
||||
|
||||
else:
|
||||
# Peer wants some advertised messages
|
||||
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:
|
||||
self.add_handled_message(transient_id)
|
||||
self.remove_unhandled_message(transient_id)
|
||||
|
||||
for transient_id in response:
|
||||
wanted_messages.append(self.router.propagation_entries[transient_id])
|
||||
wanted_message_ids.append(transient_id)
|
||||
|
||||
if len(wanted_messages) > 0:
|
||||
RNS.log(f"Peer {RNS.prettyhexrep(self.destination_hash)} wanted {str(len(wanted_messages))} of the available messages", RNS.LOG_VERBOSE)
|
||||
|
||||
lxm_list = []
|
||||
for message_entry in wanted_messages:
|
||||
file_path = message_entry[1]
|
||||
if os.path.isfile(file_path):
|
||||
file = open(file_path, "rb")
|
||||
lxmf_data = file.read()
|
||||
file.close()
|
||||
lxm_list.append(lxmf_data)
|
||||
|
||||
data = msgpack.packb([time.time(), lxm_list])
|
||||
RNS.log(f"Total transfer size for this sync is {RNS.prettysize(len(data))}", RNS.LOG_VERBOSE)
|
||||
resource = RNS.Resource(data, self.link, callback = self.resource_concluded)
|
||||
self.currently_transferring_messages = wanted_message_ids
|
||||
self.current_sync_transfer_started = time.time()
|
||||
self.state = LXMPeer.RESOURCE_TRANSFERRING
|
||||
|
||||
else:
|
||||
RNS.log(f"Peer {RNS.prettyhexrep(self.destination_hash)} did not request any of the available messages, sync completed", RNS.LOG_VERBOSE)
|
||||
self.offered += len(self.last_offer)
|
||||
if self.link != None:
|
||||
self.link.teardown()
|
||||
|
||||
self.link = None
|
||||
self.state = LXMPeer.IDLE
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Error while handling offer response from peer "+str(self.destination), RNS.LOG_ERROR)
|
||||
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
if self.link != None:
|
||||
self.link.teardown()
|
||||
|
||||
self.link = None
|
||||
self.state = LXMPeer.IDLE
|
||||
|
||||
def resource_concluded(self, resource):
|
||||
if resource.status == RNS.Resource.COMPLETE:
|
||||
if self.currently_transferring_messages == None:
|
||||
RNS.log(f"Sync transfer completed on {self}, but transferred message index was unavailable. Aborting.", RNS.LOG_ERROR)
|
||||
if self.link != None: self.link.teardown()
|
||||
self.link = None
|
||||
self.state = LXMPeer.IDLE
|
||||
|
||||
for transient_id in self.currently_transferring_messages:
|
||||
self.add_handled_message(transient_id)
|
||||
self.remove_unhandled_message(transient_id)
|
||||
|
||||
if self.link != None: self.link.teardown()
|
||||
self.link = None
|
||||
self.state = LXMPeer.IDLE
|
||||
|
||||
rate_str = ""
|
||||
if self.current_sync_transfer_started != None:
|
||||
self.sync_transfer_rate = (resource.get_transfer_size()*8)/(time.time()-self.current_sync_transfer_started)
|
||||
rate_str = f" at {RNS.prettyspeed(self.sync_transfer_rate)}"
|
||||
|
||||
RNS.log(f"Syncing {len(self.currently_transferring_messages)} messages to peer {RNS.prettyhexrep(self.destination_hash)} completed{rate_str}", RNS.LOG_VERBOSE)
|
||||
self.alive = True
|
||||
self.last_heard = time.time()
|
||||
self.offered += len(self.last_offer)
|
||||
self.outgoing += len(self.currently_transferring_messages)
|
||||
self.tx_bytes += resource.get_data_size()
|
||||
|
||||
self.currently_transferring_messages = None
|
||||
self.current_sync_transfer_started = None
|
||||
|
||||
if self.sync_strategy == self.STRATEGY_PERSISTENT:
|
||||
if self.unhandled_message_count > 0: self.sync()
|
||||
|
||||
else:
|
||||
RNS.log("Resource transfer for LXMF peer sync failed to "+str(self.destination), RNS.LOG_VERBOSE)
|
||||
if self.link != None: self.link.teardown()
|
||||
self.link = None
|
||||
self.state = LXMPeer.IDLE
|
||||
self.currently_transferring_messages = None
|
||||
self.current_sync_transfer_started = None
|
||||
|
||||
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):
|
||||
self.link = None
|
||||
self.state = LXMPeer.IDLE
|
||||
|
||||
def queued_items(self):
|
||||
return len(self.handled_messages_queue) > 0 or len(self.unhandled_messages_queue) > 0
|
||||
|
||||
def queue_unhandled_message(self, transient_id):
|
||||
self.unhandled_messages_queue.append(transient_id)
|
||||
|
||||
def queue_handled_message(self, transient_id):
|
||||
self.handled_messages_queue.append(transient_id)
|
||||
|
||||
def process_queues(self):
|
||||
if len(self.unhandled_messages_queue) > 0 or len(self.handled_messages_queue) > 0:
|
||||
handled_messages = self.handled_messages
|
||||
unhandled_messages = self.unhandled_messages
|
||||
|
||||
while len(self.handled_messages_queue) > 0:
|
||||
transient_id = self.handled_messages_queue.pop()
|
||||
if not transient_id in handled_messages: self.add_handled_message(transient_id)
|
||||
if transient_id in unhandled_messages: self.remove_unhandled_message(transient_id)
|
||||
|
||||
while len(self.unhandled_messages_queue) > 0:
|
||||
transient_id = self.unhandled_messages_queue.pop()
|
||||
if not transient_id in handled_messages and not transient_id in unhandled_messages:
|
||||
self.add_unhandled_message(transient_id)
|
||||
|
||||
del handled_messages, unhandled_messages
|
||||
|
||||
@property
|
||||
def handled_messages(self):
|
||||
pes = self.router.propagation_entries.copy()
|
||||
hm = list(filter(lambda tid: self.destination_hash in pes[tid][4], pes))
|
||||
self._hm_count = len(hm); del pes
|
||||
self._hm_counts_synced = True
|
||||
return hm
|
||||
|
||||
@property
|
||||
def unhandled_messages(self):
|
||||
pes = self.router.propagation_entries.copy()
|
||||
um = list(filter(lambda tid: self.destination_hash in pes[tid][5], pes))
|
||||
self._um_count = len(um); del pes
|
||||
self._um_counts_synced = True
|
||||
return um
|
||||
|
||||
@property
|
||||
def handled_message_count(self):
|
||||
if not self._hm_counts_synced: self._update_counts()
|
||||
return self._hm_count
|
||||
|
||||
@property
|
||||
def unhandled_message_count(self):
|
||||
if not self._um_counts_synced: self._update_counts()
|
||||
return self._um_count
|
||||
|
||||
@property
|
||||
def acceptance_rate(self):
|
||||
return 0 if self.offered == 0 else (self.outgoing/self.offered)
|
||||
|
||||
def _update_counts(self):
|
||||
if not self._hm_counts_synced:
|
||||
hm = self.handled_messages; del hm
|
||||
|
||||
if not self._um_counts_synced:
|
||||
um = self.unhandled_messages; del um
|
||||
|
||||
def add_handled_message(self, transient_id):
|
||||
if transient_id in self.router.propagation_entries:
|
||||
if not self.destination_hash in self.router.propagation_entries[transient_id][4]:
|
||||
self.router.propagation_entries[transient_id][4].append(self.destination_hash)
|
||||
self._hm_counts_synced = False
|
||||
|
||||
def add_unhandled_message(self, transient_id):
|
||||
if transient_id in self.router.propagation_entries:
|
||||
if not self.destination_hash in self.router.propagation_entries[transient_id][5]:
|
||||
self.router.propagation_entries[transient_id][5].append(self.destination_hash)
|
||||
self._um_count += 1
|
||||
|
||||
def remove_handled_message(self, transient_id):
|
||||
if transient_id in self.router.propagation_entries:
|
||||
if self.destination_hash in self.router.propagation_entries[transient_id][4]:
|
||||
self.router.propagation_entries[transient_id][4].remove(self.destination_hash)
|
||||
self._hm_counts_synced = False
|
||||
|
||||
def remove_unhandled_message(self, transient_id):
|
||||
if transient_id in self.router.propagation_entries:
|
||||
if self.destination_hash in self.router.propagation_entries[transient_id][5]:
|
||||
self.router.propagation_entries[transient_id][5].remove(self.destination_hash)
|
||||
self._um_counts_synced = False
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
if type(self.metadata) != dict: return None
|
||||
else:
|
||||
if not PN_META_NAME in self.metadata: return None
|
||||
else:
|
||||
try: return self.metadata[PN_META_NAME].decode("utf-8")
|
||||
except: return None
|
||||
|
||||
def __str__(self):
|
||||
if self.destination_hash: return RNS.prettyhexrep(self.destination_hash)
|
||||
else: return "<Unknown>"
|
||||
+2728
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,825 @@
|
||||
import RNS
|
||||
import RNS.vendor.umsgpack as msgpack
|
||||
|
||||
import os
|
||||
import time
|
||||
import base64
|
||||
import multiprocessing
|
||||
|
||||
import LXMF.LXStamper as LXStamper
|
||||
from .LXMF import APP_NAME
|
||||
|
||||
|
||||
class LXMessage:
|
||||
GENERATING = 0x00
|
||||
OUTBOUND = 0x01
|
||||
SENDING = 0x02
|
||||
SENT = 0x04
|
||||
DELIVERED = 0x08
|
||||
REJECTED = 0xFD
|
||||
CANCELLED = 0xFE
|
||||
FAILED = 0xFF
|
||||
states = [GENERATING, OUTBOUND, SENDING, SENT, DELIVERED, REJECTED, CANCELLED, FAILED]
|
||||
|
||||
UNKNOWN = 0x00
|
||||
PACKET = 0x01
|
||||
RESOURCE = 0x02
|
||||
representations = [UNKNOWN, PACKET, RESOURCE]
|
||||
|
||||
OPPORTUNISTIC = 0x01
|
||||
DIRECT = 0x02
|
||||
PROPAGATED = 0x03
|
||||
PAPER = 0x05
|
||||
valid_methods = [OPPORTUNISTIC, DIRECT, PROPAGATED, PAPER]
|
||||
|
||||
SOURCE_UNKNOWN = 0x01
|
||||
SIGNATURE_INVALID = 0x02
|
||||
unverified_reasons = [SOURCE_UNKNOWN, SIGNATURE_INVALID]
|
||||
|
||||
DESTINATION_LENGTH = RNS.Identity.TRUNCATED_HASHLENGTH//8
|
||||
SIGNATURE_LENGTH = RNS.Identity.SIGLENGTH//8
|
||||
TICKET_LENGTH = RNS.Identity.TRUNCATED_HASHLENGTH//8
|
||||
|
||||
# Default ticket expiry is 3 weeks, with an
|
||||
# additional grace period of 5 days, allowing
|
||||
# for timekeeping inaccuracies. Tickets will
|
||||
# automatically renew when there is less than
|
||||
# 14 days to expiry.
|
||||
TICKET_EXPIRY = 21*24*60*60
|
||||
TICKET_GRACE = 5*24*60*60
|
||||
TICKET_RENEW = 14*24*60*60
|
||||
TICKET_INTERVAL = 1*24*60*60
|
||||
COST_TICKET = 0x100
|
||||
|
||||
# LXMF overhead is 112 bytes per message:
|
||||
# 16 bytes for destination hash
|
||||
# 16 bytes for source hash
|
||||
# 64 bytes for Ed25519 signature
|
||||
# 8 bytes for timestamp
|
||||
# 8 bytes for msgpack structure
|
||||
TIMESTAMP_SIZE = 8
|
||||
STRUCT_OVERHEAD = 8
|
||||
LXMF_OVERHEAD = 2*DESTINATION_LENGTH + SIGNATURE_LENGTH + TIMESTAMP_SIZE + STRUCT_OVERHEAD
|
||||
|
||||
# With an MTU of 500, the maximum amount of data
|
||||
# we can send in a single encrypted packet is
|
||||
# 391 bytes.
|
||||
ENCRYPTED_PACKET_MDU = RNS.Packet.ENCRYPTED_MDU + TIMESTAMP_SIZE
|
||||
|
||||
# The max content length we can fit in LXMF message
|
||||
# inside a single RNS packet is the encrypted MDU, minus
|
||||
# the LXMF overhead. We can optimise a bit though, by
|
||||
# inferring the destination hash from the destination
|
||||
# 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 295 bytes. If a message
|
||||
# is larger than that, a Reticulum link will be used.
|
||||
ENCRYPTED_PACKET_MAX_CONTENT = ENCRYPTED_PACKET_MDU - LXMF_OVERHEAD + DESTINATION_LENGTH
|
||||
|
||||
# Links can carry a larger MDU, due to less overhead per
|
||||
# packet. The link MDU with default Reticulum parameters
|
||||
# is 431 bytes.
|
||||
LINK_PACKET_MDU = RNS.Link.MDU
|
||||
|
||||
# Which means that we can deliver single-packet LXMF
|
||||
# messages with content of up to 319 bytes over a link.
|
||||
# If a message is larger than that, LXMF will sequence
|
||||
# and transfer it as a RNS resource over the link instead.
|
||||
LINK_PACKET_MAX_CONTENT = LINK_PACKET_MDU - LXMF_OVERHEAD
|
||||
|
||||
# For plain packets without encryption, we can
|
||||
# fit up to 368 bytes of content.
|
||||
PLAIN_PACKET_MDU = RNS.Packet.PLAIN_MDU
|
||||
PLAIN_PACKET_MAX_CONTENT = PLAIN_PACKET_MDU - LXMF_OVERHEAD + DESTINATION_LENGTH
|
||||
|
||||
# Descriptive strings regarding transport encryption
|
||||
ENCRYPTION_DESCRIPTION_AES = "AES-128"
|
||||
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)+">"
|
||||
else:
|
||||
return "<LXMessage>"
|
||||
|
||||
def __init__(self, destination, source, content = "", title = "", fields = None, desired_method = None, destination_hash = None, source_hash = None, stamp_cost=None, include_ticket=False):
|
||||
|
||||
if isinstance(destination, RNS.Destination) or destination == None:
|
||||
self.__destination = destination
|
||||
if destination != None:
|
||||
self.destination_hash = destination.hash
|
||||
else:
|
||||
self.destination_hash = destination_hash
|
||||
else:
|
||||
raise ValueError("LXMessage initialised with invalid destination")
|
||||
|
||||
if isinstance(source, RNS.Destination) or source == None:
|
||||
self.__source = source
|
||||
if source != None:
|
||||
self.source_hash = source.hash
|
||||
else:
|
||||
self.source_hash = source_hash
|
||||
else:
|
||||
raise ValueError("LXMessage initialised with invalid source")
|
||||
|
||||
if title == None:
|
||||
title = ""
|
||||
|
||||
if type(title) == bytes:
|
||||
self.set_title_from_bytes(title)
|
||||
else:
|
||||
self.set_title_from_string(title)
|
||||
|
||||
if type(content) == bytes:
|
||||
self.set_content_from_bytes(content)
|
||||
else:
|
||||
self.set_content_from_string(content)
|
||||
|
||||
self.set_fields(fields)
|
||||
|
||||
self.payload = None
|
||||
self.timestamp = None
|
||||
self.signature = None
|
||||
self.hash = None
|
||||
self.transient_id = None
|
||||
self.packed = None
|
||||
self.state = LXMessage.GENERATING
|
||||
self.method = LXMessage.UNKNOWN
|
||||
self.progress = 0.0
|
||||
self.rssi = None
|
||||
self.snr = None
|
||||
self.q = None
|
||||
|
||||
self.stamp = None
|
||||
self.stamp_cost = stamp_cost
|
||||
self.stamp_value = None
|
||||
self.stamp_valid = False
|
||||
self.stamp_checked = False
|
||||
self.propagation_stamp = None
|
||||
self.propagation_stamp_value = None
|
||||
self.propagation_stamp_valid = False
|
||||
self.propagation_target_cost = None
|
||||
self.defer_stamp = True
|
||||
self.defer_propagation_stamp = True
|
||||
self.outbound_ticket = None
|
||||
self.include_ticket = include_ticket
|
||||
|
||||
self.propagation_packed = None
|
||||
self.paper_packed = None
|
||||
|
||||
self.incoming = False
|
||||
self.signature_validated = False
|
||||
self.unverified_reason = None
|
||||
self.ratchet_id = None
|
||||
|
||||
self.representation = LXMessage.UNKNOWN
|
||||
self.desired_method = desired_method
|
||||
self.delivery_attempts = 0
|
||||
self.transport_encrypted = False
|
||||
self.transport_encryption = None
|
||||
self.ratchet_id = None
|
||||
self.packet_representation = None
|
||||
self.resource_representation = None
|
||||
self.__delivery_destination = None
|
||||
self.__delivery_callback = None
|
||||
self.__pn_encrypted_data = None
|
||||
self.failed_callback = None
|
||||
|
||||
self.deferred_stamp_generating = False
|
||||
|
||||
def set_title_from_string(self, title_string):
|
||||
self.title = title_string.encode("utf-8")
|
||||
|
||||
def set_title_from_bytes(self, title_bytes):
|
||||
self.title = title_bytes
|
||||
|
||||
def title_as_string(self):
|
||||
return self.title.decode("utf-8")
|
||||
|
||||
def set_content_from_string(self, content_string):
|
||||
self.content = content_string.encode("utf-8")
|
||||
|
||||
def set_content_from_bytes(self, content_bytes):
|
||||
self.content = content_bytes
|
||||
|
||||
def content_as_string(self):
|
||||
try:
|
||||
return self.content.decode("utf-8")
|
||||
except Exception as e:
|
||||
RNS.log(f"{self} could not decode message content as string: {e}")
|
||||
return None
|
||||
|
||||
def set_fields(self, fields):
|
||||
if isinstance(fields, dict) or fields == None:
|
||||
self.fields = fields or {}
|
||||
else:
|
||||
raise ValueError("LXMessage property \"fields\" can only be dict or None")
|
||||
|
||||
def get_fields(self):
|
||||
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:
|
||||
if isinstance(destination, RNS.Destination):
|
||||
self.__destination = destination
|
||||
else:
|
||||
raise ValueError("Invalid destination set on LXMessage")
|
||||
else:
|
||||
raise ValueError("Cannot reassign destination on LXMessage")
|
||||
|
||||
@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:
|
||||
if isinstance(source, RNS.Destination):
|
||||
self.__source = source
|
||||
else:
|
||||
raise ValueError("Invalid source set on LXMessage")
|
||||
else:
|
||||
raise ValueError("Cannot reassign source on LXMessage")
|
||||
|
||||
def set_delivery_destination(self, delivery_destination):
|
||||
self.__delivery_destination = delivery_destination
|
||||
|
||||
def register_delivery_callback(self, callback):
|
||||
self.__delivery_callback = callback
|
||||
|
||||
def register_failed_callback(self, callback):
|
||||
self.failed_callback = callback
|
||||
|
||||
def validate_stamp(self, target_cost, tickets=None):
|
||||
if tickets != None:
|
||||
for ticket in tickets:
|
||||
try:
|
||||
if self.stamp == RNS.Identity.truncated_hash(ticket+self.message_id):
|
||||
RNS.log(f"Stamp on {self} validated by inbound ticket", RNS.LOG_DEBUG) # TODO: Remove at some point
|
||||
self.stamp_value = LXMessage.COST_TICKET
|
||||
return True
|
||||
except Exception as e:
|
||||
RNS.log(f"Error while validating ticket: {e}", RNS.LOG_ERROR)
|
||||
RNS.trace_exception(e)
|
||||
|
||||
if self.stamp == None:
|
||||
return False
|
||||
else:
|
||||
workblock = LXStamper.stamp_workblock(self.message_id)
|
||||
if LXStamper.stamp_valid(self.stamp, target_cost, workblock):
|
||||
RNS.log(f"Stamp on {self} validated", RNS.LOG_DEBUG) # TODO: Remove at some point
|
||||
self.stamp_value = LXStamper.stamp_value(workblock, self.stamp)
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def get_stamp(self, timeout=None):
|
||||
# If an outbound ticket exists, use this for
|
||||
# generating a valid stamp.
|
||||
if self.outbound_ticket != None and type(self.outbound_ticket) == bytes and len(self.outbound_ticket) == LXMessage.TICKET_LENGTH:
|
||||
generated_stamp = RNS.Identity.truncated_hash(self.outbound_ticket+self.message_id)
|
||||
self.stamp_value = LXMessage.COST_TICKET
|
||||
RNS.log(f"Generated stamp with outbound ticket {RNS.hexrep(self.outbound_ticket)} for {self}", RNS.LOG_DEBUG) # TODO: Remove at some point
|
||||
return generated_stamp
|
||||
|
||||
# If no stamp cost is required, we can just
|
||||
# return immediately.
|
||||
elif self.stamp_cost == None:
|
||||
self.stamp_value = None
|
||||
return None
|
||||
|
||||
# If a stamp was already generated, return
|
||||
# it immediately.
|
||||
elif self.stamp != None:
|
||||
return self.stamp
|
||||
|
||||
# Otherwise, we will need to generate a
|
||||
# valid stamp according to the cost that
|
||||
# the receiver has specified.
|
||||
else:
|
||||
generated_stamp, value = LXStamper.generate_stamp(self.message_id, self.stamp_cost)
|
||||
if generated_stamp:
|
||||
self.stamp_value = value
|
||||
self.stamp_valid = True
|
||||
return generated_stamp
|
||||
|
||||
else:
|
||||
return None
|
||||
|
||||
def get_propagation_stamp(self, target_cost, timeout=None):
|
||||
# If a stamp was already generated, return
|
||||
# it immediately.
|
||||
if self.propagation_stamp != None:
|
||||
return self.propagation_stamp
|
||||
|
||||
# Otherwise, we will need to generate a
|
||||
# valid stamp according to the cost that
|
||||
# the propagation node has specified.
|
||||
else:
|
||||
self.propagation_target_cost = target_cost
|
||||
if self.propagation_target_cost == None:
|
||||
raise ValueError("Cannot generate propagation stamp without configured target propagation cost")
|
||||
|
||||
|
||||
if not self.transient_id: self.pack()
|
||||
generated_stamp, value = LXStamper.generate_stamp(self.transient_id, target_cost, expand_rounds=LXStamper.WORKBLOCK_EXPAND_ROUNDS_PN)
|
||||
if generated_stamp:
|
||||
self.propagation_stamp = generated_stamp
|
||||
self.propagation_stamp_value = value
|
||||
self.propagation_stamp_valid = True
|
||||
return generated_stamp
|
||||
|
||||
else:
|
||||
return None
|
||||
|
||||
def pack(self, payload_updated=False):
|
||||
if not self.packed:
|
||||
if self.timestamp == None: self.timestamp = time.time()
|
||||
|
||||
self.propagation_packed = None
|
||||
self.paper_packed = None
|
||||
|
||||
self.payload = [self.timestamp, self.title, self.content, self.fields]
|
||||
|
||||
hashed_part = b""
|
||||
hashed_part += self.__destination.hash
|
||||
hashed_part += self.__source.hash
|
||||
hashed_part += msgpack.packb(self.payload)
|
||||
self.hash = RNS.Identity.full_hash(hashed_part)
|
||||
self.message_id = self.hash
|
||||
|
||||
if not self.defer_stamp:
|
||||
self.stamp = self.get_stamp()
|
||||
if self.stamp != None: self.payload.append(self.stamp)
|
||||
|
||||
signed_part = b""
|
||||
signed_part += hashed_part
|
||||
signed_part += self.hash
|
||||
self.signature = self.__source.sign(signed_part)
|
||||
self.signature_validated = True
|
||||
|
||||
packed_payload = msgpack.packb(self.payload)
|
||||
self.packed = b""
|
||||
self.packed += self.__destination.hash
|
||||
self.packed += self.__source.hash
|
||||
self.packed += self.signature
|
||||
self.packed += packed_payload
|
||||
self.packed_size = len(self.packed)
|
||||
content_size = len(packed_payload)-LXMessage.TIMESTAMP_SIZE-LXMessage.STRUCT_OVERHEAD
|
||||
|
||||
# If no desired delivery method has been defined,
|
||||
# one will be chosen according to these rules:
|
||||
if self.desired_method == None:
|
||||
self.desired_method = LXMessage.DIRECT
|
||||
|
||||
# If opportunistic delivery was requested, check
|
||||
# that message will fit within packet size limits
|
||||
if self.desired_method == LXMessage.OPPORTUNISTIC:
|
||||
if self.__destination.type == RNS.Destination.SINGLE:
|
||||
if content_size > LXMessage.ENCRYPTED_PACKET_MAX_CONTENT:
|
||||
RNS.log(f"Opportunistic delivery was requested for {self}, but content of length {content_size} exceeds packet size limit. Falling back to link-based delivery.", RNS.LOG_DEBUG)
|
||||
self.desired_method = LXMessage.DIRECT
|
||||
|
||||
# Set delivery parameters according to delivery method
|
||||
if self.desired_method == LXMessage.OPPORTUNISTIC:
|
||||
if self.__destination.type == RNS.Destination.SINGLE:
|
||||
single_packet_content_limit = LXMessage.ENCRYPTED_PACKET_MAX_CONTENT
|
||||
elif self.__destination.type == RNS.Destination.PLAIN:
|
||||
single_packet_content_limit = LXMessage.PLAIN_PACKET_MAX_CONTENT
|
||||
|
||||
if content_size > single_packet_content_limit:
|
||||
raise TypeError(f"LXMessage desired opportunistic delivery method, but content of length {content_size} exceeds single-packet content limit of {single_packet_content_limit}.")
|
||||
else:
|
||||
self.method = LXMessage.OPPORTUNISTIC
|
||||
self.representation = LXMessage.PACKET
|
||||
self.__delivery_destination = self.__destination
|
||||
|
||||
elif self.desired_method == LXMessage.DIRECT:
|
||||
single_packet_content_limit = LXMessage.LINK_PACKET_MAX_CONTENT
|
||||
if content_size <= single_packet_content_limit:
|
||||
self.method = self.desired_method
|
||||
self.representation = LXMessage.PACKET
|
||||
else:
|
||||
self.method = self.desired_method
|
||||
self.representation = LXMessage.RESOURCE
|
||||
|
||||
elif self.desired_method == LXMessage.PROPAGATED:
|
||||
single_packet_content_limit = LXMessage.LINK_PACKET_MAX_CONTENT
|
||||
|
||||
if self.__pn_encrypted_data == None or payload_updated:
|
||||
self.__pn_encrypted_data = self.__destination.encrypt(self.packed[LXMessage.DESTINATION_LENGTH:])
|
||||
self.ratchet_id = self.__destination.latest_ratchet_id
|
||||
|
||||
lxmf_data = self.packed[:LXMessage.DESTINATION_LENGTH]+self.__pn_encrypted_data
|
||||
self.transient_id = RNS.Identity.full_hash(lxmf_data)
|
||||
if self.propagation_stamp != None: lxmf_data += self.propagation_stamp
|
||||
self.propagation_packed = msgpack.packb([time.time(), [lxmf_data]])
|
||||
|
||||
content_size = len(self.propagation_packed)
|
||||
if content_size <= single_packet_content_limit:
|
||||
self.method = self.desired_method
|
||||
self.representation = LXMessage.PACKET
|
||||
else:
|
||||
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.ratchet_id = self.__destination.latest_ratchet_id
|
||||
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")
|
||||
|
||||
def send(self):
|
||||
self.determine_transport_encryption()
|
||||
|
||||
if self.method == LXMessage.OPPORTUNISTIC:
|
||||
lxm_packet = self.__as_packet()
|
||||
lxm_packet.send().set_delivery_callback(self.__mark_delivered)
|
||||
self.progress = 0.50
|
||||
self.ratchet_id = lxm_packet.ratchet_id
|
||||
self.state = LXMessage.SENT
|
||||
|
||||
elif self.method == LXMessage.DIRECT:
|
||||
self.state = LXMessage.SENDING
|
||||
|
||||
if self.representation == LXMessage.PACKET:
|
||||
lxm_packet = self.__as_packet()
|
||||
receipt = lxm_packet.send()
|
||||
self.ratchet_id = self.__delivery_destination.link_id
|
||||
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.ratchet_id = self.__delivery_destination.link_id
|
||||
self.progress = 0.10
|
||||
|
||||
elif self.method == LXMessage.PROPAGATED:
|
||||
self.state = LXMessage.SENDING
|
||||
|
||||
if self.representation == LXMessage.PACKET:
|
||||
receipt = self.__as_packet().send()
|
||||
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):
|
||||
# TODO: These descriptions are old and outdated.
|
||||
# Update the transport encryption descriptions to
|
||||
# account for ratchets and other changes.
|
||||
if self.method == LXMessage.OPPORTUNISTIC:
|
||||
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
|
||||
elif self.method == LXMessage.DIRECT:
|
||||
self.transport_encrypted = True
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_EC
|
||||
elif self.method == LXMessage.PROPAGATED:
|
||||
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
|
||||
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
|
||||
|
||||
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:
|
||||
self.__delivery_callback(self)
|
||||
except Exception as e:
|
||||
RNS.log("An error occurred in the external delivery callback for "+str(self), RNS.LOG_ERROR)
|
||||
RNS.trace_exception(e)
|
||||
|
||||
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(self), RNS.LOG_ERROR)
|
||||
RNS.trace_exception(e)
|
||||
|
||||
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:
|
||||
self.__delivery_callback(self)
|
||||
except Exception as e:
|
||||
RNS.log("An error occurred in the external delivery callback for "+str(self), RNS.LOG_ERROR)
|
||||
RNS.trace_exception(e)
|
||||
|
||||
def __resource_concluded(self, resource):
|
||||
if resource.status == RNS.Resource.COMPLETE:
|
||||
self.__mark_delivered()
|
||||
else:
|
||||
if resource.status == RNS.Resource.REJECTED:
|
||||
self.state = LXMessage.REJECTED
|
||||
|
||||
elif self.state != LXMessage.CANCELLED:
|
||||
resource.link.teardown()
|
||||
self.state = LXMessage.OUTBOUND
|
||||
|
||||
def __propagation_resource_concluded(self, resource):
|
||||
if resource.status == RNS.Resource.COMPLETE:
|
||||
self.__mark_propagated()
|
||||
else:
|
||||
if self.state != LXMessage.CANCELLED:
|
||||
resource.link.teardown()
|
||||
self.state = LXMessage.OUTBOUND
|
||||
|
||||
def __link_packet_timed_out(self, packet_receipt):
|
||||
if self.state != LXMessage.CANCELLED:
|
||||
if packet_receipt:
|
||||
packet_receipt.destination.teardown()
|
||||
|
||||
self.state = LXMessage.OUTBOUND
|
||||
|
||||
def __update_transfer_progress(self, resource):
|
||||
self.progress = 0.10 + (resource.get_progress()*0.90)
|
||||
|
||||
def __as_packet(self):
|
||||
if not self.packed:
|
||||
self.pack()
|
||||
|
||||
if not self.__delivery_destination:
|
||||
raise ValueError("Can't synthesize packet for LXMF message before delivery destination is known")
|
||||
|
||||
if self.method == LXMessage.OPPORTUNISTIC:
|
||||
return RNS.Packet(self.__delivery_destination, self.packed[LXMessage.DESTINATION_LENGTH:])
|
||||
elif self.method == LXMessage.DIRECT:
|
||||
return RNS.Packet(self.__delivery_destination, self.packed)
|
||||
elif self.method == LXMessage.PROPAGATED:
|
||||
return RNS.Packet(self.__delivery_destination, self.propagation_packed)
|
||||
|
||||
def __as_resource(self):
|
||||
if not self.packed:
|
||||
self.pack()
|
||||
|
||||
if not self.__delivery_destination:
|
||||
raise ValueError("Can't synthesize resource for LXMF message before delivery destination is known")
|
||||
|
||||
if not self.__delivery_destination.type == RNS.Destination.LINK:
|
||||
raise TypeError("Tried to synthesize resource for LXMF message on a delivery destination that was not a link")
|
||||
|
||||
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")
|
||||
|
||||
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:
|
||||
return RNS.Resource(self.propagation_packed, self.__delivery_destination, callback = self.__propagation_resource_concluded, progress_callback = self.__update_transfer_progress)
|
||||
else:
|
||||
return None
|
||||
|
||||
def packed_container(self):
|
||||
if not self.packed:
|
||||
self.pack()
|
||||
|
||||
container = {
|
||||
"state": self.state,
|
||||
"lxmf_bytes": self.packed,
|
||||
"transport_encrypted": self.transport_encrypted,
|
||||
"transport_encryption": self.transport_encryption,
|
||||
"method": self.method
|
||||
}
|
||||
|
||||
return msgpack.packb(container)
|
||||
|
||||
|
||||
def write_to_directory(self, directory_path):
|
||||
file_name = RNS.hexrep(self.hash, delimit=False)
|
||||
file_path = directory_path+"/"+file_name
|
||||
|
||||
try:
|
||||
file = open(file_path, "wb")
|
||||
file.write(self.packed_container())
|
||||
file.close()
|
||||
|
||||
return file_path
|
||||
|
||||
except Exception as e:
|
||||
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, 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]
|
||||
packed_payload = lxmf_bytes[2*LXMessage.DESTINATION_LENGTH+LXMessage.SIGNATURE_LENGTH:]
|
||||
unpacked_payload = msgpack.unpackb(packed_payload)
|
||||
|
||||
# Extract stamp from payload if included
|
||||
if len(unpacked_payload) > 4:
|
||||
stamp = unpacked_payload[4]
|
||||
unpacked_payload = unpacked_payload[:4]
|
||||
packed_payload = msgpack.packb(unpacked_payload)
|
||||
else:
|
||||
stamp = None
|
||||
|
||||
hashed_part = b"" + destination_hash + source_hash + packed_payload
|
||||
message_hash = RNS.Identity.full_hash(hashed_part)
|
||||
signed_part = b"" + hashed_part + message_hash
|
||||
timestamp = unpacked_payload[0]
|
||||
title_bytes = unpacked_payload[1]
|
||||
content_bytes = unpacked_payload[2]
|
||||
fields = unpacked_payload[3]
|
||||
|
||||
destination_identity = RNS.Identity.recall(destination_hash)
|
||||
if destination_identity != None:
|
||||
destination = RNS.Destination(destination_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "delivery")
|
||||
else:
|
||||
destination = None
|
||||
|
||||
source_identity = RNS.Identity.recall(source_hash)
|
||||
if source_identity != None:
|
||||
source = RNS.Destination(source_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "delivery")
|
||||
else:
|
||||
source = None
|
||||
|
||||
message = LXMessage(
|
||||
destination = destination,
|
||||
source = source,
|
||||
content = "",
|
||||
title = "",
|
||||
fields = fields,
|
||||
destination_hash = destination_hash,
|
||||
source_hash = source_hash,
|
||||
desired_method = original_method)
|
||||
|
||||
message.hash = message_hash
|
||||
message.message_id = message.hash
|
||||
message.signature = signature
|
||||
message.stamp = stamp
|
||||
message.incoming = True
|
||||
message.timestamp = timestamp
|
||||
message.packed = lxmf_bytes
|
||||
message.packed_size = len(lxmf_bytes)
|
||||
message.set_title_from_bytes(title_bytes)
|
||||
message.set_content_from_bytes(content_bytes)
|
||||
|
||||
try:
|
||||
if source:
|
||||
if source.identity.validate(signature, signed_part):
|
||||
message.signature_validated = True
|
||||
else:
|
||||
message.signature_validated = False
|
||||
message.unverified_reason = LXMessage.SIGNATURE_INVALID
|
||||
else:
|
||||
signature_validated = False
|
||||
message.unverified_reason = LXMessage.SOURCE_UNKNOWN
|
||||
RNS.log("Unpacked LXMF message signature could not be validated, since source identity is unknown", RNS.LOG_DEBUG)
|
||||
except Exception as e:
|
||||
message.signature_validated = False
|
||||
RNS.log("Error while validating LXMF message signature. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
return message
|
||||
|
||||
@staticmethod
|
||||
def unpack_from_file(lxmf_file_handle):
|
||||
try:
|
||||
container = msgpack.unpackb(lxmf_file_handle.read())
|
||||
lxm = LXMessage.unpack_from_bytes(container["lxmf_bytes"])
|
||||
|
||||
if "state" in container:
|
||||
lxm.state = container["state"]
|
||||
if "transport_encrypted" in container:
|
||||
lxm.transport_encrypted = container["transport_encrypted"]
|
||||
if "transport_encryption" in container:
|
||||
lxm.transport_encryption = container["transport_encryption"]
|
||||
if "method" in container:
|
||||
lxm.method = container["method"]
|
||||
|
||||
return lxm
|
||||
except Exception as e:
|
||||
RNS.log("Could not unpack LXMessage from file. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
return None
|
||||
@@ -0,0 +1,395 @@
|
||||
import RNS
|
||||
import RNS.vendor.umsgpack as msgpack
|
||||
|
||||
import os
|
||||
import time
|
||||
import math
|
||||
import itertools
|
||||
import multiprocessing
|
||||
|
||||
WORKBLOCK_EXPAND_ROUNDS = 3000
|
||||
WORKBLOCK_EXPAND_ROUNDS_PN = 1000
|
||||
WORKBLOCK_EXPAND_ROUNDS_PEERING = 25
|
||||
STAMP_SIZE = RNS.Identity.HASHLENGTH//8
|
||||
PN_VALIDATION_POOL_MIN_SIZE = 256
|
||||
|
||||
active_jobs = {}
|
||||
|
||||
def stamp_workblock(material, expand_rounds=WORKBLOCK_EXPAND_ROUNDS):
|
||||
wb_st = time.time()
|
||||
workblock = b""
|
||||
for n in range(expand_rounds):
|
||||
workblock += RNS.Cryptography.hkdf(length=256,
|
||||
derive_from=material,
|
||||
salt=RNS.Identity.full_hash(material+msgpack.packb(n)),
|
||||
context=None)
|
||||
wb_time = time.time() - wb_st
|
||||
# RNS.log(f"Stamp workblock size {RNS.prettysize(len(workblock))}, generated in {round(wb_time*1000,2)}ms", RNS.LOG_DEBUG)
|
||||
|
||||
return workblock
|
||||
|
||||
def stamp_value(workblock, stamp):
|
||||
value = 0
|
||||
bits = 256
|
||||
material = RNS.Identity.full_hash(workblock+stamp)
|
||||
i = int.from_bytes(material, byteorder="big")
|
||||
while ((i & (1 << (bits - 1))) == 0):
|
||||
i = (i << 1)
|
||||
value += 1
|
||||
|
||||
return value
|
||||
|
||||
def stamp_valid(stamp, target_cost, workblock):
|
||||
target = 0b1 << 256-target_cost
|
||||
result = RNS.Identity.full_hash(workblock+stamp)
|
||||
if int.from_bytes(result, byteorder="big") > target: return False
|
||||
else: return True
|
||||
|
||||
def validate_peering_key(peering_id, peering_key, target_cost):
|
||||
workblock = stamp_workblock(peering_id, expand_rounds=WORKBLOCK_EXPAND_ROUNDS_PEERING)
|
||||
if not stamp_valid(peering_key, target_cost, workblock): return False
|
||||
else: return True
|
||||
|
||||
def validate_pn_stamp(transient_data, target_cost):
|
||||
from .LXMessage import LXMessage
|
||||
if len(transient_data) <= LXMessage.LXMF_OVERHEAD+STAMP_SIZE: return None, None, None, None
|
||||
else:
|
||||
lxm_data = transient_data[:-STAMP_SIZE]
|
||||
stamp = transient_data[-STAMP_SIZE:]
|
||||
transient_id = RNS.Identity.full_hash(lxm_data)
|
||||
workblock = stamp_workblock(transient_id, expand_rounds=WORKBLOCK_EXPAND_ROUNDS_PN)
|
||||
|
||||
if not stamp_valid(stamp, target_cost, workblock): return None, None, None, None
|
||||
else:
|
||||
value = stamp_value(workblock, stamp)
|
||||
return transient_id, lxm_data, value, stamp
|
||||
|
||||
def validate_pn_stamps_job_simple(transient_list, target_cost):
|
||||
validated_messages = []
|
||||
for transient_data in transient_list:
|
||||
transient_id, lxm_data, value, stamp_data = validate_pn_stamp(transient_data, target_cost)
|
||||
if transient_id: validated_messages.append([transient_id, lxm_data, value, stamp_data])
|
||||
|
||||
return validated_messages
|
||||
|
||||
def validate_pn_stamps_job_multip(transient_list, target_cost):
|
||||
cores = multiprocessing.cpu_count()
|
||||
pool_count = min(cores, math.ceil(len(transient_list) / PN_VALIDATION_POOL_MIN_SIZE))
|
||||
|
||||
RNS.log(f"Validating {len(transient_list)} stamps using {pool_count} processes...", RNS.LOG_VERBOSE)
|
||||
with multiprocessing.get_context("spawn").Pool(pool_count) as p:
|
||||
validated_entries = p.starmap(validate_pn_stamp, zip(transient_list, itertools.repeat(target_cost)))
|
||||
|
||||
RNS.log(f"Validation pool completed for {len(transient_list)} stamps", RNS.LOG_VERBOSE)
|
||||
|
||||
return [e for e in validated_entries if e[0] != None]
|
||||
|
||||
def validate_pn_stamps(transient_list, target_cost):
|
||||
non_mp_platform = RNS.vendor.platformutils.is_android()
|
||||
if len(transient_list) <= PN_VALIDATION_POOL_MIN_SIZE or non_mp_platform: return validate_pn_stamps_job_simple(transient_list, target_cost)
|
||||
else: return validate_pn_stamps_job_multip(transient_list, target_cost)
|
||||
|
||||
def generate_stamp(message_id, stamp_cost, expand_rounds=WORKBLOCK_EXPAND_ROUNDS):
|
||||
RNS.log(f"Generating stamp with cost {stamp_cost} for {RNS.prettyhexrep(message_id)}...", RNS.LOG_DEBUG)
|
||||
workblock = stamp_workblock(message_id, expand_rounds=expand_rounds)
|
||||
|
||||
start_time = time.time()
|
||||
stamp = None
|
||||
rounds = 0
|
||||
value = 0
|
||||
|
||||
if RNS.vendor.platformutils.is_windows() or RNS.vendor.platformutils.is_darwin(): stamp, rounds = job_simple(stamp_cost, workblock, message_id)
|
||||
elif RNS.vendor.platformutils.is_android(): stamp, rounds = job_android(stamp_cost, workblock, message_id)
|
||||
else: stamp, rounds = job_linux(stamp_cost, workblock, message_id)
|
||||
|
||||
duration = time.time() - start_time
|
||||
speed = rounds/duration
|
||||
if stamp != None: value = stamp_value(workblock, stamp)
|
||||
|
||||
RNS.log(f"Stamp with value {value} generated in {RNS.prettytime(duration)}, {rounds} rounds, {int(speed)} rounds per second", RNS.LOG_DEBUG)
|
||||
|
||||
return stamp, value
|
||||
|
||||
def cancel_work(message_id):
|
||||
if RNS.vendor.platformutils.is_windows() or RNS.vendor.platformutils.is_darwin():
|
||||
try:
|
||||
if message_id in active_jobs:
|
||||
active_jobs[message_id] = True
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Error while terminating stamp generation workers: {e}", RNS.LOG_ERROR)
|
||||
RNS.trace_exception(e)
|
||||
|
||||
elif RNS.vendor.platformutils.is_android():
|
||||
try:
|
||||
if message_id in active_jobs:
|
||||
active_jobs[message_id] = True
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Error while terminating stamp generation workers: {e}", RNS.LOG_ERROR)
|
||||
RNS.trace_exception(e)
|
||||
|
||||
else:
|
||||
try:
|
||||
if message_id in active_jobs:
|
||||
stop_event = active_jobs[message_id][0]
|
||||
result_queue = active_jobs[message_id][1]
|
||||
stop_event.set()
|
||||
result_queue.put(None)
|
||||
active_jobs.pop(message_id)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Error while terminating stamp generation workers: {e}", RNS.LOG_ERROR)
|
||||
RNS.trace_exception(e)
|
||||
|
||||
def job_simple(stamp_cost, workblock, message_id):
|
||||
# A simple, single-process stamp generator.
|
||||
# should work on any platform, and is used
|
||||
# as a fall-back, in case of limited multi-
|
||||
# processing and/or acceleration support.
|
||||
|
||||
platform = RNS.vendor.platformutils.get_platform()
|
||||
RNS.log(f"Running stamp generation on {platform}, work limited to single CPU core. This will be slower than ideal.", RNS.LOG_WARNING)
|
||||
|
||||
rounds = 0
|
||||
pstamp = os.urandom(256//8)
|
||||
st = time.time()
|
||||
|
||||
active_jobs[message_id] = False;
|
||||
|
||||
def sv(s, c, w):
|
||||
target = 0b1<<256-c; m = w+s
|
||||
result = RNS.Identity.full_hash(m)
|
||||
if int.from_bytes(result, byteorder="big") > target: return False
|
||||
else: return True
|
||||
|
||||
while not sv(pstamp, stamp_cost, workblock) and not active_jobs[message_id]:
|
||||
pstamp = os.urandom(256//8); rounds += 1
|
||||
if rounds % 2500 == 0:
|
||||
speed = rounds / (time.time()-st)
|
||||
RNS.log(f"Stamp generation running. {rounds} rounds completed so far, {int(speed)} rounds per second", RNS.LOG_DEBUG)
|
||||
|
||||
if active_jobs[message_id] == True:
|
||||
pstamp = None
|
||||
|
||||
active_jobs.pop(message_id)
|
||||
|
||||
return pstamp, rounds
|
||||
|
||||
def job_linux(stamp_cost, workblock, message_id):
|
||||
allow_kill = True
|
||||
stamp = None
|
||||
total_rounds = 0
|
||||
cores = multiprocessing.cpu_count()
|
||||
jobs = cores if cores <= 12 else int(cores/2)
|
||||
stop_event = multiprocessing.Event()
|
||||
result_queue = multiprocessing.Queue(1)
|
||||
rounds_queue = multiprocessing.Queue()
|
||||
|
||||
def job(stop_event, pn, sc, wb):
|
||||
terminated = False
|
||||
rounds = 0
|
||||
pstamp = os.urandom(256//8)
|
||||
|
||||
def sv(s, c, w):
|
||||
target = 0b1<<256-c; m = w+s
|
||||
result = RNS.Identity.full_hash(m)
|
||||
if int.from_bytes(result, byteorder="big") > target:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
while not stop_event.is_set() and not sv(pstamp, sc, wb):
|
||||
pstamp = os.urandom(256//8); rounds += 1
|
||||
|
||||
if not stop_event.is_set():
|
||||
stop_event.set()
|
||||
result_queue.put(pstamp)
|
||||
rounds_queue.put(rounds)
|
||||
|
||||
job_procs = []
|
||||
RNS.log(f"Starting {jobs} stamp generation workers", RNS.LOG_DEBUG)
|
||||
for jpn in range(jobs):
|
||||
process = multiprocessing.get_context("fork").Process(target=job, kwargs={"stop_event": stop_event, "pn": jpn, "sc": stamp_cost, "wb": workblock}, daemon=True)
|
||||
job_procs.append(process)
|
||||
process.start()
|
||||
|
||||
active_jobs[message_id] = [stop_event, result_queue]
|
||||
|
||||
stamp = result_queue.get()
|
||||
|
||||
# Collect any potential spurious
|
||||
# results from worker queue.
|
||||
try:
|
||||
while True: result_queue.get_nowait()
|
||||
except: pass
|
||||
|
||||
for j in range(jobs):
|
||||
nrounds = 0
|
||||
try:
|
||||
nrounds = rounds_queue.get(timeout=2)
|
||||
except Exception as e:
|
||||
RNS.log(f"Failed to get round stats part {j}: {e}", RNS.LOG_ERROR)
|
||||
total_rounds += nrounds
|
||||
|
||||
all_exited = False
|
||||
exit_timeout = time.time() + 5
|
||||
while time.time() < exit_timeout:
|
||||
if not any(p.is_alive() for p in job_procs):
|
||||
all_exited = True
|
||||
break
|
||||
time.sleep(0.1)
|
||||
|
||||
if not all_exited:
|
||||
RNS.log("Stamp generation IPC timeout, possible worker deadlock. Terminating remaining processes.", RNS.LOG_ERROR)
|
||||
if allow_kill:
|
||||
for j in range(jobs):
|
||||
process = job_procs[j]
|
||||
process.kill()
|
||||
else:
|
||||
return None
|
||||
|
||||
else:
|
||||
for j in range(jobs):
|
||||
process = job_procs[j]
|
||||
process.join()
|
||||
# RNS.log(f"Joined {j} / {process}", RNS.LOG_DEBUG) # TODO: Remove
|
||||
|
||||
return stamp, total_rounds
|
||||
|
||||
def job_android(stamp_cost, workblock, message_id):
|
||||
# Semaphore support is flaky to non-existent on
|
||||
# Android, so we need to manually dispatch and
|
||||
# manage workloads here, while periodically
|
||||
# checking in on the progress.
|
||||
|
||||
stamp = None
|
||||
start_time = time.time()
|
||||
total_rounds = 0
|
||||
rounds_per_worker = 1000
|
||||
|
||||
use_nacl = False
|
||||
try:
|
||||
import nacl.encoding
|
||||
import nacl.hash
|
||||
use_nacl = True
|
||||
except:
|
||||
pass
|
||||
|
||||
if use_nacl:
|
||||
def full_hash(m):
|
||||
return nacl.hash.sha256(m, encoder=nacl.encoding.RawEncoder)
|
||||
else:
|
||||
def full_hash(m):
|
||||
return RNS.Identity.full_hash(m)
|
||||
|
||||
def sv(s, c, w):
|
||||
target = 0b1<<256-c
|
||||
m = w+s
|
||||
result = full_hash(m)
|
||||
if int.from_bytes(result, byteorder="big") > target:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
wm = multiprocessing.Manager()
|
||||
jobs = multiprocessing.cpu_count()
|
||||
|
||||
def job(procnum=None, results_dict=None, wb=None, sc=None, jr=None):
|
||||
# RNS.log(f"Worker {procnum} starting for {jr} rounds...") # TODO: Remove
|
||||
try:
|
||||
rounds = 0
|
||||
found_stamp = None
|
||||
|
||||
while True:
|
||||
pstamp = os.urandom(256//8)
|
||||
rounds += 1
|
||||
if sv(pstamp, sc, wb):
|
||||
found_stamp = pstamp
|
||||
break
|
||||
|
||||
if rounds >= jr:
|
||||
# RNS.log(f"Worker {procnum} found no result in {rounds} rounds") # TODO: Remove
|
||||
break
|
||||
|
||||
results_dict[procnum] = [found_stamp, rounds]
|
||||
except Exception as e:
|
||||
RNS.log(f"Stamp generation worker error: {e}", RNS.LOG_ERROR)
|
||||
RNS.trace_exception(e)
|
||||
|
||||
active_jobs[message_id] = False;
|
||||
|
||||
RNS.log(f"Dispatching {jobs} workers for stamp generation...", RNS.LOG_DEBUG) # TODO: Remove
|
||||
|
||||
results_dict = wm.dict()
|
||||
while stamp == None and active_jobs[message_id] == False:
|
||||
job_procs = []
|
||||
try:
|
||||
for pnum in range(jobs):
|
||||
pargs = {"procnum":pnum, "results_dict": results_dict, "wb": workblock, "sc":stamp_cost, "jr":rounds_per_worker}
|
||||
process = multiprocessing.Process(target=job, kwargs=pargs)
|
||||
job_procs.append(process)
|
||||
process.start()
|
||||
|
||||
for process in job_procs:
|
||||
process.join()
|
||||
|
||||
for j in results_dict:
|
||||
r = results_dict[j]
|
||||
total_rounds += r[1]
|
||||
if r[0] != None:
|
||||
stamp = r[0]
|
||||
|
||||
if stamp == None:
|
||||
elapsed = time.time() - start_time
|
||||
speed = total_rounds/elapsed
|
||||
RNS.log(f"Stamp generation running. {total_rounds} rounds completed so far, {int(speed)} rounds per second", RNS.LOG_DEBUG)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Stamp generation job error: {e}")
|
||||
RNS.trace_exception(e)
|
||||
|
||||
active_jobs.pop(message_id)
|
||||
|
||||
return stamp, total_rounds
|
||||
|
||||
# def stamp_value_linear(workblock, stamp):
|
||||
# value = 0
|
||||
# bits = 256
|
||||
# material = RNS.Identity.full_hash(workblock+stamp)
|
||||
# s = int.from_bytes(material, byteorder="big")
|
||||
# return s.bit_count()
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
if len(sys.argv) < 2:
|
||||
RNS.log("No cost argument provided", RNS.LOG_ERROR)
|
||||
exit(1)
|
||||
else:
|
||||
try:
|
||||
cost = int(sys.argv[1])
|
||||
except Exception as e:
|
||||
RNS.log(f"Invalid cost argument provided: {e}", RNS.LOG_ERROR)
|
||||
exit(1)
|
||||
|
||||
RNS.loglevel = RNS.LOG_DEBUG
|
||||
RNS.log("Testing LXMF stamp generation", RNS.LOG_DEBUG)
|
||||
message_id = os.urandom(32)
|
||||
generate_stamp(message_id, cost)
|
||||
|
||||
RNS.log("", RNS.LOG_DEBUG)
|
||||
RNS.log("Testing propagation stamp generation", RNS.LOG_DEBUG)
|
||||
message_id = os.urandom(32)
|
||||
generate_stamp(message_id, cost, expand_rounds=WORKBLOCK_EXPAND_ROUNDS_PN)
|
||||
|
||||
RNS.log("", RNS.LOG_DEBUG)
|
||||
RNS.log("Testing peering key generation", RNS.LOG_DEBUG)
|
||||
message_id = os.urandom(32)
|
||||
generate_stamp(message_id, cost, expand_rounds=WORKBLOCK_EXPAND_ROUNDS_PEERING)
|
||||
|
||||
transient_list = []
|
||||
st = time.time(); count = 10000
|
||||
for i in range(count): transient_list.append(os.urandom(256))
|
||||
validate_pn_stamps(transient_list, 5)
|
||||
dt = time.time()-st; mps = count/dt
|
||||
RNS.log(f"Validated {count} PN stamps in {RNS.prettytime(dt)}, {round(mps,1)} m/s", RNS.LOG_DEBUG)
|
||||
File diff suppressed because it is too large.
Load diff
+5
-2
@@ -1,7 +1,10 @@
|
||||
import os
|
||||
import glob
|
||||
from .LXMF import LXMessage
|
||||
from .LXMF import LXMRouter
|
||||
from .LXMessage import LXMessage
|
||||
from .LXMRouter import LXMRouter
|
||||
from .LXMF import *
|
||||
|
||||
from ._version import __version__
|
||||
|
||||
modules = glob.glob(os.path.dirname(__file__)+"/*.py")
|
||||
__all__ = [ os.path.basename(f)[:-3] for f in modules if not f.endswith('__init__.py')]
|
||||
@@ -0,0 +1 @@
|
||||
__version__ = "0.9.4"
|
||||
@@ -0,0 +1,33 @@
|
||||
This repository is a public mirror. All potential future development is happening elsewhere.
|
||||
|
||||
I am stepping back from all public-facing interaction with this project. Reticulum has always been primarily my work, and continuing in the current public, internet-facing model is no longer sustainable.
|
||||
|
||||
The software remains available for use as-is. Occasional updates may appear at unpredictable intervals, but there will be no support, no responses to issues, no discussions, and no community management in this or any other public venue. If it doesn't work for you, it doesn't work. That is the entire extent of available troubleshooting assistance I can offer you.
|
||||
|
||||
If you've followed this project for a while, you already know what this means. You know who designed, wrote and tested this, and you know how many years of my life it took. You'll also know about both my particular challenges and strengths, and how I believe anything worth building needs to be built and maintained with our own hands.
|
||||
|
||||
Seven months ago, I said I needed to step back, that I was exhausted, and that I needed to recover. I believed a public resolve would be enough to effectuate that, but while striving to get just a few more useful features and protocols out, the unproductive requests and demands also ramped up, and I got pulled back into the same patterns and draining interactions that I'd explicitly said I couldn't sustain anymore.
|
||||
|
||||
So here's what you might have already guessed: I'm done playing the game by rules I can't win at.
|
||||
|
||||
Everything you need is right here, and by any sensible measure, it's done. Anyone who wants to invest the time, skill and persistence can build on it, or completely re-imagine it with different priorities. That was always the point.
|
||||
|
||||
The people who actually contributed - you know who you are, and you know I mean it when I say: Thank you. All of you who've used this to build something real - that was the goal, and you did it without needing me to hold your hand.
|
||||
|
||||
The rest of you: You have what you need. Use it or don't. I am not going to be the person who explains it to you anymore.
|
||||
|
||||
This is not a temporary break. It's not "see you after some rest", but a recognition that the current model is fundamentally incompatible with my life, my health, and my reality.
|
||||
|
||||
If you want to support continued work, you can do so at the donation links listed in this repository. But please understand, that this is not purchasing support or guaranteeing updates. It is support for work that happens on my timeline, according to my capacity, which at the moment is not what it was.
|
||||
|
||||
If you want Reticulum to continue evolving, you have the power to make that happen. The protocol is public domain. The code is open source. Everything you need is right here. I've provided the tools, but building what comes next is not my responsibility anymore. It's yours.
|
||||
|
||||
To the small group of people who has actually been here, and understood what this work was and what it cost - you already know where to find me if it actually matters.
|
||||
|
||||
To everyone else: This is where we part ways. No hard feelings. It's just time.
|
||||
|
||||
---
|
||||
|
||||
असतो मा सद्गमय
|
||||
तमसो मा ज्योतिर्गमय
|
||||
मृत्योर्मा अमृतं गमय
|
||||
@@ -8,13 +8,20 @@ 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
|
||||
python3 setup.py bdist_wheel
|
||||
|
||||
build_sdist:
|
||||
python3 setup.py sdist
|
||||
|
||||
build_spkg: remove_symlinks build_sdist create_symlinks
|
||||
|
||||
release: remove_symlinks build_wheel create_symlinks
|
||||
|
||||
|
||||
@@ -1,13 +1,31 @@
|
||||
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.
|
||||
*This repository is [a public mirror](./MIRROR.md). All development is happening elsewhere.*
|
||||
|
||||
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)
|
||||
- [MeshChat](https://github.com/liamcottle/reticulum-meshchat)
|
||||
- [Nomad Network](https://unsigned.io/nomadnet)
|
||||
|
||||
Community-provided tools and utilities for LXMF include:
|
||||
|
||||
- [LXMFy](https://lxmfy.quad4.io/)
|
||||
- [LXMF-Bot](https://github.com/randogoth/lxmf-bot)
|
||||
- [LXMF Messageboard](https://github.com/chengtripp/lxmf_messageboard)
|
||||
- [LXMEvent](https://github.com/faragher/LXMEvent)
|
||||
- [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 +36,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 +57,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 +94,128 @@ 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.
|
||||
|
||||
## Caveat Emptor
|
||||
## Code Examples
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
## 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
|
||||
```
|
||||
|
||||
## Daemon Included
|
||||
|
||||
The `lxmf` package comes with the `lxmd` program, a fully functional (but lightweight) LXMF message router and propagation node daemon. After installing the `lxmf` package, you can run `lxmd --help` to learn more about the command-line options:
|
||||
|
||||
```text
|
||||
$ lxmd --help
|
||||
|
||||
usage: lxmd [-h] [--config CONFIG] [--rnsconfig RNSCONFIG] [-p] [-i PATH] [-v] [-q] [-s] [--exampleconfig] [--version]
|
||||
|
||||
Lightweight Extensible Messaging Daemon
|
||||
|
||||
options:
|
||||
-h, --help show this help message and exit
|
||||
--config CONFIG path to alternative lxmd config directory
|
||||
--rnsconfig RNSCONFIG
|
||||
path to alternative Reticulum config directory
|
||||
-p, --propagation-node
|
||||
run an LXMF Propagation Node
|
||||
-i PATH, --on-inbound PATH
|
||||
executable to run when a message is received
|
||||
-v, --verbose
|
||||
-q, --quiet
|
||||
-s, --service lxmd is running as a service and should log to file
|
||||
--exampleconfig print verbose configuration example to stdout and exit
|
||||
--version show program's version number and exit
|
||||
```
|
||||
|
||||
Or run `lxmd --exampleconfig` to generate a commented example configuration documenting all the available configuration directives.
|
||||
|
||||
## Support LXMF Development
|
||||
You can help support the continued development of open, free and private communications systems by donating via one of the following channels:
|
||||
|
||||
- Monero:
|
||||
```
|
||||
84FpY1QbxHcgdseePYNmhTHcrgMX4nFfBYtz2GKYToqHVVhJp8Eaw1Z1EedRnKD19b3B8NiLCGVxzKV17UMmmeEsCrPyA5w
|
||||
```
|
||||
- Bitcoin
|
||||
```
|
||||
bc1pgqgu8h8xvj4jtafslq396v7ju7hkgymyrzyqft4llfslz5vp99psqfk3a6
|
||||
```
|
||||
- Ethereum
|
||||
```
|
||||
0x91C421DdfB8a30a49A71d63447ddb54cEBe3465E
|
||||
```
|
||||
- Liberapay: https://liberapay.com/Reticulum/
|
||||
|
||||
- Ko-Fi: https://ko-fi.com/markqvist
|
||||
|
||||
|
||||
## 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.
|
||||
|
||||
## Development Roadmap
|
||||
|
||||
LXMF is actively being developed, and the following improvements and features are currently planned for implementation:
|
||||
|
||||
- ~~Update examples in readme to actually work~~
|
||||
- ~~Sync affinity based on link speeds and distances, for more intelligently choosing peer sync order~~
|
||||
- Sneakernet and physical transport functionality
|
||||
- Content Destinations, and easy to use API for group messaging and discussion threads
|
||||
- Write and release full API and protocol documentation
|
||||
- Documenting and possibly expanding LXMF limits and priorities
|
||||
@@ -0,0 +1,72 @@
|
||||
import RNS
|
||||
import LXMF
|
||||
import time
|
||||
|
||||
required_stamp_cost = 8
|
||||
enforce_stamps = False
|
||||
|
||||
def delivery_callback(message):
|
||||
global my_lxmf_destination, router
|
||||
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"
|
||||
|
||||
if message.stamp_valid:
|
||||
stamp_string = "Validated"
|
||||
else:
|
||||
stamp_string = "Invalid"
|
||||
|
||||
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 : "+str(message.title_as_string()))
|
||||
RNS.log("\t| Content : "+str(message.content_as_string()))
|
||||
RNS.log("\t| Fields : "+str(message.fields))
|
||||
if message.ratchet_id:
|
||||
RNS.log("\t| Ratchet : "+str(RNS.Identity._get_ratchet_id(message.ratchet_id)))
|
||||
RNS.log("\t| Message signature : "+signature_string)
|
||||
RNS.log("\t| Stamp : "+stamp_string)
|
||||
RNS.log("\t+---------------------------------------------------------------")
|
||||
|
||||
# Optionally, send a reply
|
||||
# source = my_lxmf_destination
|
||||
# dest = message.source
|
||||
# lxm = LXMF.LXMessage(dest, source, "Reply", None, desired_method=LXMF.LXMessage.DIRECT, include_ticket=True)
|
||||
# router.handle_outbound(lxm)
|
||||
|
||||
r = RNS.Reticulum()
|
||||
|
||||
router = LXMF.LXMRouter(storagepath="./tmp1", enforce_stamps=enforce_stamps)
|
||||
identity = RNS.Identity()
|
||||
my_lxmf_destination = router.register_delivery_identity(identity, display_name="Anonymous Peer", stamp_cost=required_stamp_cost)
|
||||
router.register_delivery_callback(delivery_callback)
|
||||
|
||||
RNS.log("Ready to receive on: "+RNS.prettyhexrep(my_lxmf_destination.hash))
|
||||
|
||||
|
||||
# You can set a propagation node address to test receiving
|
||||
# messages from a propagation node, instead of directly
|
||||
|
||||
# router.set_outbound_propagation_node(bytes.fromhex("e75d9b6a69f82b48b6077cf2242d7499"))
|
||||
|
||||
|
||||
# This loop allows you to execute various actions for testing
|
||||
# and experimenting with the example scripts.
|
||||
while True:
|
||||
input()
|
||||
RNS.log("Announcing lxmf.delivery destination...")
|
||||
router.announce(my_lxmf_destination.hash)
|
||||
|
||||
# input()
|
||||
# RNS.log("Requesting messages from propagation node...")
|
||||
# router.request_messages_from_propagation_node(identity)
|
||||
@@ -0,0 +1,69 @@
|
||||
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", "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)], stamp_cost=8)
|
||||
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")
|
||||
|
||||
# This loop allows you to execute various actions for testing
|
||||
# and experimenting with the example scripts.
|
||||
while True:
|
||||
|
||||
# Create a message that will be sent directly to the
|
||||
# destination over a Reticulum link:
|
||||
|
||||
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, include_ticket=True)
|
||||
|
||||
# Or, create an oppertunistic, single-packet message
|
||||
# for sending without first establishing a link:
|
||||
|
||||
# lxm = LXMF.LXMessage(dest, source, "This is a test",
|
||||
# random_titles[random.randint(0,len(random_titles)-1)],
|
||||
# desired_method=LXMF.LXMessage.OPPORTUNISTIC, include_ticket=True)
|
||||
|
||||
|
||||
# Or, try sending the message via a propagation node:
|
||||
|
||||
# router.set_outbound_propagation_node(bytes.fromhex("e75d9b6a69f82b48b6077cf2242d7499"))
|
||||
# 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.PROPAGATED)
|
||||
|
||||
# Finally dispatch the message to the LXMF message
|
||||
# router, which will handle the delivery according
|
||||
# to the specified message parameters and options:
|
||||
|
||||
router.handle_outbound(lxm)
|
||||
|
||||
# Wait for user input before starting over
|
||||
input()
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.6 KiB |
@@ -0,0 +1,2 @@
|
||||
qrcode>=7.4.2
|
||||
rns>=1.0.0
|
||||
@@ -3,21 +3,29 @@ import setuptools
|
||||
with open("README.md", "r") as fh:
|
||||
long_description = fh.read()
|
||||
|
||||
exec(open("LXMF/_version.py", "r").read())
|
||||
|
||||
setuptools.setup(
|
||||
name="lxmf",
|
||||
version="0.1.3",
|
||||
version=__version__,
|
||||
author="Mark Qvist",
|
||||
author_email="mark@unsigned.io",
|
||||
description="Lightweight Extensible Message Format for Reticulum",
|
||||
long_description=long_description,
|
||||
long_description_content_type="text/markdown",
|
||||
url="https://github.com/markqvist/lxmf",
|
||||
packages=setuptools.find_packages(),
|
||||
packages=["LXMF", "LXMF.Utilities"],
|
||||
license="Reticulum License",
|
||||
license_files = ("LICENSE"),
|
||||
classifiers=[
|
||||
"Programming Language :: Python :: 3",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Operating System :: OS Independent",
|
||||
],
|
||||
install_requires=['rns>=0.3.0'],
|
||||
python_requires='>=3.6',
|
||||
entry_points= {
|
||||
'console_scripts': [
|
||||
'lxmd=LXMF.Utilities.lxmd:main',
|
||||
]
|
||||
},
|
||||
install_requires=["rns>=1.1.1"],
|
||||
python_requires=">=3.7",
|
||||
)
|
||||
Reference in new issue
Block a user