mirror of
https://github.com/ratspeak/rsLXMF
synced 2026-11-27 13:52:18 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
00f439df7e | ||
|
|
5a6a0cbbdb | ||
|
|
18b99b8932 |
No files matched your search
@@ -10,7 +10,7 @@ permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
RSLXMF_RSRETICULUM_COMMIT: bf7d16fc36045b6d33ca0d4c85d2b35b1b20751f
|
||||
RSLXMF_RSRETICULUM_COMMIT: 14241a383910e6ee7665303eff1e7c8d98957cc0
|
||||
|
||||
jobs:
|
||||
api-compat:
|
||||
|
||||
@@ -25,7 +25,7 @@ env:
|
||||
PACKAGE_ROOT: rsLXMF
|
||||
LXMF_BINS: lxmd-rs
|
||||
RSLXMF_RSRETICULUM_VERSION: 1.4.0
|
||||
RSLXMF_RSRETICULUM_COMMIT: bf7d16fc36045b6d33ca0d4c85d2b35b1b20751f
|
||||
RSLXMF_RSRETICULUM_COMMIT: 14241a383910e6ee7665303eff1e7c8d98957cc0
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
|
||||
+3
-4
@@ -2,6 +2,8 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
## 1.4.0 - 2026-11-08
|
||||
|
||||
- Start a propagation node without rereading and flushing every stored message, so restarts with large stores no longer delay announces and hosting. Each message is still verified when it is served.
|
||||
- Space `lxmd` announces like Python lxmd: the propagation and control announces follow their trigger by 20 seconds instead of going out together with the delivery announce, so Python transport nodes no longer hold the control announce after a restart. A node set not to announce at start now waits a full interval before its first periodic announce.
|
||||
- Fall back from opportunistic to direct delivery whenever a message's content does not fit one encrypted packet, over 287 bytes, as in Python LXMF 1.2.0.
|
||||
@@ -9,15 +11,12 @@
|
||||
- Store a signed message so its delivery can resume after a restart under the same id. A message that is already queued is no longer queued twice.
|
||||
- Generate deferred stamps in the order messages were sent, as Python LXMF does, so a reply no longer overtakes the message it answers.
|
||||
- Keep a destination's identity in Reticulum once a message to it is delivered, as Python LXMF does. `lxmd` asks the shared instance when attached to one.
|
||||
|
||||
## 1.4.0 - 2026-10-12
|
||||
|
||||
- Preserve each signed message exactly as received, including binary text and custom fields, and reject ambiguous field definitions.
|
||||
- Remove downloaded messages from a propagation node only after the receiving application confirms durable acceptance. Failed items remain available for retry.
|
||||
- Keep propagation messages encrypted in storage, quarantine untrusted legacy entries, and require storage recovery before a node becomes available.
|
||||
- Keep stamps, encryption, and ticket state consistent across retries and restarts, and reject undecipherable messages instead of treating them as plaintext.
|
||||
- Bound background delivery work, keep node downloads responsive during storage operations, and defer excess downloads without dropping valid messages during busy periods.
|
||||
- Updated message construction and delivery APIs and require rsReticulum `~1.4.0`. This source-breaking release uses the `~1.4.0` compatibility line.
|
||||
- Updated message construction and delivery APIs and require rsReticulum `~1.4.0`. Use the `~1.4.0` compatibility line for these source-breaking APIs.
|
||||
|
||||
## 1.3.0 - 2026-10-12
|
||||
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ members = [
|
||||
[workspace.package]
|
||||
version = "1.4.0"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-or-later"
|
||||
license-file = "LICENSE"
|
||||
rust-version = "1.89"
|
||||
|
||||
[workspace.dependencies]
|
||||
|
||||
@@ -1,661 +1,34 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
Reticulum License
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
Derived from the reference implementation at
|
||||
https://github.com/markqvist/LXMF
|
||||
|
||||
Preamble
|
||||
Copyright (c) 2020-2026 Mark Qvist, unless otherwise noted
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
Additions and modifications Copyright (c) 2026 Ratspeak LLC
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
- 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.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
- 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.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
- The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -4,10 +4,10 @@
|
||||
|
||||
**Rust LXMF messaging and propagation for Reticulum.**
|
||||
|
||||
[](LICENSE)
|
||||
[](LICENSE)
|
||||
[](https://www.rust-lang.org)
|
||||
[](https://github.com/markqvist/LXMF)
|
||||
[](https://github.com/markqvist/LXMF)
|
||||
[](https://github.com/markqvist/LXMF)
|
||||
[](#feature-status)
|
||||
|
||||
[LXMF Reference](https://github.com/markqvist/LXMF) |
|
||||
@@ -19,7 +19,11 @@
|
||||
|
||||
---
|
||||
|
||||
rsLXMF is a Rust implementation of LXMF, the Reticulum messaging layer. This is not a fork of LXMF, this is LXMF written in a different language focused on staying interoperable. This is not a source of truth implementation, do not use it as such.
|
||||
rsLXMF is a Rust port of [LXMF](https://github.com/markqvist/LXMF), the
|
||||
Reticulum messaging layer, from the reference implementation by Mark Qvist. It
|
||||
was written from the reference source, not from a specification, and tracks the
|
||||
reference's wire behavior release by release. The Python reference
|
||||
implementation remains the source of truth. See [License](#license).
|
||||
|
||||
Commands are intentionally namespaced for Rust with the Rust-specific `lxmd-rs` command, so rsLXMF can live beside other
|
||||
LXMF daemons on `PATH` without worry.
|
||||
@@ -38,6 +42,8 @@ LXMF daemons on `PATH` without worry.
|
||||
|
||||
## Build It
|
||||
|
||||
This guide describes the 1.4.0 release, [v1.4.0](https://github.com/ratspeak/rsLXMF/releases/tag/v1.4.0), built with rsReticulum [v1.4.0](https://github.com/ratspeak/rsReticulum/releases/tag/v1.4.0); it is the source line Ratspeak builds from. For the 1.3.0 daemon, use [the v1.3.0 README](https://github.com/ratspeak/rsLXMF/blob/v1.3.0/README.md) and that build's `--help`. The 1.4 message and durable relay APIs require a coordinated source migration.
|
||||
|
||||
The current development layout for rsLXMF requires
|
||||
rsReticulum as a sibling directory/repo next to it, such as:
|
||||
|
||||
@@ -52,9 +58,13 @@ mkdir ratspeak-src
|
||||
cd ratspeak-src
|
||||
git clone https://github.com/ratspeak/rsReticulum
|
||||
git clone https://github.com/ratspeak/rsLXMF
|
||||
git -C rsReticulum checkout --detach v1.4.0
|
||||
git -C rsLXMF checkout --detach v1.4.0
|
||||
cd rsLXMF
|
||||
```
|
||||
|
||||
Run the build commands below from that `rsLXMF` directory. The host crates require Rust 1.89 or newer.
|
||||
|
||||
### macOS
|
||||
|
||||
Install Rust with `rustup`, then install Apple's build tools:
|
||||
@@ -66,7 +76,6 @@ xcode-select --install
|
||||
Build from the sibling checkout:
|
||||
|
||||
```bash
|
||||
cd rsLXMF
|
||||
cargo build --release --locked
|
||||
```
|
||||
|
||||
@@ -78,25 +87,24 @@ Debian, Ubuntu, and Raspberry Pi OS:
|
||||
|
||||
```bash
|
||||
sudo apt update
|
||||
sudo apt install -y build-essential pkg-config libudev-dev
|
||||
sudo apt install -y build-essential pkg-config
|
||||
```
|
||||
|
||||
Fedora:
|
||||
|
||||
```bash
|
||||
sudo dnf install gcc make pkgconf-pkg-config systemd-devel
|
||||
sudo dnf install gcc make pkgconf-pkg-config
|
||||
```
|
||||
|
||||
Arch:
|
||||
|
||||
```bash
|
||||
sudo pacman -S --needed base-devel pkgconf systemd
|
||||
sudo pacman -S --needed base-devel pkgconf
|
||||
```
|
||||
|
||||
#### Build the daemon:
|
||||
|
||||
```bash
|
||||
cd rsLXMF
|
||||
cargo build --release --locked
|
||||
```
|
||||
|
||||
@@ -108,7 +116,6 @@ Build Tools, install the "Desktop development with C++" workload.
|
||||
Build from PowerShell:
|
||||
|
||||
```powershell
|
||||
cd rsLXMF
|
||||
cargo build --release --locked
|
||||
```
|
||||
|
||||
@@ -125,7 +132,7 @@ macOS/Linux or `.\target\release\lxmd-rs.exe` on Windows.
|
||||
|
||||
|
||||
|
||||
Generate the example config:
|
||||
Print the example configuration to standard output:
|
||||
|
||||
```bash
|
||||
lxmd-rs --exampleconfig
|
||||
@@ -143,11 +150,11 @@ Run a propagation node:
|
||||
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --propagation-node
|
||||
```
|
||||
|
||||
Send a message and exit:
|
||||
Send a message and exit. Replace uppercase hash placeholders with the appropriate 32-character hexadecimal destination hash:
|
||||
|
||||
```bash
|
||||
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum \
|
||||
--send <destination_hash> "message body"
|
||||
--send "DELIVERY_DESTINATION_HASH" "message body"
|
||||
```
|
||||
|
||||
The `--send` flag is an rsLXMF convenience. Normal
|
||||
@@ -157,7 +164,7 @@ Send UTF-8 file content or select a delivery method:
|
||||
|
||||
```bash
|
||||
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum \
|
||||
--send <destination_hash> --send-file ./message.txt --send-method direct
|
||||
--send "DELIVERY_DESTINATION_HASH" --send-file ./message.txt --send-method direct
|
||||
```
|
||||
|
||||
Supported `--send-method` values are `opportunistic`, `direct`, and
|
||||
@@ -167,20 +174,23 @@ Attach custom LXMF fields from scripts:
|
||||
|
||||
```bash
|
||||
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum \
|
||||
--send <destination_hash> "with fields" \
|
||||
--send-fields-json '{"1":"aGVsbG8=","42":"AAECAw=="}'
|
||||
--send "DELIVERY_DESTINATION_HASH" "with fields" \
|
||||
--send-fields-json '{"200":"aGVsbG8=","201":"AAECAw=="}'
|
||||
```
|
||||
|
||||
The JSON object maps field IDs to base64-encoded bytes. It is only a shell
|
||||
convenience; LXMF fields remain MessagePack field maps on the wire.
|
||||
The CLI JSON object maps IDs from 0 to 255 to base64-encoded binary values.
|
||||
Choose IDs and schemas agreed with the receiving application. This option
|
||||
does not construct structured MessagePack fields such as an LRGP envelope;
|
||||
use the library’s typed field API for those. The library supports a wider
|
||||
integer ID range than this CLI convenience.
|
||||
|
||||
Control a propagation node:
|
||||
|
||||
```bash
|
||||
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --status
|
||||
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --peers
|
||||
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --sync <peer_hash>
|
||||
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --break <peer_hash>
|
||||
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --sync "PEER_PROPAGATION_HASH"
|
||||
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --break "PEER_PROPAGATION_HASH"
|
||||
```
|
||||
|
||||
These commands query an `lxmf.propagation.control` endpoint over Reticulum.
|
||||
@@ -192,7 +202,7 @@ For a remote propagation node, pass the node's propagation destination hash:
|
||||
|
||||
```bash
|
||||
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum \
|
||||
--status --peers --remote <propagation_destination_hash> --timeout 5
|
||||
--status --peers --remote "PROPAGATION_DESTINATION_HASH" --timeout 5
|
||||
```
|
||||
|
||||
Control queries use `<config-dir>/identity` by default. Use `--identity PATH`
|
||||
@@ -218,6 +228,8 @@ If no LXMF config directory is supplied, the default is:
|
||||
| Linux/macOS | `/etc/rsLXMF/config`, then `~/.config/rsLXMF/config`, then `~/.rsLXMF/config` |
|
||||
| Windows | `%APPDATA%\rsLXMF\config` |
|
||||
|
||||
On Linux/macOS, the first two locations are selected only when their `config` file exists; otherwise the home-directory fallback is used.
|
||||
|
||||
|
||||
If `--rnsconfig` is omitted, Reticulum config resolution follows
|
||||
rsReticulum-specific defaults.
|
||||
@@ -251,8 +263,8 @@ autopeer = yes
|
||||
autopeer_maxdepth = 6
|
||||
auth_required = no
|
||||
# node_name = Rat Nest
|
||||
# static_peers = e17f833c4ddf8890dd3a79a6fea8161d
|
||||
# outbound_node = e17f833c4ddf8890dd3a79a6fea8161d
|
||||
# static_peers = 0123456789abcdef0123456789abcdef
|
||||
# outbound_node = 0123456789abcdef0123456789abcdef
|
||||
# max_peers = 20
|
||||
# propagation_stamp_cost_target = 16
|
||||
# propagation_stamp_cost_flexibility = 3
|
||||
@@ -261,17 +273,16 @@ auth_required = no
|
||||
loglevel = 4
|
||||
```
|
||||
|
||||
The standalone daemon follows current Python LXMF 1.1.0 and defaults this
|
||||
setting to 1 decimal KB when it is omitted. This is intentionally distinct
|
||||
from the reusable router library's 1000 KB default. Applications that accept
|
||||
`delivery_transfer_max_accepted_size` limits incoming Direct Resource data
|
||||
in decimal KB and defaults to 1 when omitted. The reusable router library has a separate 1000 KB default. Applications that accept
|
||||
larger incoming messages should set their own explicit policy.
|
||||
|
||||
Supported sections:
|
||||
Common sections and supported keys (see `--exampleconfig` for annotated defaults):
|
||||
|
||||
| Section | Keys |
|
||||
| --- | --- |
|
||||
| `[lxmf]` | `display_name`, `announce_at_start`, `announce_interval`, `delivery_transfer_max_accepted_size`, `stamp_cost`, `on_inbound` |
|
||||
| `[propagation]` | `enable_node`, `node_name`, `auth_required`, `announce_at_start`, `announce_interval`, `autopeer`, `autopeer_maxdepth`, `message_storage_limit`, `propagation_message_max_accepted_size`, `propagation_sync_max_accepted_size`, `propagation_stamp_cost_target`, `propagation_stamp_cost_flexibility`, `peering_cost`, `remote_peering_cost_max`, `max_peers`, `static_peers`, `prioritise_destinations`, `control_allowed`, `from_static_only`, `outbound_node`, `propagation_stamp_cost`, `propagation_limit`, `enforce_stamps` |
|
||||
| `[propagation]` | `enable_node`, `node_name`, `auth_required`, `announce_at_start`, `announce_interval`, `autopeer`, `autopeer_maxdepth`, `message_storage_limit`, `propagation_message_max_accepted_size`, `propagation_sync_max_accepted_size`, `propagation_stamp_cost_target`, `propagation_stamp_cost_flexibility`, `peering_cost`, `remote_peering_cost_max`, `max_peers`, `static_peers`, `prioritise_destinations`, `control_allowed`, `from_static_only`, `sequential_pn_stamp_validation`, `static_peers_bypass_sequential`, `max_inbound_syncs`, `outbound_node`, `propagation_stamp_cost`, `propagation_limit`, `enforce_stamps` |
|
||||
| `[control]` | `auth_required`, `allowed` |
|
||||
| `[logging]` | `loglevel` |
|
||||
|
||||
@@ -279,10 +290,10 @@ Optional hash-list files live next to `<config-dir>/config`:
|
||||
|
||||
| File | Meaning |
|
||||
| --- | --- |
|
||||
| `ignored` | Hashes loaded into the router ignored list. |
|
||||
| `allowed` | Hashes loaded into the router delivery allow-list. Empty means no allow-list restriction. |
|
||||
| `ignored` | LXMF destination hashes to ignore. |
|
||||
| `allowed` | Reticulum **identity hashes** permitted to retrieve messages when propagation `auth_required = yes`. An empty list then admits no clients. |
|
||||
|
||||
Hash-list files accept one raw 32-character hex destination hash per line.
|
||||
Each file accepts one raw 32-character hex hash per line. The two files use different hash types. Propagation administration is separate: `control_allowed` contains authorized control identity hashes; the daemon’s own identity is also authorized. Client retrieval authorization does not make the node’s stored messages readable to other clients.
|
||||
|
||||
## Delivery Model
|
||||
|
||||
@@ -291,7 +302,7 @@ and, where network-backed, through `lxmd-rs --send-method`.
|
||||
|
||||
| Method | Behavior |
|
||||
| --- | --- |
|
||||
| Opportunistic | Single-packet delivery when the packed message fits the Reticulum packet path. Delivery completes only after an authenticated Reticulum proof; bounded retries remain in flight until then. Oversized opportunistic messages are downgraded to Direct by the router. |
|
||||
| Opportunistic | Single-packet delivery when the packed message fits the Reticulum packet path. Delivery completes only after an authenticated Reticulum proof; bounded retries remain in flight until then. The router switches oversized opportunistic messages to Direct. |
|
||||
| Direct | Link-backed delivery over a Reticulum Link, with resource transfer for larger content. |
|
||||
| Propagated | Store-and-forward delivery through a propagation node, including deposit, retrieve, peer sync, stamps, and tickets. |
|
||||
| Paper | Library support for `lxm://` URI generation and ingest. The CLI does not generate QR images. |
|
||||
@@ -312,13 +323,17 @@ signature 64 bytes
|
||||
payload MessagePack([timestamp, title, content, fields, optional_stamp])
|
||||
```
|
||||
|
||||
`title` and `content` are bytes on the wire. `fields` is a `map<u8, bytes>` for
|
||||
application-defined data such as tickets, attachments, location data, or
|
||||
application envelopes.
|
||||
`title` and `content` are bytes on the wire. `fields` maps integer IDs to
|
||||
MessagePack values, which can be binary, text, arrays, maps or other supported
|
||||
values. Standard fields have defined schemas. The 1.4 library preserves signed
|
||||
and unsigned integer IDs beyond the CLI’s 0–255 range and rejects duplicate
|
||||
outer IDs. Encoding a structured field as a binary blob changes its meaning.
|
||||
|
||||
Library callers requesting a reply ticket set `include_ticket`, call
|
||||
`LxmRouter::prepare_outbound`, and then sign the message. The router rejects a
|
||||
requested ticket that would require changing an already-signed message.
|
||||
In the 1.4 API, construct `LxMessageDraft` and set `include_ticket` before
|
||||
calling `LxmRouter::prepare_outbound`. Persist the returned ticket intent before
|
||||
signing; a pending intent blocks signing. Signing consumes the draft, and
|
||||
finalization produces an immutable message. See the [1.4 migration guide](api/migrations/1.4.md)
|
||||
for stamp work, typed fields, inbound verification and propagation storage.
|
||||
|
||||
|
||||
## Feature Status
|
||||
@@ -326,7 +341,7 @@ requested ticket that would require changing an already-signed message.
|
||||
| Area | Current behavior |
|
||||
| --- | --- |
|
||||
| Message format | Signed LXMF envelopes, custom field maps, standard reply/reaction/comment fields, propagation wrappers, `.lxm` containers, and paper URI encode/decode. |
|
||||
| Delivery | Opportunistic, Direct, Propagated, callbacks, failure callbacks, cancellation, progress state, opportunistic-to-direct downgrade, and compression signalling in delivery announces. |
|
||||
| Delivery | Opportunistic, Direct, Propagated, callbacks, failure callbacks, cancellation, progress state, opportunistic-to-direct fallback, and compression signalling in delivery announces. |
|
||||
| Propagation | Transactional disk-backed store, deposit, retrieve, peer sync, autopeer/static peers, weighted culling, duplicate checks, size checks, and stamp checks. |
|
||||
| Stamps and tickets | Soft/hard stamp validation, HKDF-expanded workblocks, cached destination stamp costs, automatic reply-ticket issue and signed learning, ticket-backed stamps, and restart-safe directional persistence. |
|
||||
| Control | `--status`, `--peers`, `--sync`, and `--break` over the propagation-control link. |
|
||||
@@ -342,11 +357,12 @@ Most daemon and control flags are implemented: `--config`, `--rnsconfig`,
|
||||
Additional rsLXMF-only flags: `--send`, `--send-file`, `--send-method`,
|
||||
`--send-timeout-secs`, and `--send-fields-json`.
|
||||
|
||||
The complete release-baseline corpus and live matrix use Python LXMF 1.0.1
|
||||
The complete corpus and live matrix for 1.3.0 and 1.4.0 use Python LXMF 1.0.1
|
||||
with Reticulum 1.4.2. A supplementary lane checks daemon, delivery,
|
||||
Resource/proof, and propagation behavior against exact LXMF 1.1.0 with the
|
||||
same Reticulum 1.4.2 source. Historical vectors retain their original
|
||||
provenance, and RNS 1.5.0 is intentionally deferred.
|
||||
provenance. Later source changes include selected LXMF 1.2.0 behavior; that
|
||||
does not establish complete compatibility with every later Python release.
|
||||
|
||||
## Contributing
|
||||
|
||||
@@ -357,4 +373,12 @@ PRs are closed for now until I have time to catch up on everything. I'm tired.
|
||||
|
||||
## License
|
||||
|
||||
GNU Affero General Public License v3.0 or later. See [LICENSE](LICENSE).
|
||||
rsLXMF is licensed under the [Reticulum License](LICENSE), the license of the
|
||||
reference implementation it is ported from. Copyright (c) 2020-2026 Mark Qvist,
|
||||
unless otherwise noted; additions and modifications Copyright (c) 2026 Ratspeak
|
||||
LLC.
|
||||
|
||||
The license is permissive with two conditions: no use in systems built to
|
||||
purposefully harm people, and no use in or contribution to AI or language-model
|
||||
training. The copyright and permission notice must stay in every copy.
|
||||
[LICENSE](LICENSE) is the binding text.
|
||||
+10
-8
@@ -1,9 +1,11 @@
|
||||
# Rust API
|
||||
|
||||
Application code that constructs or inspects LXMF messages should use
|
||||
`lxmf_core::message_api`. It re-exports the existing message, status, and
|
||||
identifier types without wrapping or replacing them. The original
|
||||
module-qualified paths remain supported.
|
||||
This guide describes the 1.4.0 API, published as v1.4.0, not the 1.3.0
|
||||
daemon. Application code should use `lxmf_core::message_api`, which
|
||||
re-exports the message types without wrappers. The equivalent module-qualified
|
||||
paths remain available. The [1.4 migration guide](migrations/1.4.md) explains
|
||||
the source-breaking change from mutable messages to drafts, signed messages
|
||||
and immutable finalized messages.
|
||||
|
||||
The compiled `lxmf-core` `message` example demonstrates message construction,
|
||||
signing, packing, and unpacking through this path.
|
||||
@@ -20,10 +22,10 @@ provisional module-qualified APIs.
|
||||
`lxmf-tools` supports the `lxmd-rs` binary and is not a public library
|
||||
integration target.
|
||||
|
||||
The message facade changes no wire fields, signatures, serialization,
|
||||
delivery methods, proofs, persistence, or runtime behavior. Later reductions
|
||||
to the broader module tree require a reviewed API diff, downstream migration,
|
||||
and an explicit version decision.
|
||||
Choosing the facade instead of the equivalent module-qualified path does not
|
||||
change behavior. Upgrading from 1.3 to 1.4 does change message and persistence
|
||||
APIs; follow the migration guide. Further reductions to the broader module tree
|
||||
require a reviewed API diff, downstream migration and an explicit version decision.
|
||||
|
||||
## Delivery-owner integration
|
||||
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
# 1.4 source migration (unreleased)
|
||||
# Migrating to the 1.4 source API
|
||||
|
||||
The 1.4 line is published as v1.4.0 and is the source line Ratspeak builds
|
||||
from. These APIs and migration commands require a 1.4 build.
|
||||
|
||||
Messages now retain the exact signed bytes received or finalized for sending.
|
||||
Verification, storage, and delivery metadata cannot change those bytes. The
|
||||
@@ -6,6 +9,8 @@ Verification, storage, and delivery metadata cannot change those bytes. The
|
||||
|
||||
## Construct, sign, then finalize
|
||||
|
||||
This fragment uses `?` to propagate `MessageError` from the enclosing function.
|
||||
|
||||
```rust
|
||||
use lxmf_core::message_api::{DeliveryMethod, LxMessageDraft};
|
||||
use rns_crypto::ed25519::Ed25519PrivateKey;
|
||||
@@ -19,7 +24,6 @@ let signed = draft.sign(&Ed25519PrivateKey::generate())?;
|
||||
let stamp = signed.generate_recipient_stamp()?;
|
||||
let message = signed.finalize(stamp)?;
|
||||
let bytes = message.wire_bytes();
|
||||
# Ok::<(), lxmf_core::message_api::MessageError>(())
|
||||
```
|
||||
|
||||
Use `sign_with` for an external or hardware signer. Both signing methods consume
|
||||
@@ -85,7 +89,7 @@ wire bytes. Use `new_with_limits` and `unpack_owned` with the same explicit
|
||||
count and exact size before signing and finalization, including stamp framing.
|
||||
These are parser/construction ceilings, not transport promises: Resource segment
|
||||
limits, metadata, encryption and propagation wrapping impose separate admission
|
||||
checks. The embedded profile retains 64 fields and depth8; host-valid custom
|
||||
checks. The embedded profile retains 64 fields and depth 8; host-valid custom
|
||||
messages are not automatically compatible with every device.
|
||||
|
||||
Old corrupted files are never silently repaired or re-signed. A hash-shaped
|
||||
@@ -176,7 +180,7 @@ copy that was already delivered.
|
||||
|
||||
`submit_signed` now refuses a message whose id is already queued, awaiting its
|
||||
stamp or delivery, with `MessageError::AlreadyQueued`. Treat that result as
|
||||
already sent.
|
||||
already queued; it is not evidence of transmission or recipient delivery.
|
||||
|
||||
## Retaining delivered destinations
|
||||
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
# Relay store migration
|
||||
|
||||
This guide applies to the 1.4 API and daemon, published as v1.4.0. The 1.3.0
|
||||
binary does not provide this migration.
|
||||
|
||||
Relay nodes now admit only validated opaque propagation data to a durable store.
|
||||
A packet proof follows complete validation and acknowledged durable admission.
|
||||
Resource completion still means transport completion; it does not certify the
|
||||
@@ -20,7 +23,7 @@ whole message bodies; every read verifies the full body, and a body that fails
|
||||
is not served.
|
||||
|
||||
Stop every process that can write the store, including service supervisors and
|
||||
scheduled restarts. Then run the candidate daemon against the correct config:
|
||||
scheduled restarts. Then run the 1.4 source-built daemon against the correct config:
|
||||
|
||||
```sh
|
||||
lxmd-rs --config /path/to/config --migrate-propagation-store --relay-writers-stopped
|
||||
|
||||
@@ -5,7 +5,7 @@ publish = false
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
license-file.workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64 = { workspace = true }
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
//! Construct, sign, freeze, and inspect a message through the canonical API.
|
||||
//! The hashes below are placeholders: this local packing example does not
|
||||
//! authenticate a sender or transmit a message. Real source hashes must bind
|
||||
//! the signing identity to its lxmf.delivery destination.
|
||||
use lxmf_core::message_api::{DeliveryMethod, LxMessage, LxMessageDraft, MessageState};
|
||||
use rns_crypto::ed25519::Ed25519PrivateKey;
|
||||
|
||||
|
||||
@@ -46,8 +46,10 @@ pub struct AdmissionRecord {
|
||||
pub committed_at: u64,
|
||||
}
|
||||
|
||||
/// Verified local purge authority with its finite policy lifetime. Adapters
|
||||
/// supply these only after checking the referenced durable effect.
|
||||
/// Local purge authority with an optional expiry. Policy-discard and user-deleted
|
||||
/// receipts expire after [`POLICY_RECEIPT_LIFETIME`]; committed/duplicate receipts
|
||||
/// have no time expiry. Adapters must check the referenced durable effect before
|
||||
/// supplying this value; constructing it does not perform that verification.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct DurableHave {
|
||||
pub transient_id: [u8; 32],
|
||||
@@ -84,8 +86,9 @@ pub enum AdmissionError {
|
||||
/// Trusted persistence adapter boundary. Implementations must atomically commit
|
||||
/// the receipt with the message/effect, or reference a previously durable effect.
|
||||
/// In particular, returning a record after a failed/uncertain filesystem or SQL
|
||||
/// commit violates this contract. SQLite implementations use the dedicated FULL
|
||||
/// connection; file implementations use the intent/body/commit journal.
|
||||
/// commit violates this contract. SQL adapters must establish their transaction
|
||||
/// and durability guarantees. [`crate::admission_store::FileAdmissionStore`]
|
||||
/// uses an intent/body/commit journal.
|
||||
pub trait DurableAdmissionBackend {
|
||||
fn commit(self) -> Result<AdmissionRecord, AdmissionError>;
|
||||
}
|
||||
@@ -320,8 +323,9 @@ pub(crate) struct AdmissionResolution {
|
||||
pub outcome: DownloadAdmissionOutcome,
|
||||
}
|
||||
|
||||
/// Single-use, generation-bound authority. Dropping it reports a retryable
|
||||
/// failure; cancelling its client generation cannot cancel a blocking commit.
|
||||
/// Single-use, generation-bound authority. Dropping an unresolved token attempts
|
||||
/// to send a Cancelled rejection to its consumer. Cancelling the client generation
|
||||
/// cannot cancel a blocking commit.
|
||||
pub struct DownloadAdmissionToken {
|
||||
scope: AdmissionScope,
|
||||
generation: u64,
|
||||
@@ -355,11 +359,19 @@ impl DownloadAdmissionToken {
|
||||
pub fn scope(&self) -> AdmissionScope {
|
||||
self.scope
|
||||
}
|
||||
/// Check immediately after durable commit before publishing current-generation effects.
|
||||
/// Cancellation cannot stop an in-flight commit or release its memory lease.
|
||||
/// Read whether this token still belongs to the current client generation.
|
||||
///
|
||||
/// This is a snapshot, not a lock: the generation can change immediately.
|
||||
/// Check after durable commit and use the adapter's lifecycle gate around
|
||||
/// current-generation UI effects. Cancellation cannot stop an in-flight
|
||||
/// commit or release its memory lease.
|
||||
pub fn is_current(&self) -> bool {
|
||||
self.current_generation.load(Ordering::Acquire) == self.generation
|
||||
}
|
||||
/// Enqueue one outcome for this token's scope and current generation.
|
||||
/// Success reports enqueueing, not remote deletion or an atomic lifecycle
|
||||
/// transition; the consumer rechecks the generation before applying it.
|
||||
/// A mismatched scope, revoked generation or closed consumer returns an error.
|
||||
pub fn resolve(mut self, outcome: DownloadAdmissionOutcome) -> Result<(), AdmissionError> {
|
||||
if let DownloadAdmissionOutcome::Accepted(receipt) = &outcome
|
||||
&& receipt.record.scope != self.scope
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
//! File adapter for lxmd's durable download receipts and hook outbox.
|
||||
//! The original ciphertext TID is journaled before publishing decrypted bytes.
|
||||
//! Keep exclusive ownership of the journal and body paths while the store is
|
||||
//! open; its mutex coordinates clones of one store, not independent open calls
|
||||
//! or external file writers.
|
||||
use crate::admission::*;
|
||||
use bytes::Bytes;
|
||||
use rns_identity::persistence::{
|
||||
@@ -109,6 +112,11 @@ impl FileAdmissionStore {
|
||||
})
|
||||
}
|
||||
|
||||
/// Prepare a persistence operation for an already authenticated message and
|
||||
/// caller-selected disposition. The scope must retain the original ciphertext
|
||||
/// TID; this method recomputes only the received plaintext wire hash.
|
||||
/// Neither preparation nor commit authenticates the sender. Preparation writes
|
||||
/// no files; commit performs persistence.
|
||||
pub fn prepare(
|
||||
&self,
|
||||
mut record: AdmissionRecord,
|
||||
@@ -125,8 +133,10 @@ impl FileAdmissionStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// Durable visible receipts remain while their referenced message exists;
|
||||
/// invisible policy/TID accelerators expire after the local90-day policy.
|
||||
/// Return live receipts from committed or recovered state for this identity/node.
|
||||
/// Visible receipts have no time expiry; invisible policy/TID receipts expire
|
||||
/// after 90 days. This query does not re-read archive files. Use the store's
|
||||
/// deletion API to revoke visible receipts when deleting a message.
|
||||
pub fn haves(&self, identity: [u8; 16], node: [u8; 16], now: u64) -> Vec<Vec<u8>> {
|
||||
let inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
|
||||
inner
|
||||
|
||||
@@ -173,7 +173,7 @@ pub const PATH_REQUEST_WAIT: u64 = 7;
|
||||
pub const MAX_PATHLESS_TRIES: u32 = 1;
|
||||
/// Maximum link inactivity before teardown (seconds).
|
||||
pub const LINK_MAX_INACTIVITY: u64 = 10 * 60;
|
||||
/// Maximum propagation link inactivity (seconds).
|
||||
/// Python propagation-link inactivity limit, in seconds; retained as a reference value.
|
||||
pub const P_LINK_MAX_INACTIVITY: u64 = 3 * 60;
|
||||
pub const MESSAGE_EXPIRY: u64 = 30 * 24 * 60 * 60;
|
||||
pub const STAMP_COST_EXPIRY: u64 = 45 * 24 * 60 * 60;
|
||||
@@ -196,7 +196,7 @@ pub const PN_STAMP_THROTTLE: u64 = 180;
|
||||
|
||||
pub const AUTOPEER: bool = true;
|
||||
pub const AUTOPEER_MAXDEPTH: usize = 4;
|
||||
/// When selecting peers for sync, pick from the N fastest.
|
||||
/// Size of the fastest-peer pool considered alongside unknown-speed peers.
|
||||
pub const FASTEST_N_RANDOM_POOL: usize = 2;
|
||||
/// Percentage of max_peers kept as headroom for rotation.
|
||||
pub const ROTATION_HEADROOM_PCT: usize = 10;
|
||||
@@ -213,12 +213,12 @@ pub const DUPLICATE_SIGNAL: &str = "lxmf_duplicate";
|
||||
|
||||
pub const OFFER_REQUEST_PATH: &str = "/offer";
|
||||
pub const MESSAGE_GET_PATH: &str = "/get";
|
||||
/// Maximum time a peer can be unreachable before removal (14 days).
|
||||
/// Age since last contact after which `mark_unreachable` marks a peer not alive (14 days).
|
||||
pub const MAX_UNREACHABLE: u64 = 14 * 24 * 60 * 60;
|
||||
/// Sync backoff step per consecutive failure (12 minutes).
|
||||
pub const SYNC_BACKOFF_STEP: u64 = 12 * 60;
|
||||
pub const PATH_REQUEST_GRACE: f64 = 7.5;
|
||||
/// Maximum time a peer can be stale before rotation (14 days).
|
||||
/// Age since last contact used by the peer staleness check (14 days).
|
||||
pub const PEER_STALE_TIME: u64 = 14 * 24 * 60 * 60;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -263,22 +263,23 @@ pub const STAMP_WORKBLOCK_EXPAND_ROUNDS_PN: usize = 1000;
|
||||
pub const STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING: usize = 25;
|
||||
/// SHA-256 output length.
|
||||
pub const STAMP_SIZE: usize = 32;
|
||||
/// Minimum batch size before using parallel validation pool.
|
||||
/// Python propagation-validation pool threshold, retained as a reference constant.
|
||||
pub const PN_VALIDATION_POOL_MIN_SIZE: usize = 256;
|
||||
|
||||
/// Interval (in ticks) for processing outbound messages.
|
||||
/// Python outbound-processing cadence in ticks; retained as a reference constant.
|
||||
pub const JOB_OUTBOUND_INTERVAL: u64 = 1;
|
||||
/// Interval (in ticks) for processing deferred stamps.
|
||||
/// Python deferred-stamp cadence in ticks; retained as a reference constant.
|
||||
pub const JOB_STAMPS_INTERVAL: u64 = 1;
|
||||
/// Interval (in ticks) for cleaning inactive links.
|
||||
/// Python inactive-link cleanup cadence in ticks; retained as a reference constant.
|
||||
pub const JOB_LINKS_INTERVAL: u64 = 1;
|
||||
/// Interval (in ticks) for cleaning transient ID caches.
|
||||
pub const JOB_TRANSIENT_INTERVAL: u64 = 60;
|
||||
/// Interval (in ticks) for cleaning the message store.
|
||||
pub const JOB_STORE_INTERVAL: u64 = 120;
|
||||
/// Interval (in ticks) for syncing peers.
|
||||
/// Tick interval for cleaning throttled-peer entries, named for Python
|
||||
/// peer-sync cadence. Peer synchronization is driven by the embedding runtime.
|
||||
pub const JOB_PEERSYNC_INTERVAL: u64 = 6;
|
||||
/// Interval (in ticks) for ingesting peer distribution queues.
|
||||
/// Python peer-distribution ingestion cadence in ticks; retained as a reference constant.
|
||||
pub const JOB_PEERINGEST_INTERVAL: u64 = 6;
|
||||
/// 56 * JOB_PEERINGEST_INTERVAL.
|
||||
pub const JOB_ROTATE_INTERVAL: u64 = 56 * 6;
|
||||
|
||||
@@ -57,7 +57,11 @@ pub struct DeliveryRatchetState {
|
||||
}
|
||||
|
||||
impl DeliveryRatchetState {
|
||||
/// Load verified state, preserving any invalid existing files in place.
|
||||
/// Load canonical or legacy Rust state, preserving rejected files in place.
|
||||
/// Canonical signatures cover the packed key list. Accepted legacy signatures
|
||||
/// cover only the current public key, not retained old keys; canonical rewrite
|
||||
/// is best-effort and does not establish their historical authenticity.
|
||||
/// A failed rewrite does not prevent use of the accepted legacy ring.
|
||||
///
|
||||
/// A missing ring is generated and persisted before it becomes live. A
|
||||
/// ring that cannot be stored leaves delivery available but unratcheted.
|
||||
|
||||
@@ -2,15 +2,15 @@
|
||||
//!
|
||||
//! # Layering
|
||||
//!
|
||||
//! Python `RNS/Discovery.py:41` imports `LXMF.LXStamper` directly; the
|
||||
//! discovery subsystem cannot work without LXMF installed. Rust keeps
|
||||
//! Python `RNS.Discovery.InterfaceAnnouncer` loads `LXMF.LXStamper` when
|
||||
//! initialized, requiring LXMF for on-network discovery. Rust keeps
|
||||
//! Reticulum below LXMF, so `rns-transport` depends on a trait object and
|
||||
//! the concrete implementation lives here.
|
||||
//!
|
||||
//! # Workblock: Python parity
|
||||
//!
|
||||
//! Python discovery uses `LXStamper.stamp_workblock(infohash, expand_rounds=20)`
|
||||
//! (RNS/Discovery.py:220), where `stamp_workblock` is the
|
||||
//! in `InterfaceAnnouncer`, where `stamp_workblock` is the
|
||||
//! HKDF-expanded construction: one HKDF expand per round, each round
|
||||
//! producing 256 bytes, total `expand_rounds * 256` bytes.
|
||||
//! [`crate::stamper::stamp_workblock`] is the same construction.
|
||||
@@ -26,14 +26,10 @@ use crate::stamper::{stamp_valid, stamp_value, stamp_workblock};
|
||||
/// interface, so this path has to stay cheap enough for periodic announces.
|
||||
pub const DISCOVERY_WORKBLOCK_EXPAND_ROUNDS: usize = 20;
|
||||
|
||||
/// Upper bound on the random-stamp search before we give up on a given
|
||||
/// tick. If the cap is hit, the announcer skips this cycle and tries again
|
||||
/// rather than pinning a blocking worker indefinitely.
|
||||
///
|
||||
/// Python has no equivalent cap (it blocks until success); we cap so
|
||||
/// `spawn_blocking` threads cannot be stuck forever if the user
|
||||
/// misconfigures `discover_interfaces_required_value` to something
|
||||
/// unreasonable.
|
||||
/// Default attempt budget for one discovery stamp search. Exhaustion returns
|
||||
/// `None`, allowing the announcer to skip this preparation attempt and retry.
|
||||
/// The budget limits attempts, not elapsed time. The requested generation cost
|
||||
/// comes from the per-interface announce configuration.
|
||||
pub const DISCOVERY_MAX_ITERATIONS: u64 = 5_000_000;
|
||||
|
||||
/// PoW stamper for on-network discovery announces. Thin wrapper around
|
||||
@@ -50,8 +46,9 @@ pub struct LxmfDiscoveryStamper {
|
||||
}
|
||||
|
||||
impl LxmfDiscoveryStamper {
|
||||
/// Build a stamper with a custom iteration cap. Most callers want
|
||||
/// [`LxmfDiscoveryStamper::default`].
|
||||
/// Build a stamper with a custom iteration cap. Zero selects
|
||||
/// [`DISCOVERY_MAX_ITERATIONS`], as does [`LxmfDiscoveryStamper::default`].
|
||||
/// This differs from [`generate_discovery_stamp`], where zero allows no attempts.
|
||||
pub fn with_max_iterations(max_iterations: u64) -> Self {
|
||||
Self { max_iterations }
|
||||
}
|
||||
@@ -107,10 +104,10 @@ impl DiscoveryStamper for LxmfDiscoveryStamper {
|
||||
}
|
||||
}
|
||||
|
||||
/// Validation helper: synchronous wrapper mirroring
|
||||
/// [`crate::stamper::generate_stamp_limited`] but using the HKDF
|
||||
/// workblock construction. Public so interop tests and downstream validation
|
||||
/// can exercise discovery stamping without a transport runtime.
|
||||
/// Synchronous discovery stamp search with 20 HKDF workblock rounds and an
|
||||
/// explicit attempt limit. Uses the same construction as
|
||||
/// [`crate::stamper::generate_stamp_limited`], without a transport runtime.
|
||||
/// For nonzero cost, a zero iteration limit returns `None`.
|
||||
pub fn generate_discovery_stamp(
|
||||
infohash: &[u8; 32],
|
||||
target_value: u8,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Announce handlers for `lxmf.delivery` and `lxmf.propagation` destinations, plus the
|
||||
//! propagation-node control endpoint dispatcher.
|
||||
//!
|
||||
//! Python reference: LXMF/Handlers.py, LXMF.py:172-198, LXMRouter.py:306-318, LXMRouter.py:985-1000.
|
||||
//! Related Python code: LXMF/Handlers.py, the announce helpers in LXMF.py,
|
||||
//! and the request handlers in LXMRouter.py.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -55,18 +56,19 @@ pub enum CompressionSupport {
|
||||
/// `[false, timebase, node_state, transfer_limit_kb, sync_limit_kb,
|
||||
/// [stamp_cost, stamp_flex, peering_cost], metadata]`.
|
||||
///
|
||||
/// Python reference: LXMRouter.py:306-318.
|
||||
/// Python reference: `LXMRouter.get_propagation_node_app_data`.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PropagationNodeAnnounceData {
|
||||
/// Legacy LXMF PN-support flag, always false.
|
||||
/// Compatibility field. The constructor/parser set it to false, and the
|
||||
/// encoder always writes false regardless of this field.
|
||||
pub legacy: bool,
|
||||
/// Node timebase as Unix seconds.
|
||||
pub timebase: i64,
|
||||
/// True when the node is actively serving propagation.
|
||||
pub node_state: bool,
|
||||
/// Per-transfer limit in kilobytes.
|
||||
/// Per-transfer limit in decimal kilobytes (1 kB = 1000 bytes).
|
||||
pub transfer_limit: u64,
|
||||
/// Per-sync limit in kilobytes.
|
||||
/// Per-sync limit in decimal kilobytes (1 kB = 1000 bytes).
|
||||
pub sync_limit: u64,
|
||||
pub stamp_cost: u8,
|
||||
pub stamp_flex: u8,
|
||||
@@ -111,7 +113,7 @@ impl PropagationNodeAnnounceData {
|
||||
|
||||
/// Encode propagation-node announce `app_data` as msgpack.
|
||||
///
|
||||
/// Python reference: LXMRouter.py:306-318.
|
||||
/// Python reference: `LXMRouter.get_propagation_node_app_data`.
|
||||
pub fn get_propagation_node_app_data(data: &PropagationNodeAnnounceData) -> Vec<u8> {
|
||||
use rmpv::Value;
|
||||
|
||||
@@ -142,13 +144,16 @@ pub fn get_propagation_node_app_data(data: &PropagationNodeAnnounceData) -> Vec<
|
||||
crate::encode_value(&announce_data)
|
||||
}
|
||||
|
||||
/// Parse propagation-node announce data. Returns `None` if the data is
|
||||
/// malformed (not msgpack, not an array, fewer than 7 elements, or any
|
||||
/// element of the wrong type) — same rejection criteria as Python's
|
||||
/// `pn_announce_data_is_valid` at `LXMF.py:172-198`. The validator and
|
||||
/// the parser used to be two separate functions; the validator was
|
||||
/// dropped because it duplicated this function's checks and every
|
||||
/// in-tree caller called both back-to-back.
|
||||
/// Parse a propagation-node announce array with at least seven elements.
|
||||
///
|
||||
/// Requires a boolean state, numeric timebase, nonnegative finite limits/costs,
|
||||
/// a cost array with at least three values, and a metadata map. Rust casts apply; costs must
|
||||
/// fit in `u8` after conversion. The legacy slot is ignored. Only metadata with
|
||||
/// `u8` keys and binary values is retained. Extra array elements and trailing
|
||||
/// MessagePack bytes are not rejected.
|
||||
///
|
||||
/// This parser does not authenticate the announce or enforce timebase freshness.
|
||||
/// Its coercion and filtering rules differ from Python `pn_announce_data_is_valid`.
|
||||
pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData> {
|
||||
fn nonnegative_u64(value: &rmpv::Value) -> Option<u64> {
|
||||
value
|
||||
@@ -211,7 +216,7 @@ pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData
|
||||
|
||||
/// Extract stamp cost from propagation-node announce data.
|
||||
///
|
||||
/// Python reference: `pn_stamp_cost_from_app_data` — LXMF.py:163-170.
|
||||
/// Uses [`parse_pn_announce_data`] and its numeric conversion rules.
|
||||
pub fn pn_stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
|
||||
parse_pn_announce_data(data).map(|p| p.stamp_cost)
|
||||
}
|
||||
@@ -222,7 +227,8 @@ pub fn pn_stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
|
||||
///
|
||||
/// `stamp_cost` must be in `1..=254`; out-of-range or `None` values are encoded as nil.
|
||||
///
|
||||
/// Python reference: `get_announce_app_data` — LXMRouter.py:985-1001 (1.0.1).
|
||||
/// Names are sanitized and limited to [`MAX_ADVERTISED_NAME_CHARS`] characters.
|
||||
/// Python reference: `LXMRouter.get_announce_app_data`.
|
||||
pub fn get_announce_app_data(display_name: Option<&str>, stamp_cost: Option<u8>) -> Vec<u8> {
|
||||
use rmpv::Value;
|
||||
|
||||
@@ -246,8 +252,10 @@ pub fn get_announce_app_data(display_name: Option<&str>, stamp_cost: Option<u8>)
|
||||
|
||||
/// Parse delivery-announce `app_data`, returning `(display_name, stamp_cost)`.
|
||||
///
|
||||
/// Accepts both Python LXMF <=0.9.8's 2-element form and the 3-element
|
||||
/// feature-list form emitted from 1.0.1 (and extended peers).
|
||||
/// Requires an array with at least two elements; later elements are ignored.
|
||||
/// A binary UTF-8 name is sanitized and bounded. Unsigned stamp costs are cast
|
||||
/// to `u8`, retaining the low byte; this does not apply the encoder's `1..=254`
|
||||
/// filter. Original raw-text announce names are not parsed by this helper.
|
||||
pub fn parse_announce_app_data(data: &[u8]) -> Option<(Option<String>, Option<u8>)> {
|
||||
let value: rmpv::Value = rmpv::decode::read_value(&mut &data[..]).ok()?;
|
||||
let arr = value.as_array()?;
|
||||
@@ -268,14 +276,14 @@ pub fn parse_announce_app_data(data: &[u8]) -> Option<(Option<String>, Option<u8
|
||||
|
||||
/// Extract just the display name from delivery-announce `app_data`.
|
||||
///
|
||||
/// Python reference: `display_name_from_app_data` — LXMF.py:131-143.
|
||||
/// Uses [`parse_announce_app_data`], including its name sanitization and array-only format.
|
||||
pub fn display_name_from_app_data(data: &[u8]) -> Option<String> {
|
||||
parse_announce_app_data(data).and_then(|(name, _)| name)
|
||||
}
|
||||
|
||||
/// Extract just the stamp cost from delivery-announce `app_data`.
|
||||
///
|
||||
/// Python reference: `stamp_cost_from_app_data` — LXMF.py:145-152.
|
||||
/// Uses [`parse_announce_app_data`], including its unsigned-to-`u8` cast.
|
||||
pub fn stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
|
||||
parse_announce_app_data(data).and_then(|(_, cost)| cost)
|
||||
}
|
||||
@@ -285,7 +293,7 @@ pub fn stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
|
||||
/// Legacy 2-element app_data, malformed data, and missing feature lists are
|
||||
/// treated as unknown. A present feature list is authoritative.
|
||||
///
|
||||
/// Python reference: `compression_support_from_app_data` — LXMF.py:154-164.
|
||||
/// Related Python helper: `compression_support_from_app_data`.
|
||||
pub fn compression_support_state_from_app_data(data: &[u8]) -> CompressionSupport {
|
||||
let Ok(value) = rmpv::decode::read_value(&mut &data[..]) else {
|
||||
return CompressionSupport::Unknown;
|
||||
@@ -312,20 +320,18 @@ pub fn compression_support_state_from_app_data(data: &[u8]) -> CompressionSuppor
|
||||
|
||||
/// Check whether a peer advertises `SF_COMPRESSION` support in its delivery-announce `app_data`.
|
||||
///
|
||||
/// Fail-open like Python: legacy 2-element app_data, malformed data, and
|
||||
/// non-list feature entries all count as supported; only an explicit feature
|
||||
/// list that omits `SF_COMPRESSION` disables compression.
|
||||
///
|
||||
/// Python reference: `compression_support_from_app_data` — LXMF.py:154-164.
|
||||
/// Returns true for Supported or Unknown, including empty/malformed input and
|
||||
/// missing or non-list feature metadata. Only a present feature list without
|
||||
/// `SF_COMPRESSION` returns false. This boolean default differs from Python
|
||||
/// helper cases that return `None` or raise a decode error.
|
||||
pub fn compression_support_from_app_data(data: &[u8]) -> bool {
|
||||
compression_support_state_from_app_data(data) != CompressionSupport::Unsupported
|
||||
}
|
||||
|
||||
/// Extract the advertised name from propagation-node announce data.
|
||||
///
|
||||
/// Reads the [`PN_META_NAME`] metadata entry and decodes it as UTF-8.
|
||||
///
|
||||
/// Python reference: `pn_name_from_app_data` — LXMF.py:172-181.
|
||||
/// Reads binary [`PN_META_NAME`] metadata, decodes UTF-8, then sanitizes and
|
||||
/// bounds the name. Returns `None` if parsing fails or the result is empty.
|
||||
pub fn pn_name_from_app_data(data: &[u8]) -> Option<String> {
|
||||
let parsed = parse_pn_announce_data(data)?;
|
||||
let name_bytes = parsed.metadata.get(&crate::constants::PN_META_NAME)?;
|
||||
@@ -374,21 +380,24 @@ pub enum ControlResult {
|
||||
|
||||
/// Propagation-node request handler.
|
||||
///
|
||||
/// Owns the access-control state and dispatches the three request paths (`/pn/get/stats`,
|
||||
/// `/offer`, `/get`) to [`crate::propagation_node::PropagationNode`]. Python reference:
|
||||
/// LXMRouter.py:650-657.
|
||||
/// Provides handlers for `/pn/get/stats`, `/offer`, `/get`, `/pn/peer/sync` and
|
||||
/// `/pn/peer/unpeer`. The embedder must supply identities already verified by
|
||||
/// the Link; these methods accept identity hashes and do not authenticate them.
|
||||
/// Sync/unpeer handlers authorize a request; the caller performs those actions.
|
||||
pub struct PropagationRequestHandler {
|
||||
pub local_identity_hash: [u8; 16],
|
||||
pub control_allowed: Vec<[u8; 16]>,
|
||||
/// When true, only peers in [`static_peers`](Self::static_peers) may submit offers.
|
||||
/// When true, offers require the supplied remote identity hash to be in
|
||||
/// [`static_peers`](Self::static_peers). This helper uses identity hashes.
|
||||
pub from_static_only: bool,
|
||||
pub static_peers: std::collections::HashSet<[u8; 16]>,
|
||||
/// Throttled peers mapped to their expiry Unix timestamp.
|
||||
/// Supplied remote identity hashes mapped to throttle-expiry Unix timestamps.
|
||||
pub throttled_peers: HashMap<[u8; 16], f64>,
|
||||
}
|
||||
|
||||
impl PropagationRequestHandler {
|
||||
/// Create a handler seeded with the local identity hash, which is always control-allowed.
|
||||
/// Create a handler with the local identity hash in its initial control allowlist.
|
||||
/// The allowlist remains mutable, including removal of that identity.
|
||||
pub fn new(identity_hash: [u8; 16]) -> Self {
|
||||
Self {
|
||||
local_identity_hash: identity_hash,
|
||||
@@ -399,9 +408,9 @@ impl PropagationRequestHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle a `/pn/get/stats` request: validates identity and access, then returns msgpack stats.
|
||||
/// Return MessagePack stats when the supplied verified identity is control-allowed.
|
||||
///
|
||||
/// Python reference: `LXMRouter.stats_get_request` — LXMRouter.py:819-822.
|
||||
/// Related Python handler: `LXMRouter.stats_get_request`.
|
||||
pub fn handle_stats_request(
|
||||
&self,
|
||||
remote_identity_hash: Option<&[u8; 16]>,
|
||||
@@ -423,9 +432,10 @@ impl PropagationRequestHandler {
|
||||
|
||||
/// Handle an `/offer` request from a syncing peer.
|
||||
///
|
||||
/// Validates identity, throttle status, access, and peering key, then delegates to
|
||||
/// [`crate::propagation_node::PropagationNode::handle_offer_request`]. Python reference:
|
||||
/// `LXMRouter.offer_request` — LXMRouter.py:2139-2189.
|
||||
/// Build identity-presence, throttle and static-access context, then delegate
|
||||
/// decoding and peering-key checks to
|
||||
/// [`crate::propagation_node::PropagationNode::handle_offer_request`].
|
||||
/// Supply an already verified remote identity; this helper does not verify it.
|
||||
pub fn handle_offer_request(
|
||||
&self,
|
||||
remote_identity_hash: Option<&[u8; 16]>,
|
||||
@@ -469,7 +479,9 @@ impl PropagationRequestHandler {
|
||||
/// [`GetRequestAction::ServeFiles`](crate::propagation_node::GetRequestAction::ServeFiles)
|
||||
/// plan — the embedder resolves it after releasing the node lock.
|
||||
///
|
||||
/// Python reference: `LXMRouter.message_get_request` — LXMRouter.py:1425-1499.
|
||||
/// The caller must derive `client_dest_hash` from the verified remote identity
|
||||
/// and enforce its access policy. This helper checks only that an identity
|
||||
/// was supplied; it does not bind the two arguments.
|
||||
pub fn handle_message_get_request(
|
||||
&self,
|
||||
remote_identity_hash: Option<&[u8; 16]>,
|
||||
@@ -494,7 +506,7 @@ impl PropagationRequestHandler {
|
||||
/// Handle a `/pn/peer/sync` request. Returns msgpack `true` on success; the caller performs
|
||||
/// the actual sync trigger.
|
||||
///
|
||||
/// Python reference: `LXMRouter.peer_sync_request` — LXMRouter.py:824-834.
|
||||
/// Related Python handler: `LXMRouter.peer_sync_request`.
|
||||
pub fn handle_peer_sync_request(
|
||||
&self,
|
||||
remote_identity_hash: Option<&[u8; 16]>,
|
||||
@@ -527,7 +539,7 @@ impl PropagationRequestHandler {
|
||||
/// Handle a `/pn/peer/unpeer` request. Returns msgpack `true` on success; the caller performs
|
||||
/// the actual peer removal.
|
||||
///
|
||||
/// Python reference: `LXMRouter.peer_unpeer_request` — LXMRouter.py:836-846.
|
||||
/// Related Python handler: `LXMRouter.peer_unpeer_request`.
|
||||
pub fn handle_peer_unpeer_request(
|
||||
&self,
|
||||
remote_identity_hash: Option<&[u8; 16]>,
|
||||
@@ -564,7 +576,7 @@ impl PropagationRequestHandler {
|
||||
|
||||
/// Throttle `peer_hash` for `duration_secs` starting now.
|
||||
///
|
||||
/// Python reference: `LXMRouter.propagation_resource_concluded` — LXMRouter.py:2277-2278.
|
||||
/// Related Python handler: `LXMRouter.propagation_resource_concluded`.
|
||||
pub fn throttle_peer(&mut self, peer_hash: [u8; 16], duration_secs: f64) {
|
||||
let expiry = now_f64() + duration_secs;
|
||||
self.throttled_peers.insert(peer_hash, expiry);
|
||||
|
||||
@@ -62,7 +62,8 @@ impl From<InboundResourceConclusion> for InboundResourceStatus {
|
||||
}
|
||||
}
|
||||
|
||||
/// Owned, non-sensitive snapshot of one inbound transfer.
|
||||
/// Owned snapshot containing link/Resource IDs, sizes, progress and status.
|
||||
/// It contains no transferred payload bytes.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct InboundResourceSnapshot {
|
||||
pub key: InboundResourceKey,
|
||||
@@ -133,10 +134,12 @@ impl InboundResourceHandle {
|
||||
self.snapshot_rx.borrow().clone()
|
||||
}
|
||||
|
||||
/// Wait for the next lifecycle/progress update.
|
||||
/// Wait for an unseen lifecycle/progress state. Intermediate updates may
|
||||
/// be coalesced by the watch channel.
|
||||
///
|
||||
/// Returns `None` after the terminal snapshot has been published and the
|
||||
/// actor owner has dropped its sender.
|
||||
/// Returns `None` once the sender is gone and its latest value has been seen.
|
||||
/// Dropping the tracker can close the channel without publishing a terminal
|
||||
/// state; terminal states require the corresponding lifecycle event.
|
||||
pub async fn changed(&mut self) -> Option<InboundResourceSnapshot> {
|
||||
if self.snapshot_rx.changed().await.is_err() {
|
||||
return None;
|
||||
@@ -166,9 +169,10 @@ struct ActiveInboundResource {
|
||||
|
||||
/// Single-owner active Resource registry.
|
||||
///
|
||||
/// Terminal records are removed immediately, so the registry is bounded by
|
||||
/// concurrent transfers. Previously returned handles retain the final owned
|
||||
/// snapshot without keeping actor state alive.
|
||||
/// Concluded and LinkClosed events remove records immediately. The embedder
|
||||
/// must forward those events to keep the registry limited to active transfers;
|
||||
/// the tracker has no independent entry cap or timeout. Previously returned
|
||||
/// handles retain their latest snapshot without keeping tracker state alive.
|
||||
#[derive(Default)]
|
||||
pub struct InboundResourceTracker {
|
||||
active: HashMap<InboundResourceKey, ActiveInboundResource>,
|
||||
@@ -203,8 +207,8 @@ impl InboundResourceTracker {
|
||||
|
||||
/// Return the active Resource matching `resource_id`.
|
||||
///
|
||||
/// A cryptographic ID collision across two Links fails closed instead of
|
||||
/// choosing the wrong cancellation authority.
|
||||
/// If the same Resource ID is active on more than one Link, returns `None`.
|
||||
/// Use [`Self::inbound_resource_exact`] with the full key to disambiguate.
|
||||
pub fn inbound_resource(&self, resource_id: &[u8; 32]) -> Option<InboundResourceHandle> {
|
||||
let mut matches = self
|
||||
.active
|
||||
@@ -237,7 +241,8 @@ impl InboundResourceTracker {
|
||||
/// Queue cancellation for a stable snapshot of every active Resource.
|
||||
///
|
||||
/// The returned count is the number accepted by the bounded command
|
||||
/// channel, matching Python's count-oriented `cancel_all_inbound` API.
|
||||
/// channel, not the number of completed cancellations. Closure is reported
|
||||
/// by subsequent lifecycle events.
|
||||
pub fn cancel_all_inbound(&self) -> usize {
|
||||
self.inbound_resources()
|
||||
.into_iter()
|
||||
|
||||
@@ -4,20 +4,20 @@
|
||||
//!
|
||||
//! This crate implements the LXMF wire model and is the core LXMF building
|
||||
//! block for `lxmf-tools` (the `lxmd-rs` daemon) and embedding applications.
|
||||
//! Its Reticulum dependency is `rns-transport` from rsReticulum; LXMF sits one
|
||||
//! layer above the Reticulum stack.
|
||||
//! It uses rsReticulum for transport, links, identities and Resources; LXMF
|
||||
//! sits one layer above the Reticulum stack.
|
||||
//!
|
||||
//! # Module map
|
||||
//!
|
||||
//! | Module | What it does |
|
||||
//! | --------------------- | -------------------------------------------------- |
|
||||
//! | [`message`] | Message object: fields, packing, stamp, encryption |
|
||||
//! | [`message`] | Message types, packing, verification and encryption hooks |
|
||||
//! | [`delivery_ratchet`] | Durable delivery-announce ratchet transaction |
|
||||
//! | [`inbound_resource`] | Public inbound Resource tracking/cancellation |
|
||||
//! | [`presentation`] | Safe bounded presentation of untrusted names |
|
||||
//! | [`router`] | Actor-driven routing and delivery state machine |
|
||||
//! | [`router`] | Caller-driven routing and delivery state machine |
|
||||
//! | [`peer`] | Propagation-peer state and sync bookkeeping |
|
||||
//! | [`propagation`] | On-disk store-and-forward message pool |
|
||||
//! | [`propagation`] | In-memory propagation message index and selection |
|
||||
//! | [`propagation_node`] | Propagation-node role logic |
|
||||
//! | [`propagation_client`]| Client side of propagation sync |
|
||||
//! | [`propagation_sync`] | Wire-level peer sync exchange |
|
||||
@@ -25,9 +25,16 @@
|
||||
//! | [`discovery_stamper`] | [`DiscoveryStamper`] impl for on-network discovery |
|
||||
//! | [`sync`] | Shared peer-to-peer sync primitives |
|
||||
//! | [`link_delivery`] | Reticulum-link-based delivery path |
|
||||
//! | [`handlers`] | Callback trait surface for delivery events |
|
||||
//! | [`ticket`] | Small typed identifier for propagation workflows |
|
||||
//! | [`handlers`] | Announce parsing and propagation control handlers |
|
||||
//! | [`ticket`] | Directional tickets for bypassing recipient stamp work |
|
||||
//! | [`persist`] | MessagePack-based on-disk state |
|
||||
//! | [`admission`] | Durable inbox admission and receipt state |
|
||||
//! | [`admission_store`] | Admission-store interface and file-backed adapter |
|
||||
//! | [`propagation_admission`] | Inbound propagation offer and transfer states |
|
||||
//! | [`propagation_offer`] | Propagation-offer evaluation outcomes |
|
||||
//! | [`propagation_send`] | Outbound propagation payload preparation |
|
||||
//! | [`propagation_store_v2`] | Durable propagation store and recovery |
|
||||
//! | [`types`] | Message, destination and identity hash aliases |
|
||||
//! | [`constants`] | Wire constants: STATE, METHOD, field IDs, etc. |
|
||||
//!
|
||||
//! See also `crates/lxmf-tools/` for the `lxmd-rs` binary, and `rsReticulum`
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
//! Link-based LXMF message delivery (Python's Direct delivery mode).
|
||||
//! Caller-driven LXMF delivery over Reticulum Links.
|
||||
//!
|
||||
//! Establishes a link to the recipient, identifies the sender, and transfers the message either
|
||||
//! as a single encrypted link packet or as a Resource over the link. Enables larger-than-MDU
|
||||
//! messages via resource segmentation, delivery confirmation via link-level proofs, and sender
|
||||
//! identity verification via link identification.
|
||||
//! Sends a message as an encrypted Link packet or as segmented Resources and
|
||||
//! tracks Link-level proofs. Reusable Direct Links identify the sender after a
|
||||
//! successful delivery when local identity keys are configured. One-shot packed
|
||||
//! deliveries, used for propagation deposits, identify before sending when those
|
||||
//! keys are available. Link proofs confirm transport receipt, not application
|
||||
//! validation or durable storage at the recipient.
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::fmt;
|
||||
@@ -57,23 +59,21 @@ const LINK_PACKET_DISPATCH_TIMEOUT: Duration = LINK_ENDPOINT_ADMISSION_TIMEOUT_M
|
||||
|
||||
/// Authority-derived first-hop timing for an outbound Link.
|
||||
///
|
||||
/// Python Reticulum computes an initiator's establishment deadline as the
|
||||
/// first-hop timeout plus six seconds for every hop to the destination. The
|
||||
/// first-hop timeout is one full Reticulum MTU at the next-hop interface's
|
||||
/// bitrate, plus the same six-second baseline. When no authoritative bitrate
|
||||
/// is available, Reticulum falls back to the baseline alone.
|
||||
/// The initiator's establishment timeout is the first-hop timeout plus six
|
||||
/// seconds times `max(hops, 1)`. With the canonical 500-byte MTU, first-hop
|
||||
/// serialization time is `500 * 8 / bitrate` seconds plus a six-second baseline,
|
||||
/// as in Python Reticulum. An unknown or zero bitrate uses the baseline alone.
|
||||
///
|
||||
/// Keeping this input independent of interface type is intentional: BLE,
|
||||
/// serial, TCP and every future adapter use the same Link timing rule. It does
|
||||
/// not pause or reset the protocol clock when an interface goes offline.
|
||||
/// This input is independent of interface type. An interface going offline
|
||||
/// does not pause or reset the establishment clock.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct LinkEstablishmentTiming {
|
||||
first_hop_timeout: Duration,
|
||||
}
|
||||
|
||||
impl LinkEstablishmentTiming {
|
||||
/// Construct timing from an already-authoritative Reticulum first-hop
|
||||
/// timeout (for example `ReticulumHandle::first_hop_timeout`).
|
||||
/// Store an authoritative Reticulum first-hop timeout without validation
|
||||
/// (for example, a value from `ReticulumHandle::first_hop_timeout`).
|
||||
pub const fn from_first_hop_timeout(first_hop_timeout: Duration) -> Self {
|
||||
Self { first_hop_timeout }
|
||||
}
|
||||
@@ -84,14 +84,13 @@ impl LinkEstablishmentTiming {
|
||||
Self::from_first_hop_bitrate_and_mtu(bitrate, rns_wire::constants::MTU as u32)
|
||||
}
|
||||
|
||||
/// Derive first-hop timing from the effective next-hop bitrate and an
|
||||
/// already-normalised Reticulum protocol MTU.
|
||||
/// Derive timing as six seconds plus `min(normalised_mtu, 500) * 8 / bitrate`.
|
||||
/// A zero bitrate contributes no serialization time.
|
||||
///
|
||||
/// Callers normally want [`Self::from_first_hop_bitrate`], which uses the
|
||||
/// canonical 500-byte Reticulum MTU exactly like Python Reticulum and the
|
||||
/// trusted rsReticulum runtime. `normalised_mtu` exists for callers that
|
||||
/// already have an authoritative *protocol* MTU. It must never be a BLE
|
||||
/// ATT MTU, an RNode serial chunk size, or a raw hardware-interface MTU.
|
||||
/// Normally use [`Self::from_first_hop_bitrate`] for the canonical 500-byte
|
||||
/// Reticulum MTU used by Python Reticulum and the rsReticulum runtime.
|
||||
/// `normalised_mtu` must be a protocol MTU, not a BLE ATT MTU, RNode serial
|
||||
/// chunk size, or raw hardware-interface MTU.
|
||||
pub fn from_first_hop_bitrate_and_mtu(bitrate: u64, normalised_mtu: u32) -> Self {
|
||||
let serialization_secs = if bitrate == 0 {
|
||||
0.0
|
||||
@@ -360,7 +359,8 @@ pub struct PendingDelivery {
|
||||
pub link: Link,
|
||||
pub state: DeliveryState,
|
||||
pub started_at: Instant,
|
||||
/// Resource transfer, populated after the link establishes.
|
||||
/// Current Resource transfer when the payload requires one; single-packet
|
||||
/// and idle deliveries have no Resource transfer.
|
||||
pub transfer: Option<OutboundTransfer>,
|
||||
/// Sequential Reticulum Resource plan for payloads larger than one
|
||||
/// efficient resource. Segment 1 is stored in `transfer`; later segments
|
||||
@@ -375,8 +375,10 @@ pub struct PendingDelivery {
|
||||
link_request_result: Option<
|
||||
oneshot::Receiver<Result<(), rns_transport::link_messages::LinkRequestDispatchError>>,
|
||||
>,
|
||||
/// Ordinary Link-packet proof window, installed when the packet is
|
||||
/// locally admitted. Resource transfers use their own progress watchdog.
|
||||
/// Current Link-packet admission or proof wait. Exact driver receipts
|
||||
/// replace the staging window with the proof window after admission;
|
||||
/// legacy queued acknowledgements include an admission allowance.
|
||||
/// Resource transfers use their own progress watchdog.
|
||||
pub timeout: Duration,
|
||||
pub msg_hash: Option<[u8; 32]>,
|
||||
pub failure_reason: Option<String>,
|
||||
@@ -390,8 +392,8 @@ pub struct PendingDelivery {
|
||||
/// Keep successful Direct links open for additional messages. Propagation
|
||||
/// deposits currently keep the old one-shot behavior.
|
||||
pub reusable: bool,
|
||||
/// Upstream identifies the initiator after the first successful Direct
|
||||
/// delivery, making the link usable as a peer backchannel.
|
||||
/// Whether local Link identification was staged after a successful Direct
|
||||
/// delivery. Requires configured identity keys; it is not a peer acknowledgement.
|
||||
pub backchannel_identified: bool,
|
||||
queued: VecDeque<QueuedDelivery>,
|
||||
/// Resources arriving in the reverse direction on this initiator-owned
|
||||
@@ -575,7 +577,9 @@ pub struct DirectLinkStartReport {
|
||||
pub in_flight_deliveries: usize,
|
||||
}
|
||||
|
||||
/// A proof-tracked send over an already-authenticated inbound delivery Link.
|
||||
/// Adapter receipt identifying a proof-tracked send over an authenticated
|
||||
/// inbound Link. The embedding runtime must establish that authentication;
|
||||
/// this publicly constructible value is not itself a proof of delivery.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum BackchannelSendReceipt {
|
||||
Packet {
|
||||
@@ -632,9 +636,9 @@ impl fmt::Display for BackchannelSendError {
|
||||
|
||||
impl std::error::Error for BackchannelSendError {}
|
||||
|
||||
/// Whether a link-delivery failure should be treated like upstream LXMF's
|
||||
/// closed/pending Link path, where the message remains eligible for Direct
|
||||
/// rediscovery instead of being terminally failed.
|
||||
/// Classify known local link-delivery failure strings as eligible for Direct
|
||||
/// rediscovery. This matches the intended closed/pending-Link retry policy;
|
||||
/// it is an explicit string whitelist, not a classifier for arbitrary peer errors.
|
||||
pub fn is_retryable_link_delivery_failure(reason: &str) -> bool {
|
||||
// Only concrete local endpoint terminal outcomes, not malformed packet,
|
||||
// role mismatch or arbitrary peer rejection text, trigger rediscovery.
|
||||
@@ -1058,10 +1062,11 @@ impl LinkDeliveryManager {
|
||||
self.backchannel_cancellation_aware = false;
|
||||
}
|
||||
|
||||
/// Install an adapter that fences closed receipt publication and retains
|
||||
/// exact cleanup ownership. New starts close/drain their receipt immediately
|
||||
/// Install an adapter whose caller contract fences closed receipt publication
|
||||
/// and retains exact cleanup ownership. New starts close/drain their receipt
|
||||
/// on user cancellation; existing starts retain their captured policy.
|
||||
/// Legacy adapters must continue using `set_backchannel_sender` instead.
|
||||
/// This setter records that contract without verifying the adapter. Legacy
|
||||
/// adapters must use [`Self::set_backchannel_sender`].
|
||||
pub fn set_cancellation_aware_backchannel_sender(
|
||||
&mut self,
|
||||
tx: mpsc::Sender<BackchannelSendCommand>,
|
||||
@@ -1109,8 +1114,9 @@ impl LinkDeliveryManager {
|
||||
self.inbound_resource_completion_handler = Some(Arc::new(handler));
|
||||
}
|
||||
|
||||
/// Register an inbound authenticated Link as a reusable backchannel for a
|
||||
/// remote LXMF delivery destination.
|
||||
/// Cache a reusable inbound Link for a remote LXMF delivery destination.
|
||||
/// The caller must already have authenticated the Link identity and verified
|
||||
/// its binding to `dest_hash`; this method only records the mapping.
|
||||
pub fn register_backchannel(&mut self, dest_hash: [u8; 16], link_id: [u8; 16]) {
|
||||
self.backchannel_links.insert(dest_hash, link_id);
|
||||
tracing::info!(
|
||||
@@ -1151,8 +1157,9 @@ impl LinkDeliveryManager {
|
||||
result
|
||||
}
|
||||
|
||||
/// Remove cached backchannel state for a closed Link and fail any
|
||||
/// in-flight backchannel sends that were using it.
|
||||
/// Remove a closed Link from the backchannel cache and fail its installed sends.
|
||||
/// Pending starts with an early settlement or cancellation remain until their
|
||||
/// exact receipt can be reconciled; closure does not discard that ownership.
|
||||
pub fn fail_backchannel_link(
|
||||
&mut self,
|
||||
link_id: [u8; 16],
|
||||
@@ -1304,10 +1311,11 @@ impl LinkDeliveryManager {
|
||||
self.start_direct_delivery(message, dest_hash, hops, timing)
|
||||
}
|
||||
|
||||
/// Start a link delivery with an already-packed payload.
|
||||
/// Start a one-shot Link delivery with a caller-supplied packed payload.
|
||||
///
|
||||
/// This is used for LXMF propagation deposits, whose link payload is the
|
||||
/// propagation wrapper rather than the regular signed LXMF representation.
|
||||
/// Propagation deposits use their propagation wrapper here rather than the
|
||||
/// regular signed LXMF representation. This method does not validate that
|
||||
/// wrapper or its correspondence to the supplied message metadata.
|
||||
pub fn start_packed_delivery(
|
||||
&mut self,
|
||||
message: LxMessage,
|
||||
@@ -2044,10 +2052,12 @@ impl LinkDeliveryManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drain inbound transport events and dispatch by packet context.
|
||||
/// Process up to 32 inbound destination events and pending local acknowledgements.
|
||||
///
|
||||
/// Call before [`Self::tick`] each cycle. Routes `LRPROOF`, `ResourceHmu`, `ResourceReq`,
|
||||
/// and `ResourcePrf` contexts to their handlers.
|
||||
/// Call before [`Self::tick`] each cycle and continue polling when more input
|
||||
/// is ready. Routes Link establishment, packets, Resources, proofs and lifecycle
|
||||
/// events. `known_identities` must contain trusted destination-to-public-key
|
||||
/// bindings for establishment-proof validation.
|
||||
pub fn drain_events(&mut self, known_identities: &HashMap<String, [u8; 64]>) {
|
||||
self.poll_link_requests();
|
||||
self.poll_endpoint_control();
|
||||
@@ -2266,8 +2276,9 @@ impl LinkDeliveryManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate an inbound `LRPROOF`, complete the handshake, and transition to
|
||||
/// [`DeliveryState::Identifying`].
|
||||
/// Validate `LRPROOF` and stage endpoint binding and RTT acknowledgement.
|
||||
/// `true` means that plan was accepted. The binding acknowledgement must be
|
||||
/// processed and RTT send staged before entering [`DeliveryState::Identifying`].
|
||||
pub fn handle_link_proof(
|
||||
&mut self,
|
||||
link_id: &[u8; 16],
|
||||
@@ -3688,11 +3699,11 @@ impl LinkDeliveryManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle an inbound `RESOURCE_REQ` (receiver's `request_next`).
|
||||
/// Handle a decrypted, authenticated `RESOURCE_REQ` from the receiver.
|
||||
///
|
||||
/// The request returns a list of parts the receiver still needs; dispatch the resulting
|
||||
/// `SendPart` actions immediately rather than waiting for the next [`Self::tick`], since
|
||||
/// the receiver may time out and retry first.
|
||||
/// This method immediately dispatches the requested parts rather than waiting
|
||||
/// for [`Self::tick`]. Direct callers must authenticate and decrypt the request;
|
||||
/// [`Self::drain_events`] performs that step for routed transport events.
|
||||
pub fn handle_request(&mut self, link_id: &[u8; 16], request_data: &[u8]) {
|
||||
let event = {
|
||||
let Some(delivery) = self.pending.get_mut(link_id) else {
|
||||
@@ -3766,7 +3777,9 @@ impl LinkDeliveryManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply an inbound resource proof; returns `true` when the proof was accepted.
|
||||
/// Validate a Resource proof; `true` means the current segment's proof was
|
||||
/// accepted. A split Resource may then advance to another segment, so this is
|
||||
/// not necessarily whole-message completion.
|
||||
pub fn handle_resource_proof(&mut self, link_id: &[u8; 16], proof_data: &[u8]) -> bool {
|
||||
let mut event = None;
|
||||
let accepted = if let Some(delivery) = self.pending.get_mut(link_id) {
|
||||
@@ -3828,7 +3841,9 @@ impl LinkDeliveryManager {
|
||||
accepted
|
||||
}
|
||||
|
||||
/// Apply an inbound receiver-cancel/reject for the current outbound resource.
|
||||
/// Apply a decrypted, authenticated receiver-cancel body for the current
|
||||
/// outbound Resource. Matches its first 32 bytes against the Resource hash;
|
||||
/// this method does not authenticate raw input. The next tick reports rejection.
|
||||
pub fn handle_resource_reject(&mut self, link_id: &[u8; 16], reject_data: &[u8]) -> bool {
|
||||
if reject_data.len() < 32 {
|
||||
return false;
|
||||
@@ -3912,6 +3927,10 @@ impl LinkDeliveryManager {
|
||||
false
|
||||
}
|
||||
|
||||
/// Record a packet proof already verified by the authenticated Link owner.
|
||||
/// This method accepts only identifiers and performs no cryptographic check.
|
||||
/// Returns a completion result for an installed send. Otherwise, records an
|
||||
/// early observation only when a start is pending on that Link.
|
||||
pub fn handle_backchannel_packet_proof(
|
||||
&mut self,
|
||||
link_id: [u8; 16],
|
||||
@@ -3920,11 +3939,12 @@ impl LinkDeliveryManager {
|
||||
self.complete_backchannel_delivery(BackchannelProofKey::Packet(link_id, packet_hash))
|
||||
}
|
||||
|
||||
/// Mirror the exact bounded packet wait observed by the authenticated Link
|
||||
/// owner. `awaiting_admission` separates local staging from the RTT proof
|
||||
/// window installed after endpoint acceptance. Call before or after its send receipt;
|
||||
/// delayed observations retain the original start instant. Unowned,
|
||||
/// cancelled and completed sends cannot be installed by this method.
|
||||
/// Mirror a packet wait supplied by the authenticated Link owner.
|
||||
/// `awaiting_admission` separates local staging from the RTT proof window
|
||||
/// installed after endpoint acceptance. Call before or after the send receipt;
|
||||
/// delayed observations retain the supplied start instant. Requires an installed
|
||||
/// send or a pending start on that Link; its receipt later confirms the exact hash.
|
||||
/// The caller must supply a valid bounded window; its duration is not clamped.
|
||||
pub fn observe_backchannel_packet_wait(
|
||||
&mut self,
|
||||
link_id: [u8; 16],
|
||||
@@ -3972,14 +3992,14 @@ impl LinkDeliveryManager {
|
||||
)
|
||||
}
|
||||
|
||||
/// Mirror an exact bounded Resource wait from its protocol owner. The
|
||||
/// owner must drive advertisement/window/proof exhaustion and report
|
||||
/// terminal results. Only real protocol progress/retry may update this
|
||||
/// window; keepalives or generic UI progress must not extend it. This
|
||||
/// replaces the finite legacy adapter fallback for this exact send only.
|
||||
/// A bounded 180-second observation grace follows the original deadline to
|
||||
/// tolerate asynchronous accounting delivery; terminal results still settle
|
||||
/// immediately and duplicate observations do not restart that envelope.
|
||||
/// Mirror a Resource wait supplied by its authenticated protocol owner.
|
||||
/// The caller must supply a valid bounded window, drive protocol exhaustion,
|
||||
/// and report terminal results; this method does not clamp the duration.
|
||||
/// Only real protocol progress or retry may update the window, not keepalives
|
||||
/// or generic UI progress. This replaces the legacy fallback for this send.
|
||||
/// A 180-second observation grace follows the supplied deadline. Terminal
|
||||
/// results still settle immediately; repeating an identical observation does
|
||||
/// not restart the window.
|
||||
pub fn observe_backchannel_resource_wait(
|
||||
&mut self,
|
||||
link_id: [u8; 16],
|
||||
@@ -4036,6 +4056,10 @@ impl LinkDeliveryManager {
|
||||
true
|
||||
}
|
||||
|
||||
/// Record a Resource proof already verified by the authenticated Link owner.
|
||||
/// This method accepts only identifiers and performs no cryptographic check.
|
||||
/// Returns a completion result for an installed send. Otherwise, records an
|
||||
/// early observation only when a start is pending on that Link.
|
||||
pub fn handle_backchannel_resource_proof(
|
||||
&mut self,
|
||||
link_id: [u8; 16],
|
||||
@@ -4667,15 +4691,14 @@ impl LinkDeliveryManager {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Return the finite delivery-owner envelope currently owning this message.
|
||||
/// Return the recorded delivery-owner wait for this message, when available.
|
||||
///
|
||||
/// Queued messages have no independent clock. Packet waits start at local
|
||||
/// admission; Resource waits belong to the progress engine, not total
|
||||
/// message age. Observed backchannel bounds preserve the external owner's
|
||||
/// original instant, with a 180-second accounting observation grace for
|
||||
/// externally owned Resources only. Direct Resource and packet protocol
|
||||
/// clocks are unchanged. Legacy adapters without observations retain the
|
||||
/// finite fallback, never an unlimited exemption from an orphan watchdog.
|
||||
/// Messages queued behind another delivery on a reusable Direct Link have no
|
||||
/// independent clock. Packet waits cover local staging and then proof receipt;
|
||||
/// Resource waits belong to the progress engine, not total message age. Backchannel observations preserve the external owner's
|
||||
/// supplied instant and duration, adding 180 seconds of accounting grace only
|
||||
/// for Resources. Without an observation, legacy backchannels use the finite
|
||||
/// fallback. Callers supplying observations are responsible for valid bounds.
|
||||
pub fn message_timeout_window(&self, msg_hash: [u8; 32]) -> Option<(Instant, Duration)> {
|
||||
for delivery in self.pending.values() {
|
||||
if delivery.msg_hash != Some(msg_hash) {
|
||||
|
||||
@@ -450,7 +450,7 @@ impl LxMessage {
|
||||
}
|
||||
/// Update [`auto_compress`](MessageMetadata::auto_compress) based on a peer's cached announce app_data.
|
||||
///
|
||||
/// Matches Python `LXMessage.determine_compression_support` — LXMessage.py:510-513.
|
||||
/// Follows Python `LXMessage.determine_compression_support`.
|
||||
/// Fail-open: no cached app_data and legacy peers without a feature list
|
||||
/// default to compression enabled; only an explicit feature list omitting
|
||||
/// `SF_COMPRESSION` disables it.
|
||||
@@ -460,9 +460,8 @@ impl LxMessage {
|
||||
.unwrap_or(true);
|
||||
}
|
||||
|
||||
/// Register a callback fired when this message transitions to `Delivered`.
|
||||
///
|
||||
/// Python reference: `LXMessage.register_delivery_callback` — LXMessage.py:264-265.
|
||||
/// Set the callback used by [`Self::notify_delivered`] and
|
||||
/// [`Self::mark_delivered`], replacing any previous delivery callback.
|
||||
pub fn register_delivery_callback<F>(&mut self, callback: F)
|
||||
where
|
||||
F: Fn(&LxMessage) + Send + Sync + 'static,
|
||||
@@ -470,9 +469,8 @@ impl LxMessage {
|
||||
self.callbacks.on_delivered = Some(Arc::new(callback));
|
||||
}
|
||||
|
||||
/// Register a callback fired when this message transitions to `Failed`.
|
||||
///
|
||||
/// Python reference: `LXMessage.register_failed_callback` — LXMessage.py:267-268.
|
||||
/// Set the callback used by [`Self::notify_failed`] and
|
||||
/// [`Self::mark_failed`], replacing any previous failure callback.
|
||||
pub fn register_failed_callback<F>(&mut self, callback: F)
|
||||
where
|
||||
F: Fn(&LxMessage) + Send + Sync + 'static,
|
||||
@@ -480,14 +478,16 @@ impl LxMessage {
|
||||
self.callbacks.on_failed = Some(Arc::new(callback));
|
||||
}
|
||||
|
||||
/// Fire the registered delivery callback, if any. Idempotent on repeated calls.
|
||||
/// Invoke the delivery callback, if registered. Every call invokes it again;
|
||||
/// the caller must prevent duplicate notifications when required.
|
||||
pub fn notify_delivered(&self) {
|
||||
if let Some(ref cb) = self.callbacks.on_delivered {
|
||||
cb(self);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fire the registered failure callback, if any. Idempotent on repeated calls.
|
||||
/// Invoke the failure callback, if registered. Every call invokes it again;
|
||||
/// the caller must prevent duplicate notifications when required.
|
||||
pub fn notify_failed(&self) {
|
||||
if let Some(ref cb) = self.callbacks.on_failed {
|
||||
cb(self);
|
||||
@@ -495,7 +495,8 @@ impl LxMessage {
|
||||
}
|
||||
|
||||
/// Decode the first native LXMF file attachment while borrowing its bytes
|
||||
/// from this message. Only the small filename is allocated.
|
||||
/// from this message. The filename is copied into a string; it has no
|
||||
/// separate length limit beyond the enclosing message's decode limits.
|
||||
pub fn first_file_attachment(&self) -> Result<Option<(String, &[u8])>, MessageError> {
|
||||
let Some(field) = self.fields().get(FIELD_FILE_ATTACHMENTS) else {
|
||||
return Ok(None);
|
||||
@@ -515,7 +516,8 @@ impl LxMessage {
|
||||
}
|
||||
|
||||
/// Decode the native LXMF image field while borrowing its image bytes
|
||||
/// from this message. Only the short format string is allocated.
|
||||
/// from this message. The format string is copied; it has no separate
|
||||
/// length limit beyond the enclosing message's decode limits.
|
||||
pub fn image_attachment(&self) -> Result<Option<(String, &[u8])>, MessageError> {
|
||||
let Some(field) = self.fields().get(FIELD_IMAGE) else {
|
||||
return Ok(None);
|
||||
@@ -576,8 +578,10 @@ impl LxMessage {
|
||||
}
|
||||
|
||||
/// Unpack a propagation wrapper `msgpack([timestamp, [lxmf_data, ...]])`, where each entry is
|
||||
/// `dest_hash(16) + encrypted_data + ?propagation_stamp`. The caller must decrypt and then
|
||||
/// call [`Self::unpack`] on the decrypted bytes.
|
||||
/// `dest_hash(16) + encrypted_data + ?propagation_stamp`. The caller removes any
|
||||
/// propagation stamp, decrypts the ciphertext after the destination hash,
|
||||
/// then prepends that destination hash before calling [`Self::unpack`].
|
||||
/// Use a bounded wrapper parser for network ingress.
|
||||
///
|
||||
/// Python reference: `LXMRouter.lxmf_propagation` / `propagation_resource_concluded`.
|
||||
pub fn unpack_propagation_wrapper(data: &[u8]) -> Result<(f64, Vec<Vec<u8>>), MessageError> {
|
||||
@@ -586,9 +590,9 @@ impl LxMessage {
|
||||
Ok(wrapper)
|
||||
}
|
||||
|
||||
/// Smallest possible valid propagation entry: anything at or below
|
||||
/// `LXMF_OVERHEAD + STAMP_SIZE` cannot carry a message (Python
|
||||
/// `LXStamper.validate_pn_stamp` rejects it before building a workblock).
|
||||
/// Minimum entry length accepted by the bounded propagation-wrapper parser.
|
||||
/// Matches Python `LXStamper.validate_pn_stamp`'s rejection of entries at or
|
||||
/// below `LXMF_OVERHEAD + STAMP_SIZE` before workblock construction.
|
||||
pub const MIN_PROPAGATION_ENTRY_SIZE: usize =
|
||||
crate::constants::LXMF_OVERHEAD + crate::constants::STAMP_SIZE + 1;
|
||||
|
||||
@@ -662,8 +666,7 @@ impl LxMessage {
|
||||
|
||||
/// Mark transmission as in progress.
|
||||
///
|
||||
/// Python reference: LXMessage.py:479, 499 — DIRECT and PROPAGATED messages enter SENDING
|
||||
/// when transmission begins.
|
||||
/// Sets the local state to [`MessageState::Sending`]; performs no network I/O.
|
||||
pub fn mark_sending(&mut self) {
|
||||
self.state = MessageState::Sending;
|
||||
}
|
||||
@@ -678,7 +681,8 @@ impl LxMessage {
|
||||
/// before emitting paper/QR content. The caller supplies that identity encryption closure,
|
||||
/// keeping this crate independent from any concrete identity store.
|
||||
///
|
||||
/// Python reference: LXMessage.py:443-455 and LXMessage.py:687-705.
|
||||
/// Requires [`DeliveryMethod::Paper`] and a destination-plus-ciphertext
|
||||
/// payload no larger than [`PAPER_MDU`].
|
||||
pub fn to_paper_uri<F>(&self, encrypt_fn: F) -> Result<String, MessageError>
|
||||
where
|
||||
F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>,
|
||||
@@ -727,10 +731,11 @@ impl LxMessage {
|
||||
Ok((destination_hash, bytes[DESTINATION_LENGTH..].to_vec()))
|
||||
}
|
||||
|
||||
/// Decode an upstream-compatible encrypted `lxm://` paper URI.
|
||||
/// Decode an encrypted `lxm://` paper URI.
|
||||
///
|
||||
/// The caller supplies the local destination identity decryption closure. On success the
|
||||
/// decrypted wire message is unpacked exactly like Python's `ingest_lxm_uri` path.
|
||||
/// The caller supplies destination-identity decryption. This method restores
|
||||
/// the destination prefix, parses the message, and marks its representation
|
||||
/// as Paper. Authenticate the sender separately with [`Self::verify`].
|
||||
pub fn from_paper_uri<F>(uri: &str, decrypt_fn: F) -> Result<Self, MessageError>
|
||||
where
|
||||
F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>,
|
||||
@@ -746,7 +751,7 @@ impl LxMessage {
|
||||
Ok(message)
|
||||
}
|
||||
|
||||
/// Alias for [`Self::to_paper_uri`]; returns `None` if packing or encryption fails.
|
||||
/// Alias for [`Self::to_paper_uri`]; returns `None` on any error.
|
||||
pub fn as_uri<F>(&self, encrypt_fn: F) -> Option<String>
|
||||
where
|
||||
F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>,
|
||||
@@ -754,7 +759,7 @@ impl LxMessage {
|
||||
self.to_paper_uri(encrypt_fn).ok()
|
||||
}
|
||||
|
||||
/// Alias for [`Self::from_paper_uri`]. Python reference: LXMessage.py:685-731.
|
||||
/// Alias for [`Self::from_paper_uri`].
|
||||
pub fn from_uri<F>(uri: &str, decrypt_fn: F) -> Result<Self, MessageError>
|
||||
where
|
||||
F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>,
|
||||
@@ -764,8 +769,11 @@ impl LxMessage {
|
||||
|
||||
/// Pack the message into a container for file storage.
|
||||
///
|
||||
/// Layout is a msgpack map `{state: u8, lxmf_bytes: bin, transport_encrypted: bool,
|
||||
/// transport_encryption: str?, method: u8}`.
|
||||
/// Writes a five-element MessagePack array in this order:
|
||||
/// `[state, lxmf_bytes, transport_encrypted, transport_encryption, method]`.
|
||||
/// `lxmf_bytes` is binary and `transport_encryption` is a string or nil.
|
||||
/// Python's `packed_container` writes a named-field map; its file reader
|
||||
/// does not accept this Rust array layout.
|
||||
pub fn pack_container(&self) -> Result<Vec<u8>, MessageError> {
|
||||
let container = MessageContainerRef {
|
||||
state: self.state as u8,
|
||||
@@ -777,7 +785,8 @@ impl LxMessage {
|
||||
rmp_serde::to_vec(&container).map_err(|e| MessageError::PackFailed(e.to_string()))
|
||||
}
|
||||
|
||||
/// Unpack a message from a container (Python parity: `unpack_from_file` in LXMessage.py).
|
||||
/// Decode a container array or a map with matching field names, then parse
|
||||
/// its LXMF wire image. This does not verify the sender's signature.
|
||||
pub fn unpack_container(data: &[u8]) -> Result<Self, MessageError> {
|
||||
if data.len() > MessageDecodeLimits::default().max_wire_bytes + 65_536 {
|
||||
return Err(MessageError::UnpackFailed(
|
||||
@@ -818,12 +827,10 @@ impl LxMessage {
|
||||
|
||||
/// Write the message to `directory_path`, named by the message hash.
|
||||
///
|
||||
/// Writes are atomic (unique tmp file + fsync + rename) so concurrent
|
||||
/// readers never observe a partial file — Python `write_to_directory`,
|
||||
/// LXMessage.py:674-696 (1.0.1). Python additionally serializes the write
|
||||
/// under a per-message persist lock; in Rust concurrent persists of one
|
||||
/// message are already exclusive-borrow serialized or hit unique tmp
|
||||
/// files, with the rename as the atomic last-writer-wins step.
|
||||
/// Writes [`Self::pack_container`] through the platform durability boundary
|
||||
/// in [`crate::persist::write_file_atomic`]. Publication errors, including
|
||||
/// uncertain commits, propagate to the caller. The message type does not
|
||||
/// serialize concurrent calls; callers needing write ordering must provide it.
|
||||
pub fn write_to_directory(&self, directory_path: &str) -> Result<String, MessageError> {
|
||||
let hash = self.message_id();
|
||||
let file_name = rns_crypto::hex_encode(&hash);
|
||||
@@ -836,7 +843,8 @@ impl LxMessage {
|
||||
Ok(file_path)
|
||||
}
|
||||
|
||||
/// Read a message from a container file (Python parity: `unpack_from_file`).
|
||||
/// Read a bounded container file. A 64-character hexadecimal filename must
|
||||
/// match the parsed message ID. Sender authentication remains a separate step.
|
||||
pub fn read_from_file(file_path: &str) -> Result<Self, MessageError> {
|
||||
use std::io::Read;
|
||||
let file = std::fs::File::open(file_path)
|
||||
|
||||
@@ -326,8 +326,9 @@ impl SignedLxMessage {
|
||||
stamp_cost,
|
||||
}
|
||||
}
|
||||
/// Store this message so its delivery can resume after a restart, under
|
||||
/// the same id. The stored form keeps the signing stamp cost as a floor.
|
||||
/// Create a representation the caller can persist to resume delivery after
|
||||
/// a restart under the same ID. It retains the signing stamp cost as a floor;
|
||||
/// this method performs no file or database write.
|
||||
pub fn to_resumable(&self) -> ResumableLxMessage {
|
||||
ResumableLxMessage::new(&self.message.wire, self.stamp_cost)
|
||||
}
|
||||
@@ -373,6 +374,8 @@ impl SignedLxMessage {
|
||||
self.outbound_ticket
|
||||
}
|
||||
/// Compute the optional recipient stamp without changing the signed body.
|
||||
/// Runs synchronously; proof of work uses [`crate::stamper::generate_stamp`]
|
||||
/// and its attempt budget.
|
||||
pub fn generate_recipient_stamp(&self) -> Result<Option<RecipientStamp>, MessageError> {
|
||||
if let Some(ticket) = self.outbound_ticket {
|
||||
let mut material = [0u8; 48];
|
||||
|
||||
@@ -164,11 +164,12 @@ pub struct LxmPeer {
|
||||
pub stamp_cost_flexibility: Option<u8>,
|
||||
/// Peering cost used for outbound peering-key generation.
|
||||
pub peering_cost: u8,
|
||||
/// Generated peering key `(stamp, value)`. `None` until [`LxmPeer::generate_peering_key`] succeeds.
|
||||
/// Cached peering stamp and work value, generated or restored from storage.
|
||||
/// Use [`Self::peering_key_ready`] to check it against the current cost.
|
||||
pub peering_key: Option<([u8; 32], u32)>,
|
||||
/// Per-transfer propagation limit in KB.
|
||||
/// Per-transfer propagation limit in decimal kilobytes (1 kB = 1000 bytes).
|
||||
pub propagation_transfer_limit: Option<f64>,
|
||||
/// Per-sync propagation limit in KB.
|
||||
/// Per-sync propagation limit in decimal kilobytes (1 kB = 1000 bytes).
|
||||
pub propagation_sync_limit: Option<f64>,
|
||||
pub currently_transferring_messages: Option<Vec<PropagationTransientId>>,
|
||||
pub link_alive: bool,
|
||||
@@ -290,10 +291,13 @@ impl LxmPeer {
|
||||
peer
|
||||
}
|
||||
|
||||
/// Refresh announce-derived policy only when `timebase` is newer.
|
||||
/// Refresh policy when the supplied `timebase` is newer. The caller must
|
||||
/// keep both supplied and stored timebases finite; this method does not
|
||||
/// validate them, and NaN bypasses the ordering guard.
|
||||
///
|
||||
/// Returns `true` when the peer was updated. Runtime counters, handled
|
||||
/// messages and static-peer status remain owned by the existing peer.
|
||||
/// Returns `true` when updated. Handled messages and static-peer status are
|
||||
/// retained. Calling `heard()` updates liveness/last-heard and resets the
|
||||
/// unreachable count and sync backoff; the next sync attempt is reset to zero.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn refresh_from_announce(
|
||||
&mut self,
|
||||
@@ -316,7 +320,9 @@ impl LxmPeer {
|
||||
)
|
||||
}
|
||||
|
||||
/// Refresh announce-derived policy and bounded metadata only when newer.
|
||||
/// Refresh policy and bounded metadata with the ordering and liveness
|
||||
/// behavior of [`Self::refresh_from_announce`]. Both supplied and stored
|
||||
/// timebases must be finite; this method does not reject NaN.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn refresh_from_announce_with_metadata(
|
||||
&mut self,
|
||||
@@ -548,13 +554,15 @@ impl LxmPeer {
|
||||
self.sync_backoff
|
||||
}
|
||||
|
||||
/// Peers unseen for [`PEER_STALE_TIME`] are stale and should be rotated to the back of the queue.
|
||||
/// Whether more than [`PEER_STALE_TIME`] seconds have elapsed since last heard.
|
||||
/// This check does not rotate or remove the peer.
|
||||
pub fn is_stale(&self) -> bool {
|
||||
let now = now_f64();
|
||||
now - self.last_heard > PEER_STALE_TIME as f64
|
||||
}
|
||||
|
||||
/// Whether the peering key has been generated and meets [`Self::peering_cost`].
|
||||
/// Whether a cached key's recorded work value meets [`Self::peering_cost`].
|
||||
/// This trusts the stored/public value; it does not revalidate the key.
|
||||
pub fn peering_key_ready(&self) -> bool {
|
||||
if let Some((_, value)) = self.peering_key {
|
||||
value >= self.peering_cost as u32
|
||||
@@ -563,7 +571,8 @@ impl LxmPeer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Peering-key value (leading zero bits), if generated.
|
||||
/// Cached peering-key work value (leading zero bits), if present.
|
||||
/// Restored or caller-supplied values are returned without recomputation.
|
||||
pub fn peering_key_value(&self) -> Option<u32> {
|
||||
self.peering_key.map(|(_, value)| value)
|
||||
}
|
||||
@@ -573,7 +582,12 @@ impl LxmPeer {
|
||||
/// Key material is `peer_identity_hash || our_identity_hash` (16 + 16 bytes), run through the
|
||||
/// stamp PoW system with [`STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING`] expand rounds.
|
||||
///
|
||||
/// Python reference: `LXMPeer.generate_peering_key` — LXMPeer.py:242-265.
|
||||
/// Returns immediately when a key is already cached; it does not revalidate
|
||||
/// that key against a changed cost. Use [`Self::peering_key_ready`] for that
|
||||
/// check. Otherwise runs synchronous proof of work with
|
||||
/// [`crate::stamper::generate_stamp`]'s attempt budget.
|
||||
///
|
||||
/// Python reference: `LXMPeer.generate_peering_key`.
|
||||
pub fn generate_peering_key(
|
||||
&mut self,
|
||||
peer_identity_hash: &[u8; 16],
|
||||
@@ -625,7 +639,7 @@ impl LxmPeer {
|
||||
/// `next_sync_attempt` so sync can proceed immediately, updates `last_heard`, and marks the
|
||||
/// peer alive.
|
||||
///
|
||||
/// Python reference: LXMPeer.py:530-538.
|
||||
/// This updates local peer state; it does not identify the link or start a sync.
|
||||
pub fn link_established(&mut self, _link_id: [u8; 16], establishment_rate: Option<f64>) {
|
||||
if let Some(rate) = establishment_rate {
|
||||
self.link_establishment_rate = rate;
|
||||
@@ -637,12 +651,10 @@ impl LxmPeer {
|
||||
self.link_alive = true;
|
||||
}
|
||||
|
||||
/// Link-closed callback: clears the link and transitions to [`PeerState::Idle`].
|
||||
/// Clear the link-alive flag and transition to [`PeerState::Idle`].
|
||||
///
|
||||
/// If the peer was mid-sync, the in-flight transfer list is cleared so backoff logic
|
||||
/// treats it as a sync failure.
|
||||
///
|
||||
/// Python reference: LXMPeer.py:540-542.
|
||||
/// If the previous state was active, clear the in-flight transfer list.
|
||||
/// This callback does not itself increment backoff or mark the peer unreachable.
|
||||
pub fn link_closed(&mut self) {
|
||||
let was_active = self.state != PeerState::Idle;
|
||||
self.link_alive = false;
|
||||
@@ -694,11 +706,13 @@ impl From<&LxmPeer> for OutboundOfferPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
/// Select the best peer to sync with from a set of candidates.
|
||||
/// Return the input index of an idle peer with unhandled messages.
|
||||
///
|
||||
/// Mirrors Python `sync_peers()`: draw from the fastest [`FASTEST_N_RANDOM_POOL`] alive peers,
|
||||
/// mix in unknown-speed peers, and fall back to unresponsive peers that have passed their sync
|
||||
/// backoff.
|
||||
/// Alive peers take priority: sort them by descending transfer rate and choose
|
||||
/// the first. This selection is deterministic; adding unknown-speed peers to
|
||||
/// the candidate pool does not randomize the choice as Python `sync_peers()` does.
|
||||
/// If no alive peer qualifies, choose the first unresponsive peer whose backoff
|
||||
/// has elapsed. Backoff is not checked in the alive-peer branch.
|
||||
pub fn select_sync_peer(peers: &[&LxmPeer]) -> Option<usize> {
|
||||
if peers.is_empty() {
|
||||
return None;
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
//! Persistent router state — matches Python `<storagepath>/lxmf/` layout.
|
||||
//! Router state files in a caller-supplied directory.
|
||||
//!
|
||||
//! Files:
|
||||
//! * `outbound_stamp_costs` — `HashMap<dest_hash, StampCostEntry>`
|
||||
//! * `outbound_stamp_costs` — destination stamp costs and observation times
|
||||
//! * `available_tickets` — versioned directional ticket state
|
||||
//! * `local_deliveries` — `HashMap<transient_id, timestamp>`
|
||||
//! * `locally_processed` — `HashMap<transient_id, timestamp>`
|
||||
//! * `local_deliveries` — delivered transient IDs and timestamps
|
||||
//! * `locally_processed` — processed transient IDs and timestamps
|
||||
//! * `node_stats` — propagation-node counters
|
||||
//! * `propagation_suppression_v1` — bounded download suppression records
|
||||
//! * `propagation_node_policies_v1` — recorded propagation-node policies
|
||||
//!
|
||||
//! All four files are MessagePack-encoded via `rmp-serde`. Missing files are
|
||||
//! treated as "no prior state" and do not raise errors — a fresh daemon is a
|
||||
//! valid state.
|
||||
//! These files use the Rust types' MessagePack representations; matching Python
|
||||
//! filenames does not establish interchangeable contents. Missing files yield
|
||||
//! empty/default state. Other I/O, malformed-data and capacity errors propagate
|
||||
//! to the caller.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
|
||||
@@ -7,9 +7,11 @@ pub const MAX_ADVERTISED_NAME_CHARS: usize = 128;
|
||||
|
||||
/// Normalize and bound an untrusted display name.
|
||||
///
|
||||
/// The result is NFKC-normalized, contains no control or presentation-control
|
||||
/// codepoints, collapses all Unicode whitespace to one ASCII space, and is
|
||||
/// truncated by Unicode scalar values rather than UTF-8 bytes.
|
||||
/// Applies NFKC normalization and filters control characters, bidi controls,
|
||||
/// private-use characters, selected zero-width characters, variation selectors,
|
||||
/// and broad emoji/symbol ranges. Tabs and newlines are removed. Remaining
|
||||
/// whitespace collapses to one ASCII space, with no leading or trailing space.
|
||||
/// The length limit counts Unicode scalar values, not UTF-8 bytes.
|
||||
pub fn sanitize_name(input: &str, max_chars: usize) -> String {
|
||||
let mut output = sanitize_name_pass(input, max_chars);
|
||||
let rounds = output.nfkd().count().saturating_add(2);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Store-and-forward message storage for LXMF propagation nodes.
|
||||
//! In-memory propagation-entry accounting, deduplication caches and distribution queue.
|
||||
//!
|
||||
//! Mirrors propagation entry management in Python LXMRouter.py.
|
||||
//! The owning router or node handles durable files and admission. Weight-based
|
||||
//! culling uses the formula from Python `LXMRouter.get_weight`.
|
||||
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
@@ -17,7 +18,7 @@ pub struct PropagationEntry {
|
||||
pub stamp_value: u8,
|
||||
pub size: usize,
|
||||
pub collected: bool,
|
||||
/// Stored file contains `lxmf_data || propagation_stamp`.
|
||||
/// When true, the stored file contains `lxmf_data || propagation_stamp`.
|
||||
///
|
||||
/// Client download strips the stamp; peer sync keeps it.
|
||||
pub stamped: bool,
|
||||
@@ -73,7 +74,11 @@ impl PropagationEntry {
|
||||
|
||||
/// Accepts canonical 64-hex transient IDs in both the 3-component format
|
||||
/// and the older 2-component `{transient_id}_{timestamp}` form (stamp_value
|
||||
/// defaults to 0). Pre-fix 32-hex transient IDs are rejected.
|
||||
/// defaults to 0). Shortened 32-hex transient IDs are rejected.
|
||||
///
|
||||
/// # Panics
|
||||
/// Non-ASCII input can panic when sliced at hexadecimal byte-pair offsets.
|
||||
/// Validate that untrusted filenames are ASCII before calling.
|
||||
pub fn parse_filename(filename: &str) -> Option<(PropagationTransientId, f64, u8)> {
|
||||
let parts: Vec<&str> = filename.split('_').collect();
|
||||
match parts.len() {
|
||||
@@ -93,7 +98,8 @@ impl PropagationEntry {
|
||||
}
|
||||
}
|
||||
|
||||
/// Owned by the router actor; no shared access.
|
||||
/// In-memory index and accounting state. Mutations require exclusive access;
|
||||
/// the owner handles synchronization, durable storage and admission policy.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct PropagationStore {
|
||||
entries: HashMap<PropagationTransientId, PropagationEntry>,
|
||||
@@ -106,7 +112,8 @@ pub struct PropagationStore {
|
||||
/// Prioritised destinations receive a 0.1x weight multiplier during culling.
|
||||
prioritised_destinations: HashSet<[u8; 16]>,
|
||||
peer_distribution_queue: VecDeque<(PropagationTransientId, Option<[u8; 16]>)>,
|
||||
/// `None` disables the byte-size cap.
|
||||
/// Optional byte-limit setting. This type does not enforce it automatically;
|
||||
/// the owner must call culling with its chosen limit.
|
||||
pub storage_limit: Option<usize>,
|
||||
}
|
||||
|
||||
@@ -116,6 +123,10 @@ impl PropagationStore {
|
||||
}
|
||||
|
||||
/// Returns `false` if the destination is in the ignored list.
|
||||
///
|
||||
/// The caller must exclude an existing transient ID before inserting.
|
||||
/// Replacing one adds the new size without subtracting the previous size.
|
||||
/// This method performs no persistence, stamp validation or size-limit check.
|
||||
pub fn insert(&mut self, entry: PropagationEntry) -> bool {
|
||||
if self.ignored_destinations.contains(&entry.destination_hash) {
|
||||
return false;
|
||||
@@ -178,11 +189,12 @@ impl PropagationStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// Cull messages by weighted score until total size is within `limit_bytes`.
|
||||
/// Remove indexed entries by weighted score until accounted size is within
|
||||
/// `limit_bytes`, assuming each transient ID was inserted only once.
|
||||
///
|
||||
/// Score = priority_weight * age_weight * size. Evicts highest-weight first
|
||||
/// (oldest + largest + non-prioritised). Matches Python
|
||||
/// `clean_message_store()` in LXMRouter.py.
|
||||
/// Score = priority_weight * age_weight * size. Highest scores go first,
|
||||
/// using Python `LXMRouter.get_weight`'s formula. This updates the in-memory
|
||||
/// index and byte count; it does not delete message files.
|
||||
pub fn cull_by_weight(&mut self, limit_bytes: usize) {
|
||||
if self.total_size <= limit_bytes {
|
||||
return;
|
||||
@@ -299,7 +311,7 @@ impl PropagationStore {
|
||||
}
|
||||
|
||||
/// Age out dedup-cache entries older than `MESSAGE_EXPIRY * 6` (Python
|
||||
/// `LXMRouter.clean_transient_id_caches`, LXMRouter.py:956). Retention is
|
||||
/// `LXMRouter.clean_transient_id_caches`). Retention is
|
||||
/// purely age-based: entries must outlive their store membership so a
|
||||
/// culled-and-reoffered message is still recognised as already handled.
|
||||
pub fn clean_transient_caches(&mut self, now: f64) {
|
||||
|
||||
@@ -23,9 +23,9 @@ use crate::constants::PN_STAMP_THROTTLE;
|
||||
|
||||
const PROPAGATION_DESTINATION_NAME: &str = "lxmf.propagation";
|
||||
|
||||
/// Default maximum number of concurrently transferring or validating syncs.
|
||||
/// Default active-sync threshold used when admitting new offers.
|
||||
pub const PN_DEFAULT_MAX_INBOUND_SYNCS: usize = 3;
|
||||
/// Smallest accepted configured inbound-sync limit.
|
||||
/// Lower bound applied to the configured inbound-sync threshold.
|
||||
pub const PN_MIN_MAX_INBOUND_SYNCS: usize = 1;
|
||||
/// Duration applied after a known peer submits an invalid-stamp batch.
|
||||
pub const PN_INVALID_STAMP_THROTTLE: Duration = Duration::from_secs(PN_STAMP_THROTTLE);
|
||||
@@ -40,7 +40,9 @@ pub struct PnInboundAdmissionConfig {
|
||||
/// The LXMF default is `false`, so a configured static peer bypasses both
|
||||
/// admission gates.
|
||||
pub static_sequential: bool,
|
||||
/// Maximum concurrent Resources in `Transferring` or `Validating` state.
|
||||
/// Reject new non-bypassing offers when this many records are Transferring
|
||||
/// or Validating. Values below one are clamped to one. Accepted offers do
|
||||
/// not reserve slots, and starting them does not recheck this threshold.
|
||||
pub max_inbound_syncs: usize,
|
||||
/// Accept propagation offers only from configured static peers.
|
||||
pub from_static_only: bool,
|
||||
@@ -286,7 +288,8 @@ impl PnInboundAdmission {
|
||||
///
|
||||
/// A successful preflight creates no admission record. The returned
|
||||
/// candidate binds the link and peer values that the caller must use for
|
||||
/// external key validation.
|
||||
/// external key validation. The caller must supply the remote identity
|
||||
/// verified on that Link; this coordinator receives hashes, not identity proofs.
|
||||
pub fn preflight_offer(
|
||||
&mut self,
|
||||
link_id: [u8; 16],
|
||||
@@ -461,6 +464,7 @@ impl PnInboundAdmission {
|
||||
}
|
||||
|
||||
/// Transition an accepted offer when its inbound Resource starts.
|
||||
/// This checks the previous state but does not rerun offer admission gates.
|
||||
pub fn resource_started(&mut self, link_id: &[u8; 16]) -> Result<(), PnTransitionError> {
|
||||
self.transition(
|
||||
link_id,
|
||||
@@ -480,7 +484,7 @@ impl PnInboundAdmission {
|
||||
)
|
||||
}
|
||||
|
||||
/// Conclude stamp validation and release all active accounting.
|
||||
/// Conclude stamp validation and release this link's active accounting.
|
||||
///
|
||||
/// Only [`PnValidationResult::InvalidStamp`] installs a throttle, and a
|
||||
/// throttle is possible only for a known peer retained in a valid record.
|
||||
|
||||
@@ -1,16 +1,24 @@
|
||||
//! Client-side propagation node download protocol.
|
||||
//! Client-side propagation node downloads, driven by the caller through
|
||||
//! [`PropagationClient::drain_events`] and [`PropagationClient::tick`].
|
||||
//!
|
||||
//! Python reference: LXMRouter.py:484-587.
|
||||
//! The `/get` wire exchange corresponds to Python
|
||||
//! `LXMRouter.request_messages_from_propagation_node()`.
|
||||
//!
|
||||
//! Protocol flow:
|
||||
//! 1. Establish link to the propagation node destination.
|
||||
//! 2. Identify on the link (LinkIdentify).
|
||||
//! 3. Request `/get` with `[None, None]` -- server returns available transient IDs.
|
||||
//! 4. Client sorts into wants/haves.
|
||||
//! 5. Purge known haves, then request bounded wants chunks with a per-transfer limit.
|
||||
//! 6. Server returns `[lxmf_data_1, lxmf_data_2, ...]`.
|
||||
//! 7. Client processes received messages.
|
||||
//! 8. `/get` with `[None, received_ids]` purges each downloaded batch before the next chunk.
|
||||
//! 1. Establish a Link and identify with the configured public/signing key pair.
|
||||
//! Without that pair, no identification is sent; an authenticating node rejects the request.
|
||||
//! 2. Request `/get` with `[None, None]` to list available transient IDs.
|
||||
//! 3. Separate caller-installed durable haves from eligible wants. Purge those
|
||||
//! haves unless retention is enabled, then request bounded wants chunks.
|
||||
//! 4. Validate the returned ciphertext IDs, membership, count and byte budget.
|
||||
//! Pass downloaded payloads and admission tokens to the application's durable adapter.
|
||||
//! 5. Await local admission decisions. Only accepted durable receipts authorize
|
||||
//! purging newly downloaded IDs; rejected items remain available for retry.
|
||||
//! 6. Purge accepted IDs before requesting the next chunk. The retention option
|
||||
//! applies to previously known haves, not these newly accepted downloads.
|
||||
//!
|
||||
//! Suppression records delay new wants but never authorize remote deletion.
|
||||
//! Persist suppression changes and acknowledge their current revision before
|
||||
//! further wants can proceed.
|
||||
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::sync::{
|
||||
@@ -57,9 +65,9 @@ pub enum PropagationClientState {
|
||||
Receiving,
|
||||
/// `/get` with `[None, received_ids]` sent.
|
||||
PurgeRequested,
|
||||
/// Download bytes await a durable local application decision.
|
||||
/// Waiting for local admission decisions or a durable suppression checkpoint.
|
||||
AwaitingAdmission,
|
||||
/// At least one item was retained remotely for retry/revalidation.
|
||||
/// At least one downloaded item lacked durable local acceptance in this cycle.
|
||||
Partial,
|
||||
Complete,
|
||||
Failed,
|
||||
@@ -333,21 +341,31 @@ impl PropagationClient {
|
||||
self.outbound_propagation_node = Some(dest_hash);
|
||||
}
|
||||
|
||||
/// KB per transfer.
|
||||
/// Set the requested server response budget in decimal kB (1000 bytes).
|
||||
/// The value is sent unchanged in `/get`; supply a finite positive number.
|
||||
/// Local Resource and admission byte limits still apply independently.
|
||||
pub fn set_delivery_limit(&mut self, limit_kb: f64) {
|
||||
self.delivery_limit = Some(limit_kb);
|
||||
}
|
||||
|
||||
/// Trust this ID as a durable local have, with no expiry. It may authorize
|
||||
/// remote purge on the next download cycle unless retention is enabled.
|
||||
/// The caller must establish the durable local effect; this method does not verify it.
|
||||
pub fn add_local_message(&mut self, transient_id: PropagationTransientId) {
|
||||
self.local_message_expiry.remove(transient_id.as_slice());
|
||||
self.local_messages.insert(transient_id.to_vec());
|
||||
}
|
||||
|
||||
/// Trust a caller-supplied transient ID as a durable local have with no expiry.
|
||||
/// This has the same purge authority as [`Self::add_local_message`]; it does
|
||||
/// not check the ID length or verify a durable local effect.
|
||||
pub fn add_local_message_id(&mut self, transient_id: Vec<u8>) {
|
||||
self.local_message_expiry.remove(&transient_id);
|
||||
self.local_messages.insert(transient_id);
|
||||
}
|
||||
|
||||
/// Replace all local haves and clear their expiry times. Every supplied ID
|
||||
/// is trusted as durable purge authority; lengths and local effects are not checked.
|
||||
pub fn replace_local_message_ids<I>(&mut self, transient_ids: I)
|
||||
where
|
||||
I: IntoIterator<Item = Vec<u8>>,
|
||||
@@ -356,6 +374,9 @@ impl PropagationClient {
|
||||
self.local_message_expiry.clear();
|
||||
}
|
||||
|
||||
/// Replace local purge authority from the durable adapter, preserving expiry
|
||||
/// times and pruning expired haves. This trusts the supplied records; it does
|
||||
/// not revalidate stored files or commit new local effects.
|
||||
pub fn replace_durable_haves(
|
||||
&mut self,
|
||||
haves: impl IntoIterator<Item = crate::admission::DurableHave>,
|
||||
@@ -398,6 +419,9 @@ impl PropagationClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep previously known local haves on the node during subsequent selection.
|
||||
/// Newly downloaded messages accepted through admission are still purged;
|
||||
/// this flag does not provide retention for those messages.
|
||||
pub fn set_retain_synced_on_node(&mut self, retain: bool) {
|
||||
self.retain_synced_on_node = retain;
|
||||
}
|
||||
@@ -477,7 +501,9 @@ impl PropagationClient {
|
||||
pub fn suppression_revision(&self) -> u64 {
|
||||
self.suppression_revision
|
||||
}
|
||||
/// A slow checkpoint must never reinstall an older ledger over new state.
|
||||
/// Acknowledge a completed durable checkpoint only if its revision is still
|
||||
/// current. Returns `false` after intervening changes; otherwise clears the
|
||||
/// dirty/failure flags without replacing the ledger. The caller performs the write.
|
||||
pub fn acknowledge_suppression_persistence(&mut self, revision: u64) -> bool {
|
||||
if revision != self.suppression_revision {
|
||||
return false;
|
||||
@@ -493,8 +519,9 @@ impl PropagationClient {
|
||||
pub fn take_suppression_updates(&mut self) -> Vec<SuppressionRecord> {
|
||||
std::mem::take(&mut self.suppression_updates)
|
||||
}
|
||||
/// The adapter must report a failed durable suppression update. Automatic
|
||||
/// new wants pause until persisted state is installed after recovery.
|
||||
/// Report a failed durable suppression update and pause new wants. Resume
|
||||
/// after durably checkpointing and acknowledging the current revision, or
|
||||
/// installing persisted state after recovery.
|
||||
pub fn suppression_persistence_failed(&mut self) {
|
||||
self.suppression_persist_failed = true;
|
||||
}
|
||||
@@ -534,8 +561,10 @@ impl PropagationClient {
|
||||
self.start_download_with_limit(None)
|
||||
}
|
||||
|
||||
/// Start a propagation download, limiting newly requested messages.
|
||||
/// `None` and zero mirror Python's `PR_ALL_MESSAGES`.
|
||||
/// Start a propagation download, limiting newly requested messages across
|
||||
/// the whole cycle. `None` and zero select all eligible messages, as with
|
||||
/// Python's `PR_ALL_MESSAGES`. Returns `false` while active, without a node,
|
||||
/// with queued downloads, or while suppression persistence blocks a restart.
|
||||
/// Move live downloads into the durable adapter before restarting. Failure
|
||||
/// or cancellation drops the client-owned queue and revokes its tokens;
|
||||
/// already moved payload/worker owners retain their memory leases.
|
||||
@@ -649,7 +678,9 @@ impl PropagationClient {
|
||||
true
|
||||
}
|
||||
|
||||
/// Cancel an active request and return to the idle state.
|
||||
/// Revoke current admissions, drop client-owned downloads and return to idle.
|
||||
/// External payload/worker owners retain their memory leases. Link cleanup
|
||||
/// is queued; this call does not wait for network teardown to complete.
|
||||
pub fn cancel_download(&mut self) {
|
||||
self.cleanup();
|
||||
self.status = PropagationTransferStatus::default();
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
//! Store-and-forward propagation node with optional disk persistence.
|
||||
//! Propagation-node storage admission, peer offer selection and client GET plans.
|
||||
//!
|
||||
//! Mirrors propagation node management in Python LXMRouter.py. Provides
|
||||
//! message acceptance with size/duplicate checks, sync offer generation with
|
||||
//! per-peer filtering, peer persistence (save/load with handled message sets),
|
||||
//! and expired message culling with orphaned file cleanup.
|
||||
//! Durable network deposits require a disk-backed v2 store. The node reserves
|
||||
//! admission under its owner lock, publishes opaque bytes and provenance on a
|
||||
//! blocking worker, then commits in-memory accounting. Expiry and quota culling
|
||||
//! retire indexed entries; unindexed legacy or orphan files are not promoted or
|
||||
//! removed by ordinary maintenance.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
@@ -18,15 +19,20 @@ use crate::types::PropagationTransientId;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PropagationNodeConfig {
|
||||
/// Stored-byte admission threshold. One new message may cross it: admission
|
||||
/// checks current stored plus reserved bytes. Run maintenance to cull excess.
|
||||
/// This is not a hard maximum for the resulting stored byte count.
|
||||
pub max_storage: usize,
|
||||
pub max_message_age: u64,
|
||||
/// Messages below this effective stamp value are rejected. Python derives
|
||||
/// this from `propagation_stamp_cost - propagation_stamp_cost_flexibility`.
|
||||
pub min_stamp_cost: u8,
|
||||
pub peering_cost: u8,
|
||||
/// Maximum newly admitted image size in bytes, including the 32-byte PN stamp.
|
||||
pub max_message_size: usize,
|
||||
/// Maximum encoded inbound `/offer` request size. This follows the
|
||||
/// node's advertised propagation sync budget.
|
||||
/// Maximum encoded inbound `/offer` request size in bytes. The default
|
||||
/// uses [`SYNC_LIMIT`] in decimal kilobytes; the caller must keep this
|
||||
/// setting aligned with its advertised sync budget.
|
||||
pub max_offer_size: usize,
|
||||
}
|
||||
|
||||
@@ -126,10 +132,10 @@ fn get_ids(input: Option<&[u8]>) -> impl Iterator<Item = PropagationTransientId>
|
||||
})
|
||||
}
|
||||
|
||||
/// Outcome of [`PropagationNode::handle_get_request`]. Phases 1/3 (and
|
||||
/// malformed input) are answered from the store alone; phase 2 returns a
|
||||
/// read plan so the embedder performs blocking file I/O after releasing
|
||||
/// the node lock.
|
||||
/// Immediate GET response or deferred file-work plan. Listing and malformed
|
||||
/// requests can return bytes directly. Requests with wants or haves produce
|
||||
/// a plan for durable retirements and reads, including purge-only requests.
|
||||
/// Resolve that plan after releasing the node lock.
|
||||
#[derive(Debug)]
|
||||
pub enum GetRequestAction {
|
||||
Respond(Vec<u8>),
|
||||
@@ -137,21 +143,22 @@ pub enum GetRequestAction {
|
||||
}
|
||||
|
||||
impl GetRequestAction {
|
||||
/// Resolve to response bytes, performing any planned file reads inline.
|
||||
/// Resolve to response bytes, performing planned retirements and reads inline.
|
||||
/// Blocking; do not call while holding a shared node lock.
|
||||
pub fn into_response(self) -> Vec<u8> {
|
||||
self.into_response_with_served_count().0
|
||||
}
|
||||
|
||||
/// Resolve the response and report how many messages were actually read
|
||||
/// and admitted by the client's transfer limit. This lets the daemon keep
|
||||
/// Python-compatible served-message accounting without repeating I/O.
|
||||
/// Perform deferred retirements/reads and return the response with its
|
||||
/// served-message count. Only successfully read messages that fit the
|
||||
/// client/local limits count. This method blocks when file work is planned.
|
||||
pub fn into_response_with_served_count(self) -> (Vec<u8>, u64) {
|
||||
self.into_response_with_served_count_bounded(rns_protocol::resource::MAX_RESOURCE_SIZE)
|
||||
}
|
||||
|
||||
/// Resolve on a blocking worker with its previously reserved local response
|
||||
/// allowance. Complete messages are skipped when they cannot fit.
|
||||
/// Perform deferred retirements/reads using a previously reserved local
|
||||
/// response allowance. The caller runs this on a blocking worker; this
|
||||
/// method does not spawn one. Complete messages are skipped if they cannot fit.
|
||||
pub fn into_response_with_served_count_bounded(self, maximum: usize) -> (Vec<u8>, u64) {
|
||||
match self {
|
||||
GetRequestAction::Respond(bytes) if bytes.len() <= maximum => (bytes, 0),
|
||||
@@ -161,8 +168,9 @@ impl GetRequestAction {
|
||||
}
|
||||
}
|
||||
|
||||
/// Phase-2 read plan: wants resolved and ownership-gated under the node
|
||||
/// lock; [`GetServePlan::serve`] does the file reads outside it.
|
||||
/// GET plan containing ownership-filtered wants and haves.
|
||||
/// [`Self::serve`] performs durable haves retirement before reading wants,
|
||||
/// outside the node lock. A purge-only request has no reads.
|
||||
#[derive(Debug)]
|
||||
pub struct GetServePlan {
|
||||
reads: Vec<PlannedRead>,
|
||||
@@ -179,11 +187,12 @@ struct PlannedRead {
|
||||
}
|
||||
|
||||
impl GetServePlan {
|
||||
/// Read planned files and encode the phase-2 response. Mirrors Python
|
||||
/// LXMRouter.message_get_request limit accounting (LXMRouter.py:1477-1494):
|
||||
/// 24-byte base + 16 bytes per message, full stored size counted,
|
||||
/// over-limit entries skipped (not a transfer abort), stamps stripped
|
||||
/// for client download. Unreadable files are skipped.
|
||||
/// Retire planned haves, then read wants and encode the response. A retirement
|
||||
/// error returns MessagePack nil. Client-limit accounting follows Python
|
||||
/// `LXMRouter.message_get_request`: a 24-byte base plus each full stored size
|
||||
/// and 16 bytes per message. Over-limit or unreadable entries are skipped;
|
||||
/// stored propagation stamps are stripped for client download. Local encoded
|
||||
/// response capacity is checked separately. This method blocks.
|
||||
pub fn serve(&self) -> Vec<u8> {
|
||||
self.serve_with_count().0
|
||||
}
|
||||
@@ -362,6 +371,7 @@ pub struct PlannedMessageRead {
|
||||
|
||||
/// Blocking reads for a plan from [`PropagationNode::plan_message_reads`];
|
||||
/// call without holding the node lock. Missing/unreadable files are skipped.
|
||||
/// Returned images retain their stored propagation stamps.
|
||||
pub fn read_planned_messages(
|
||||
plan: &[PlannedMessageRead],
|
||||
) -> Vec<(PropagationTransientId, Vec<u8>)> {
|
||||
@@ -664,7 +674,8 @@ pub struct PropagationNode {
|
||||
}
|
||||
|
||||
impl PropagationNode {
|
||||
/// In-memory node (no disk persistence).
|
||||
/// In-memory bookkeeping node. It cannot acknowledge durable network deposits;
|
||||
/// use [`Self::with_storage`] for hosted propagation storage.
|
||||
pub fn new(config: PropagationNodeConfig, dest_hash: [u8; 16]) -> Self {
|
||||
Self {
|
||||
config,
|
||||
@@ -732,7 +743,10 @@ impl PropagationNode {
|
||||
self.offer_generation = self.offer_generation.saturating_add(1);
|
||||
}
|
||||
|
||||
/// Disk-backed node. Loads existing messages from `storage_path` on startup.
|
||||
/// Open a disk-backed v2 store, retain its hosting lock, and load indexed entries.
|
||||
/// `storage_path` identifies the legacy/base path; its parent must exist.
|
||||
/// Historical stores or incomplete migrations require explicit offline
|
||||
/// migration rather than automatic promotion of existing files.
|
||||
pub fn with_storage(
|
||||
config: PropagationNodeConfig,
|
||||
dest_hash: [u8; 16],
|
||||
@@ -807,7 +821,9 @@ impl PropagationNode {
|
||||
})
|
||||
}
|
||||
|
||||
/// Release a reservation after a failed blocking write.
|
||||
/// Release failed-write accounting after its owning plan has been dropped.
|
||||
/// Supply the plan's original transient ID and size. A still-live reservation
|
||||
/// owner prevents release.
|
||||
pub fn abort_store_write(&mut self, transient_id: &PropagationTransientId, size: usize) {
|
||||
if self
|
||||
.pending_admissions
|
||||
@@ -876,12 +892,13 @@ impl PropagationNode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Store a validated propagated LXMF blob with its propagation-node stamp.
|
||||
/// Validate and reserve a new opaque propagation image plus its 32-byte stamp.
|
||||
/// Checks the measured stamp value against `stamp_value` and node policy;
|
||||
/// this method does not persist the returned plan.
|
||||
///
|
||||
/// Canonical propagation-node storage mirrors upstream Python: keep
|
||||
/// `lxmf_data || stamp` on disk so peer sync can forward proof-carrying
|
||||
/// data. Client `/get` strips the final 32-byte stamp before returning
|
||||
/// messages to recipients.
|
||||
/// Stored images retain `lxmf_data || stamp` for peer sync. Client `/get`
|
||||
/// strips that stamp. Duplicates return `None`; use [`Self::plan_opaque_admission`]
|
||||
/// when the caller needs pending/committed duplicate outcomes.
|
||||
pub fn plan_accept_stamped_propagated_blob(
|
||||
&mut self,
|
||||
lxmf_data: &[u8],
|
||||
@@ -904,8 +921,11 @@ impl PropagationNode {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Preferred network admission API. Same-TID exact-image duplicates share
|
||||
/// the original completion and never perform a second disk write.
|
||||
/// Plan a durable network admission or observe an existing one. Pending
|
||||
/// same-TID duplicates must have identical complete bytes and share the
|
||||
/// original completion. A committed TID retains its first stored image and
|
||||
/// returns a separate durability/provenance check; it is not overwritten.
|
||||
/// Volatile nodes reject this operation.
|
||||
pub fn plan_opaque_admission(
|
||||
&mut self,
|
||||
blob: ValidatedOpaquePropagationBlob,
|
||||
@@ -1109,7 +1129,9 @@ impl PropagationNode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns only messages the peer has not already received.
|
||||
/// Return indexed IDs absent from the caller's handled set. This compatibility
|
||||
/// helper does not apply stamp/transfer policy or pending-retirement filtering;
|
||||
/// use [`Self::prepare_sync_offer_with_policy`] for a peer-policy offer.
|
||||
pub fn create_offer_filtered(
|
||||
&self,
|
||||
handled: &HashSet<PropagationTransientId>,
|
||||
@@ -1198,9 +1220,9 @@ impl PropagationNode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Inverse-offer pattern: the peer lists what it has; we return the IDs
|
||||
/// we hold that the peer does not. Python reference:
|
||||
/// LXMRouter.offer_request_received().
|
||||
/// Local inverse-set helper: return indexed IDs absent from `offered_ids`.
|
||||
/// This is not the network `/offer` handler and performs no peer admission
|
||||
/// or pending-retirement filtering.
|
||||
pub fn offer_request(
|
||||
&mut self,
|
||||
_peer_hash: [u8; 16],
|
||||
@@ -1238,8 +1260,8 @@ impl PropagationNode {
|
||||
crate::encode_value(&value)
|
||||
}
|
||||
|
||||
/// Handle a Link REQUEST at the `/offer` path. Python reference:
|
||||
/// LXMRouter.offer_request() (LXMRouter.py:2139-2189).
|
||||
/// Handle a Link REQUEST at the `/offer` path. Related Python handler:
|
||||
/// `LXMRouter.offer_request`.
|
||||
///
|
||||
/// `request_data` is msgpack `[peering_key, [transient_id_1, ...]]`.
|
||||
/// Transitional compatibility wrapper for callers that still compute the
|
||||
@@ -1314,16 +1336,17 @@ impl PropagationNode {
|
||||
)
|
||||
}
|
||||
|
||||
/// Handle a Link REQUEST at the `/get` path for client download. Python
|
||||
/// reference: LXMRouter.message_get_request() (LXMRouter.py:1425-1499).
|
||||
/// Plan a Link REQUEST at `/get` for an already authenticated client. The
|
||||
/// caller binds `client_dest_hash` to that identity and enforces access policy.
|
||||
/// Related Python handler: `LXMRouter.message_get_request`.
|
||||
///
|
||||
/// Wire format is msgpack `[wants, haves]` or `[wants, haves, delivery_limit]`:
|
||||
/// - Phase 1 (list): `[None, None]` -> available transient IDs for the client,
|
||||
/// smallest message first (Python sorts by file size ascending).
|
||||
/// - Phase 2 (get): `[[wants...], [haves...]]` -> haves are purged first
|
||||
/// (Python order), then wants resolve to a [`GetServePlan`] whose file
|
||||
/// reads the embedder performs without holding the node lock.
|
||||
/// - Phase 3 (purge): `[None, [received_ids...]]` -> delete from store.
|
||||
/// - Phase 2 (get): `[[wants...], [haves...]]` -> a [`GetServePlan`] retires
|
||||
/// haves before reading wants when resolved on the blocking worker.
|
||||
/// - Phase 3 (purge): `[None, [received_ids...]]` -> the same deferred plan
|
||||
/// with retirements and no reads. Planning itself performs no file I/O.
|
||||
pub fn handle_get_request(
|
||||
&mut self,
|
||||
request_data: &[u8],
|
||||
@@ -1442,7 +1465,9 @@ impl PropagationNode {
|
||||
|
||||
/// Resolve requested transient IDs into store-file read plans (no I/O).
|
||||
/// Perform the reads via [`read_planned_messages`] after releasing the
|
||||
/// node lock. Returns an empty vec when there is no disk storage.
|
||||
/// node lock. Returns an empty vec when there is no disk storage. The caller
|
||||
/// must enforce any destination or offered-ID restrictions before using this
|
||||
/// helper; it selects existing eligible IDs without those authorization checks.
|
||||
pub fn plan_message_reads(
|
||||
&self,
|
||||
requested_ids: &[PropagationTransientId],
|
||||
@@ -1466,9 +1491,9 @@ impl PropagationNode {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Fetch raw packed message data for each requested transient ID. Python
|
||||
/// reference: LXMRouter.message_get_request_received(). Blocking
|
||||
/// convenience over [`Self::plan_message_reads`] — prefer the staged pair
|
||||
/// Fetch full stored opaque images, including propagation stamps, for the
|
||||
/// supplied IDs. Blocking convenience over [`Self::plan_message_reads`],
|
||||
/// with the same caller authorization responsibility. Prefer the staged pair
|
||||
/// when the node sits behind a shared lock.
|
||||
pub fn message_get_request(
|
||||
&self,
|
||||
@@ -1477,9 +1502,10 @@ impl PropagationNode {
|
||||
read_planned_messages(&self.plan_message_reads(requested_ids))
|
||||
}
|
||||
|
||||
/// Produce a `SyncOffer` listing message IDs the peer has not yet handled.
|
||||
/// The caller sends it over an established link. Python reference:
|
||||
/// LXMRouter.sync_request_received().
|
||||
/// Blocking compatibility wrapper: load the peer policy from disk, falling
|
||||
/// back to [`OutboundOfferPolicy::unrestricted`] if unavailable, then prepare
|
||||
/// an offer. Prefer an authoritative live policy snapshot. The returned
|
||||
/// [`SyncOffer`] is local data; the network task encodes the binary `/offer` wire form.
|
||||
pub fn prepare_sync_offer(&mut self, peer_hash: [u8; 16]) -> SyncOffer {
|
||||
let policy = self
|
||||
.load_peer(&peer_hash)
|
||||
@@ -1552,11 +1578,15 @@ impl PropagationNode {
|
||||
|
||||
/// Prepare one offer from an authoritative peer-policy snapshot.
|
||||
///
|
||||
/// Selection mirrors `LXMPeer.sync`: only existing, unhandled messages
|
||||
/// meeting the peer's stamp and transfer limits are eligible. Candidates
|
||||
/// are ordered by ascending store weight before the cumulative sync cap is
|
||||
/// applied. The chosen IDs are retained in the session so a subsequent
|
||||
/// response cannot request data outside this offer.
|
||||
/// Select eligible unhandled messages by ascending weight, filtering stamp
|
||||
/// and per-message limits before the cumulative sync cap, as in Python
|
||||
/// `LXMPeer.sync`. The session retains the chosen IDs; the network task uses
|
||||
/// them to validate responses. [`Self::process_sync_get`] does not perform
|
||||
/// that membership check.
|
||||
///
|
||||
/// This compatibility wrapper performs blocking peer-file reads and may
|
||||
/// persist terminal handled-ID updates. The network task stages this work
|
||||
/// outside the node lock.
|
||||
pub fn prepare_sync_offer_with_policy(&mut self, policy: &OutboundOfferPolicy) -> SyncOffer {
|
||||
loop {
|
||||
let snapshot = self.snapshot_sync_offer_preparation(policy);
|
||||
@@ -1582,8 +1612,9 @@ impl PropagationNode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Compare a peer's `SyncOffer` against our store and return a `SyncGet`
|
||||
/// listing IDs we want. Python reference: LXMRouter.offer_request_received().
|
||||
/// Local compatibility helper: select offered 32-byte IDs absent from the
|
||||
/// index and replace this peer's session. It does not validate a peering key
|
||||
/// or apply the network offer-admission policy.
|
||||
pub fn process_sync_offer(&mut self, peer_hash: [u8; 16], offer: &SyncOffer) -> SyncGet {
|
||||
// process_offer needs &self.store; compute the get before mutating sync_sessions.
|
||||
let mut tmp_session = SyncSession::new(peer_hash);
|
||||
@@ -1592,9 +1623,10 @@ impl PropagationNode {
|
||||
result
|
||||
}
|
||||
|
||||
/// Return the packed message data for each ID in `get`. The caller
|
||||
/// transfers each blob as a Resource over the link. Python reference:
|
||||
/// LXMRouter.message_get_request_received().
|
||||
/// Blocking compatibility helper returning full stored images for the valid
|
||||
/// 32-byte IDs in `get`. This does not restrict requests to a previous offer;
|
||||
/// the caller must validate that membership. The network task in
|
||||
/// [`crate::propagation_sync`] filters responses and constructs the batch wire format.
|
||||
pub fn process_sync_get(&mut self, peer_hash: [u8; 16], get: &SyncGet) -> Vec<Vec<u8>> {
|
||||
if let Some(session) = self.sync_sessions.get_mut(&peer_hash) {
|
||||
session.process_get(get);
|
||||
@@ -1623,11 +1655,10 @@ impl PropagationNode {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Record a successful transfer for a peer. Loads the peer, adds the
|
||||
/// transient ID to its handled set, saves it, and records the transfer in
|
||||
/// the sync session. Python reference:
|
||||
/// LXMRouter.propagation_resource_concluded() (LXMRouter.py:2271) --
|
||||
/// `peer.queue_handled_message(transient_id)`.
|
||||
/// Best-effort blocking bookkeeping for a successful peer transfer. If the
|
||||
/// peer loads, add the ID and attempt to save; save errors are ignored.
|
||||
/// An existing session's transfer counter increments independently. Use
|
||||
/// [`Self::persist_peer_handled`] when the caller needs persistence errors.
|
||||
pub fn mark_peer_handled(
|
||||
&mut self,
|
||||
peer_hash: &[u8; 16],
|
||||
@@ -1643,8 +1674,9 @@ impl PropagationNode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Merge peer-handled observations into persisted state using the same
|
||||
/// authoritative policy that produced the offer.
|
||||
/// Merge peer-handled observations using the authoritative offer policy and
|
||||
/// persist the result, returning write errors. This blocks on peer-file I/O.
|
||||
/// A volatile node returns success without writing a peer file.
|
||||
pub fn persist_peer_handled(
|
||||
&self,
|
||||
policy: &OutboundOfferPolicy,
|
||||
|
||||
@@ -13,7 +13,10 @@ use crate::types::PropagationTransientId;
|
||||
/// A binary 32-byte transient ID requires at least 34 MessagePack bytes.
|
||||
const ENCODED_TRANSIENT_ID_MIN_BYTES: usize = 34;
|
||||
|
||||
/// A peering-key-validated offer and the subset not present in local storage.
|
||||
/// Offer outcome and the subset absent from local storage. The variants are
|
||||
/// publicly constructible, so this value alone is not proof of authentication
|
||||
/// or admission. Obtain it through [`crate::propagation_node::PropagationNode::evaluate_offer_request`]
|
||||
/// after preflight, then commit it to that same admission candidate.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum PnOfferEvaluation {
|
||||
HaveAll,
|
||||
|
||||
@@ -27,8 +27,10 @@ pub struct PreparedNode {
|
||||
pub policy: AdvertisedNodePolicy,
|
||||
}
|
||||
|
||||
/// Identity and policy freshness are required; the recipient itself may be
|
||||
/// offline. Only a missing recipient key warrants recipient path discovery.
|
||||
/// Check the node identity, node path, advertised policy and recipient key.
|
||||
/// Policy must be younger than [`NODE_METADATA_MAX_AGE`] and have a finite,
|
||||
/// nonnegative transfer limit. The recipient may be offline: only its key is
|
||||
/// needed. This function reports missing inputs; it performs no path discovery.
|
||||
pub fn propagation_readiness(
|
||||
node: [u8; 16],
|
||||
node_identity_known: bool,
|
||||
@@ -58,8 +60,9 @@ pub fn propagation_readiness(
|
||||
Ok(PreparedNode { node, policy })
|
||||
}
|
||||
|
||||
/// One send-owned encryption result. Retrying changes only the outer timestamp
|
||||
/// and (when required cost rises) the PN stamp, never ciphertext or transient ID.
|
||||
/// One send-owned encryption result. Retrying changes the outer timestamp and,
|
||||
/// if the saved stamp no longer meets the node's cost, regenerates the PN stamp.
|
||||
/// Ciphertext and transient ID stay fixed.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PropagationEnvelope {
|
||||
message: LxMessage,
|
||||
@@ -155,7 +158,9 @@ impl PropagationEnvelope {
|
||||
self.message.wire_bytes() == message.wire_bytes()
|
||||
&& &self.encryption_binding == encryption_binding
|
||||
}
|
||||
/// Call immediately before dispatch with refreshed advertised policy.
|
||||
/// Pack immediately before dispatch using policy checked by
|
||||
/// [`propagation_readiness`]. This does not refresh the policy or send data.
|
||||
/// It may synchronously regenerate the PN stamp if more work is required.
|
||||
pub fn pack_for(
|
||||
&mut self,
|
||||
node: PreparedNode,
|
||||
|
||||
@@ -177,8 +177,10 @@ fn verify_inventory(root: &Path, j: &MigrationJournal) -> io::Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Startup only initializes a truly absent store. An incomplete journal or
|
||||
/// historical directory requires the explicit offline recovery path.
|
||||
/// Initialize a truly absent store or validate a completed v2 store. An
|
||||
/// incomplete journal or historical directory requires explicit offline migration.
|
||||
/// The temporary store lock is released before this returns the path; this
|
||||
/// function does not grant a hosting lease.
|
||||
pub fn open_store(legacy: &Path) -> io::Result<PathBuf> {
|
||||
Ok(open_locked_store(legacy)?.0)
|
||||
}
|
||||
@@ -230,8 +232,10 @@ fn verify_published(j: &MigrationJournal) -> io::Result<()> {
|
||||
durable_reconcile(&j.v2.join("FORMAT"), FORMAT).map_err(err)?;
|
||||
Ok(())
|
||||
}
|
||||
/// The guard binds both path and verified writer exclusion. Neither a retry nor
|
||||
/// operator approval promotes any legacy object without independent provenance.
|
||||
/// Migrate the canonical path protected by the guard. Keep the constructor's
|
||||
/// writer-exclusion conditions in force throughout this call. Legacy objects
|
||||
/// remain quarantined; a retry or operator approval does not establish ingress
|
||||
/// provenance for them.
|
||||
pub fn migrate_store_offline(guard: &OfflineMigrationGuard) -> io::Result<MigrationReport> {
|
||||
migrate(&guard.legacy, None)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
use super::*;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// Holds the same OS lock as every v2 host. Legacy binaries ignore this lock;
|
||||
/// the mandatory supervisor assertion and known-process probe address that gap.
|
||||
/// Hold the OS lock shared with current v2 hosts during offline migration.
|
||||
/// Legacy binaries ignore it. The desktop constructor also requires the caller
|
||||
/// to stop supervisors and checks known processes; the iOS/Android constructors
|
||||
/// use restricted app-container checks and require the caller to join its writers.
|
||||
pub struct OfflineMigrationGuard {
|
||||
pub(super) legacy: PathBuf,
|
||||
pub(super) _lock: File,
|
||||
|
||||
@@ -91,8 +91,10 @@ fn validate(
|
||||
}
|
||||
|
||||
/// Import exact positively attested archive entries under the same offline
|
||||
/// guard. Every entry is checked before the first write, then rechecked at its
|
||||
/// publication boundary. Partial IO completion is restart-safe and idempotent.
|
||||
/// guard. Existing deletion journals are reconciled first. All selected entries
|
||||
/// are checked before any imported object is published, then rechecked at each
|
||||
/// publication boundary. Retrying after partial completion retains already
|
||||
/// committed entries and imports only those still absent.
|
||||
pub fn import_trusted_recovery_manifest(
|
||||
guard: &OfflineMigrationGuard,
|
||||
path: &Path,
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
//! Propagation sync background task.
|
||||
//! Outbound propagation-peer sync, driven by the caller through
|
||||
//! [`PropagationSyncTask::drain_events`] and [`PropagationSyncTask::tick`].
|
||||
//!
|
||||
//! Outbound sync to a configured propagation node using the Link
|
||||
//! REQUEST/RESPONSE pattern. Python reference: LXMPeer.py:381-386.
|
||||
//! The `/offer` exchange follows Python `LXMPeer.sync()` and `offer_response()`:
|
||||
//! 1. Establish a Link and send identification when local identity material is configured.
|
||||
//! 2. Send `/offer` with `[peering_key, transient_ids]`.
|
||||
//! 3. Read the response and intersect requested IDs with this attempt's offer.
|
||||
//! 4. Transfer available requested messages as a Resource, splitting large payloads.
|
||||
//! 5. Expose handled-ID updates and a terminal result for the caller to persist.
|
||||
//!
|
||||
//! Flow:
|
||||
//! 1. Establish a link to the node.
|
||||
//! 2. Send link.request("/offer", [peering_key, transient_ids]).
|
||||
//! 3. Receive a Response packet (context 0x0A) with OfferResponse.
|
||||
//! 4. Transfer requested messages as a Resource.
|
||||
//! Use an authoritative peer-policy snapshot for production sync. Policy-based
|
||||
//! offer preparation and message reads use blocking workers when a Tokio runtime
|
||||
//! is available; without one, they run synchronously. Compatibility offer
|
||||
//! preparation is always synchronous. This type does not spawn its own polling loop.
|
||||
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::sync::{Arc, Mutex};
|
||||
@@ -62,11 +66,12 @@ pub struct PeerSyncTerminalResult {
|
||||
/// Store generation used by successful offer preparation. Failures leave
|
||||
/// this unset so unchanged-store work remains retryable after backoff.
|
||||
pub offer_generation: Option<u64>,
|
||||
/// True only when no cumulative-limit or vanished-file work remains for
|
||||
/// this generation.
|
||||
/// With an authoritative policy, a completed attempt sets this only when
|
||||
/// no cumulative-limit or vanished-file work remains for the generation.
|
||||
/// The compatibility path without a policy assumes the offer exhausted it;
|
||||
/// it does not track work excluded by its offer limit.
|
||||
pub generation_exhausted: bool,
|
||||
/// Peer accounting deltas matching Python `LXMPeer.offer_response()` and
|
||||
/// `resource_concluded()` semantics.
|
||||
/// Number of IDs offered in a completed attempt; zero on failure.
|
||||
pub offered: u64,
|
||||
pub outgoing: u64,
|
||||
pub tx_bytes: u64,
|
||||
@@ -232,7 +237,9 @@ impl PropagationSyncTask {
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a sync task with disk-backed propagation storage.
|
||||
/// Create a sync task with v2 propagation storage and its retained hosting lock.
|
||||
/// Path resolution, startup errors and migration prerequisites are those of
|
||||
/// [`PropagationNode::with_storage`].
|
||||
pub fn with_storage(
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
dest_hash: [u8; 16],
|
||||
@@ -358,11 +365,10 @@ impl PropagationSyncTask {
|
||||
self.node_dest_hash = Some(dest_hash);
|
||||
}
|
||||
|
||||
/// Force an immediate sync attempt with `dest_hash`.
|
||||
///
|
||||
/// Python `LXMPeer.sync()` is called directly by lxmd control requests;
|
||||
/// this public shim preserves that behavior without waiting for the
|
||||
/// periodic sync interval.
|
||||
/// Start an attempt without waiting for the periodic interval. Returns
|
||||
/// `false` when busy, while a terminal result awaits collection, or if Link
|
||||
/// setup cannot be staged. This compatibility entry point clears the
|
||||
/// authoritative policy; use [`Self::request_sync_now_with_policy`] when available.
|
||||
pub fn request_sync_now(&mut self, dest_hash: [u8; 16]) -> bool {
|
||||
if self.state != SyncTaskState::Idle || self.terminal_result.is_some() {
|
||||
return false;
|
||||
@@ -376,7 +382,9 @@ impl PropagationSyncTask {
|
||||
true
|
||||
}
|
||||
|
||||
/// Force an immediate sync using an authoritative peer-policy snapshot.
|
||||
/// Start an attempt with an authoritative peer-policy snapshot, bypassing
|
||||
/// the periodic interval. Returns `false` when busy, while a terminal result
|
||||
/// awaits collection, or if Link setup cannot be staged.
|
||||
pub fn request_sync_now_with_policy(&mut self, policy: OutboundOfferPolicy) -> bool {
|
||||
if self.state != SyncTaskState::Idle || self.terminal_result.is_some() {
|
||||
return false;
|
||||
@@ -399,9 +407,9 @@ impl PropagationSyncTask {
|
||||
self.identity_key = Some(identity_key);
|
||||
}
|
||||
|
||||
/// Drain peer-handled updates discovered during offer negotiation or
|
||||
/// proven Resource transfer. The daemon merges these into its authoritative
|
||||
/// `LxmPeer` and persists that peer.
|
||||
/// Drain handled IDs from policy filtering, offer negotiation and proven
|
||||
/// Resource transfer. The caller must merge these into its authoritative
|
||||
/// `LxmPeer` and persist it; draining alone performs no write.
|
||||
pub fn take_handled_updates(&mut self) -> Vec<PropagationTransientId> {
|
||||
std::mem::take(&mut self.handled_updates)
|
||||
}
|
||||
@@ -410,9 +418,11 @@ impl PropagationSyncTask {
|
||||
self.terminal_result.take()
|
||||
}
|
||||
|
||||
/// Cancel all active and pending work for one peer. Dropping the bounded
|
||||
/// worker receivers makes late preparation results inert, and clearing
|
||||
/// handled deltas prevents an explicit unpeer from recreating persistence.
|
||||
/// Discard this task's active and pending work for a matching peer, remove
|
||||
/// its session and return to idle. Already running blocking workers may
|
||||
/// finish their I/O, but dropped result receivers prevent installing their
|
||||
/// results. Handled deltas are cleared so this task cannot restore them
|
||||
/// after an explicit unpeer. Returns `false` if neither node nor policy matches.
|
||||
pub fn cancel_peer_sync(&mut self, peer_hash: &[u8; 16]) -> bool {
|
||||
let matches_active = self.node_dest_hash.as_ref() == Some(peer_hash);
|
||||
let matches_policy = self
|
||||
|
||||
+176
-150
@@ -1,7 +1,9 @@
|
||||
//! LXMF Router: message delivery engine and propagation node.
|
||||
//! LXMF routing policy, delivery queues and propagation bookkeeping.
|
||||
//!
|
||||
//! Python reference: LXMF/LXMRouter.py. Actor pattern — a single tokio task owns
|
||||
//! all mutable state.
|
||||
//! The embedding application owns and drives [`LxmRouter`]. It must connect
|
||||
//! transport delivery, durable admission and peer-sync workers; the router does
|
||||
//! not spawn an actor loop or host a propagation node by itself. Python's
|
||||
//! `LXMRouter` is the corresponding protocol reference.
|
||||
|
||||
use crate::now_f64;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
@@ -26,15 +28,17 @@ use crate::stamper;
|
||||
use crate::ticket::{Ticket, TicketStore};
|
||||
use crate::types::PropagationTransientId;
|
||||
|
||||
/// Outstanding actor-owned admission. Only this router can match its nonce.
|
||||
/// Outstanding inbound admission reservation. Return it to the same router
|
||||
/// instance that issued it; its counter is not unique across router instances.
|
||||
#[derive(Debug)]
|
||||
pub struct InboundReservation {
|
||||
message_id: [u8; 32],
|
||||
nonce: u64,
|
||||
}
|
||||
|
||||
/// Durable barrier for router-minted reply tickets. Signing the marked draft
|
||||
/// fails until this exact intent has committed its immutable ticket snapshot.
|
||||
/// Persistence barrier for a router-minted reply ticket. Signing the marked
|
||||
/// draft remains blocked until this intent establishes that the required ticket
|
||||
/// is durable, either in its snapshot or a newer committed ticket snapshot.
|
||||
pub struct OutboundTicketIntent {
|
||||
barrier: Option<std::sync::Arc<()>>,
|
||||
snapshot: Option<crate::persist::TicketPersistenceSnapshot>,
|
||||
@@ -63,8 +67,8 @@ impl OutboundTicketIntent {
|
||||
|
||||
/// Router configuration.
|
||||
///
|
||||
/// Core fields are stable for downstream compatibility; additional Python
|
||||
/// `LXMRouter.__init__` knobs live in [`RouterConfigExt`] behind the `ext` field.
|
||||
/// Additional settings live in [`RouterConfigExt`] behind the `ext` field.
|
||||
/// Embedders must pass relevant policy to their transport and propagation owners.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RouterConfig {
|
||||
pub propagation_enabled: bool,
|
||||
@@ -81,7 +85,7 @@ pub struct RouterConfig {
|
||||
|
||||
/// Extended router configuration.
|
||||
///
|
||||
/// Additional `LXMRouter.__init__` fields; all have sensible defaults.
|
||||
/// Additional routing, admission and propagation settings with a [`Default`] implementation.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RouterConfigExt {
|
||||
pub autopeer_maxdepth: usize,
|
||||
@@ -89,13 +93,14 @@ pub struct RouterConfigExt {
|
||||
pub peering_cost: u8,
|
||||
pub max_peering_cost: u8,
|
||||
pub processing_outbound: bool,
|
||||
/// Maximum outbound messages to process per tick (`None` = unlimited).
|
||||
/// Maximum messages advanced per outbound-processing call (`None` = no count limit).
|
||||
pub processing_limit: Option<usize>,
|
||||
pub retain_synced_on_node: bool,
|
||||
pub auth_required: bool,
|
||||
/// Generate outbound message PoW stamps through the router deferred-stamp queue.
|
||||
pub defer_stamp_generation: bool,
|
||||
/// Propagation storage cap in bytes (`None` = unlimited).
|
||||
/// Size-culling target for the router's in-memory propagation index, in bytes.
|
||||
/// `None` disables size-based culling; this is not an insertion or disk quota.
|
||||
pub message_storage_limit: Option<usize>,
|
||||
/// Name advertised in propagation announce metadata.
|
||||
pub name: Option<String>,
|
||||
@@ -235,12 +240,9 @@ pub enum DirectDeliveryPlan {
|
||||
Fail,
|
||||
}
|
||||
|
||||
/// Apply upstream LXMF Direct delivery attempt/path/link policy to one message.
|
||||
///
|
||||
/// This is a policy primitive for embedders that still own transport adapters.
|
||||
/// It mutates the same attempt/progress fields Python mutates in
|
||||
/// `LXMRouter.process_outbound`, but leaves actual path requests and Link
|
||||
/// creation to the caller.
|
||||
/// Plan a Direct delivery from the caller's identity, route and Link snapshot.
|
||||
/// Mutates attempt, timing, progress and message state; the caller performs
|
||||
/// path requests and Link operations and reports their outcomes.
|
||||
pub fn plan_direct_delivery(
|
||||
message: &mut LxMessage,
|
||||
input: DirectDeliveryPlanInput,
|
||||
@@ -314,7 +316,7 @@ pub fn plan_direct_delivery(
|
||||
}
|
||||
}
|
||||
|
||||
/// LXMF router — owns all mutable state under the actor pattern.
|
||||
/// Router-owned policy and queues. The embedding application serializes access and drives it.
|
||||
pub struct LxmRouter {
|
||||
pub config: RouterConfig,
|
||||
pub pending_outbound: Vec<LxMessage>,
|
||||
@@ -323,13 +325,13 @@ pub struct LxmRouter {
|
||||
/// Order in which `defer_stamp` queued the deferred messages, so stamps
|
||||
/// are generated first in, first out.
|
||||
deferred_stamp_order: VecDeque<[u8; 32]>,
|
||||
/// Captured at construction so deferred-stamp PoW can spawn onto the
|
||||
/// blocking pool even when the caller is itself on a `spawn_blocking`
|
||||
/// thread, where `Handle::try_current()` fails. Without it the tick grinds
|
||||
/// stamps inline while holding the manager lock (observed 53 s stall).
|
||||
/// Fallback runtime for deferred stamp workers, captured at construction.
|
||||
/// The current runtime is preferred. If neither is available, stamp search
|
||||
/// runs synchronously in the calling thread.
|
||||
pub runtime_handle: Option<tokio::runtime::Handle>,
|
||||
pub active_deferred_stamp: Option<DeferredStampJob>,
|
||||
/// Identities allowed for delivery. An empty list means "all allowed".
|
||||
/// Allow-list consulted by [`Self::is_allowed`]. Empty admits identities not blocked;
|
||||
/// authentication policy must be enforced separately by the embedding adapter.
|
||||
pub allowed: Vec<[u8; 16]>,
|
||||
pub blocked: Vec<[u8; 16]>,
|
||||
pub allowed_control: Vec<[u8; 16]>,
|
||||
@@ -342,7 +344,8 @@ pub struct LxmRouter {
|
||||
pub outbound_stamp_costs: HashMap<[u8; 16], StampCostEntry>,
|
||||
pub ticket_store: TicketStore,
|
||||
ticket_intent_in_flight: std::sync::Weak<()>,
|
||||
/// Identity hash → priority level.
|
||||
/// Destination hash → recorded priority level. The propagation index uses
|
||||
/// membership to apply its fixed priority weight; it does not use the level.
|
||||
pub prioritized: HashMap<[u8; 16], u8>,
|
||||
pub delivery_callback: Option<DeliveryCallback>,
|
||||
pub transport_tx: Option<mpsc::Sender<rns_transport::messages::TransportMessage>>,
|
||||
@@ -405,8 +408,8 @@ pub struct StampCostEntry {
|
||||
|
||||
/// Owned, coherent snapshot of the router state written by [`LxmRouter::save_state`].
|
||||
///
|
||||
/// Creating the snapshot only clones in-memory state. The caller can therefore
|
||||
/// release any lock that protects the router before calling [`Self::save_state`],
|
||||
/// Capturing this snapshot clones in-memory state and assigns a ticket revision.
|
||||
/// The caller can release any router lock before calling [`Self::save_state`],
|
||||
/// keeping filesystem I/O out of the router's critical section.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RouterStateSnapshot {
|
||||
@@ -421,7 +424,8 @@ impl RouterStateSnapshot {
|
||||
/// Persist this owned snapshot using the router's MessagePack layout.
|
||||
///
|
||||
/// Each file is written atomically via rename, matching
|
||||
/// [`LxmRouter::save_state`].
|
||||
/// [`LxmRouter::save_state`]. The group is not one transaction: an error can
|
||||
/// follow successful writes to earlier files. Serialize snapshot writes.
|
||||
pub fn save_state(&self, state_dir: &std::path::Path) -> std::io::Result<()> {
|
||||
use crate::persist;
|
||||
|
||||
@@ -503,14 +507,14 @@ impl LxmRouter {
|
||||
|
||||
/// Number of active ordinary inbound delivery Resources.
|
||||
///
|
||||
/// Python reference: `LXMRouter.inbound_count` — LXMRouter.py:466.
|
||||
/// Python reference: `LXMRouter.inbound_count`.
|
||||
pub fn inbound_count(&self) -> usize {
|
||||
self.inbound_resource_tracker.inbound_count()
|
||||
}
|
||||
|
||||
/// Owned handles for all active ordinary inbound delivery Resources.
|
||||
///
|
||||
/// Python reference: `LXMRouter.inbound_resources` — LXMRouter.py:474.
|
||||
/// Python reference: `LXMRouter.inbound_resources`.
|
||||
pub fn inbound_resources(&self) -> Vec<InboundResourceHandle> {
|
||||
self.inbound_resource_tracker.inbound_resources()
|
||||
}
|
||||
@@ -527,7 +531,7 @@ impl LxmRouter {
|
||||
|
||||
/// Queue cancellation for one unique active logical Resource.
|
||||
///
|
||||
/// Python reference: `LXMRouter.cancel_inbound` — LXMRouter.py:484.
|
||||
/// Python reference: `LXMRouter.cancel_inbound`.
|
||||
pub fn cancel_inbound(&self, resource_id: &[u8; 32]) -> bool {
|
||||
self.inbound_resource_tracker.cancel_inbound(resource_id)
|
||||
}
|
||||
@@ -538,8 +542,8 @@ impl LxmRouter {
|
||||
}
|
||||
|
||||
/// Queue cancellation for a stable snapshot of all active Resources.
|
||||
///
|
||||
/// Python reference: `LXMRouter.cancel_all_inbound` — LXMRouter.py:505.
|
||||
/// Returns the number of requests accepted by the adapter queue, not the
|
||||
/// number of completed cancellations.
|
||||
pub fn cancel_all_inbound(&self) -> usize {
|
||||
self.inbound_resource_tracker.cancel_all_inbound()
|
||||
}
|
||||
@@ -565,10 +569,10 @@ impl LxmRouter {
|
||||
|
||||
/// Queue a message for outbound delivery and report immediate routing errors.
|
||||
///
|
||||
/// Mirrors Python LXMF 0.9.8's explicit `IOError` when a caller attempts
|
||||
/// `PROPAGATED` delivery without configuring an outbound propagation node.
|
||||
/// The legacy [`send`](Self::send) wrapper preserves older Rust call-sites
|
||||
/// while still marking the message failed and firing its callback.
|
||||
/// Propagated delivery requires an outbound propagation node; otherwise the
|
||||
/// returned error owns the message after its failure callback has fired.
|
||||
/// This low-level method does not verify signatures or reject duplicate IDs.
|
||||
/// Use [`Self::submit_signed`] for signed-message preparation and duplicate checks.
|
||||
pub fn try_send(&mut self, mut message: LxMessage) -> Result<(), SendError> {
|
||||
if message.method == DeliveryMethod::Propagated && self.outbound_propagation_node.is_none()
|
||||
{
|
||||
@@ -602,8 +606,9 @@ impl LxmRouter {
|
||||
/// Learned outbound tickets do not change signed fields and can be
|
||||
/// attached at any time. A requested reply ticket is a signed LXMF field,
|
||||
/// so it must be inserted before signing. The method is deliberately
|
||||
/// signer-agnostic: callers may subsequently use either `sign` or
|
||||
/// `sign_with` without exposing private key material to the router.
|
||||
/// signer-agnostic. When the returned intent requires persistence, call
|
||||
/// [`OutboundTicketIntent::persist`] with this draft before `sign` or
|
||||
/// `sign_with`; signing remains blocked until that barrier is released.
|
||||
pub fn prepare_outbound(
|
||||
&mut self,
|
||||
message: &mut LxMessageDraft,
|
||||
@@ -684,11 +689,10 @@ impl LxmRouter {
|
||||
|
||||
/// Restore a stored message for another delivery under the same id.
|
||||
///
|
||||
/// `source_public_key` is the active identity's: the message must verify
|
||||
/// as sent by it. The outbound ticket is the current one, and the stamp
|
||||
/// cost is the larger of the cost the message was signed under and the
|
||||
/// destination's current cost. Finish the message as for a fresh send,
|
||||
/// then pass it to [`Self::submit_signed`].
|
||||
/// The caller supplies the active identity's public key; the message must
|
||||
/// verify against it. Uses the current outbound ticket and the larger of
|
||||
/// the stored stamp-cost floor and the destination's current cost. Pass the
|
||||
/// returned signed message to [`Self::submit_signed`] for recipient work and queuing.
|
||||
pub fn restore_signed(
|
||||
&self,
|
||||
stored: &ResumableLxMessage,
|
||||
@@ -860,7 +864,8 @@ impl LxmRouter {
|
||||
self.blocked.retain(|h| h != identity_hash);
|
||||
}
|
||||
|
||||
/// An empty allow-list means "everyone not blocked is allowed".
|
||||
/// An empty allow-list admits every identity not blocked. This helper does
|
||||
/// not consult [`Self::requires_authentication`] or verify an identity proof.
|
||||
pub fn is_allowed(&self, identity_hash: &[u8; 16]) -> bool {
|
||||
if !self.blocked.contains(identity_hash) {
|
||||
self.allowed.is_empty() || self.allowed.contains(identity_hash)
|
||||
@@ -873,47 +878,47 @@ impl LxmRouter {
|
||||
self.allowed_control.contains(identity_hash)
|
||||
}
|
||||
|
||||
/// Whether delivery requires an entry in the allow-list.
|
||||
///
|
||||
/// Python reference: `LXMRouter.requires_authentication` — LXMRouter.py:415-417.
|
||||
/// Configured authentication requirement for the embedding delivery adapter.
|
||||
/// This getter does not enforce access; [`Self::is_allowed`] is a separate check.
|
||||
pub fn requires_authentication(&self) -> bool {
|
||||
self.config.ext.auth_required
|
||||
}
|
||||
|
||||
/// Toggle whether delivery requires an entry in the allow-list.
|
||||
///
|
||||
/// Python reference: `LXMRouter.set_authentication` — LXMRouter.py:409-413.
|
||||
/// Set the authentication requirement consumed by the embedding adapter.
|
||||
/// This does not change [`Self::is_allowed`] or validate incoming messages itself.
|
||||
pub fn set_authentication(&mut self, required: bool) {
|
||||
self.config.ext.auth_required = required;
|
||||
}
|
||||
|
||||
/// Whether the node keeps synchronized messages in its propagation store.
|
||||
/// Retention preference passed to [`crate::propagation_client::PropagationClient`].
|
||||
/// The current client retains previously known haves when enabled; newly
|
||||
/// downloaded messages accepted through admission are still purged.
|
||||
pub fn retain_node_lxms(&self) -> bool {
|
||||
self.config.ext.retain_synced_on_node
|
||||
}
|
||||
|
||||
/// Toggle whether the node keeps synchronized messages in its propagation store.
|
||||
///
|
||||
/// Python reference: `LXMRouter.set_retain_node_lxms` — LXMRouter.py:419-420.
|
||||
/// Set the retention preference for the embedding propagation client.
|
||||
/// The adapter must copy it to the client. See [`Self::retain_node_lxms`]
|
||||
/// for the current known-haves-only scope.
|
||||
pub fn set_retain_node_lxms(&mut self, retain: bool) {
|
||||
self.config.ext.retain_synced_on_node = retain;
|
||||
}
|
||||
|
||||
/// Propagation storage cap in bytes (`None` = unlimited).
|
||||
/// Size-culling target for the router's propagation index, in bytes.
|
||||
/// `None` disables size-based culling.
|
||||
pub fn message_storage_limit(&self) -> Option<usize> {
|
||||
self.config.ext.message_storage_limit
|
||||
}
|
||||
|
||||
/// Set the propagation storage cap in bytes (`None` = unlimited).
|
||||
///
|
||||
/// Python reference: `LXMRouter.set_message_storage_limit` — LXMRouter.py:423-424.
|
||||
/// Set the propagation index's size-culling target in bytes. `None` disables
|
||||
/// size-based culling; the setter does not cull immediately or impose a disk quota.
|
||||
/// Culling runs through [`Self::cull_propagation`] or enabled periodic jobs.
|
||||
pub fn set_message_storage_limit(&mut self, limit: Option<usize>) {
|
||||
self.config.ext.message_storage_limit = limit;
|
||||
}
|
||||
|
||||
/// Current on-disk-equivalent size of the propagation store, in bytes.
|
||||
///
|
||||
/// Python reference: `LXMRouter.message_storage_size` — LXMRouter.py:437-441.
|
||||
/// Byte count recorded by the router's in-memory propagation index.
|
||||
/// This does not inspect files or a separately hosted [`crate::propagation_node::PropagationNode`].
|
||||
pub fn message_storage_size(&self) -> usize {
|
||||
self.propagation_store.total_size()
|
||||
}
|
||||
@@ -923,7 +928,9 @@ impl LxmRouter {
|
||||
/// The returned token can be shared with a peer that should bypass stamp PoW when sending
|
||||
/// to this router. Default expiry is [`TICKET_EXPIRY`] seconds.
|
||||
///
|
||||
/// Python reference: `LXMRouter.generate_ticket` — LXMRouter.py:1094-1108.
|
||||
/// This low-level helper always generates a token, without renewal/interval
|
||||
/// reuse or persistence. Persist ticket state before advertising the token;
|
||||
/// [`Self::prepare_outbound`] supplies the normal reply-ticket barrier.
|
||||
pub fn generate_ticket(
|
||||
&mut self,
|
||||
destination_hash: [u8; 16],
|
||||
@@ -940,15 +947,15 @@ impl LxmRouter {
|
||||
|
||||
/// Record an externally-provided outbound ticket so the router can use it when sending.
|
||||
///
|
||||
/// Python reference: `LXMRouter.remember_ticket` — LXMRouter.py:1110-1113.
|
||||
/// Python reference: `LXMRouter.remember_ticket`.
|
||||
pub fn remember_ticket(&mut self, destination_hash: [u8; 16], token: [u8; 16], expires: f64) {
|
||||
self.ticket_store
|
||||
.remember_outbound(Ticket::new(token, destination_hash, expires));
|
||||
}
|
||||
|
||||
/// Returns the token of the first valid ticket for `destination_hash`.
|
||||
/// Return the currently stored valid outbound ticket for `destination_hash`.
|
||||
///
|
||||
/// Python reference: `LXMRouter.get_outbound_ticket` — LXMRouter.py:1058-1064.
|
||||
/// Python reference: `LXMRouter.get_outbound_ticket`.
|
||||
pub fn get_outbound_ticket(&self, destination_hash: &[u8; 16]) -> Option<[u8; 16]> {
|
||||
let now = now_f64();
|
||||
self.ticket_store
|
||||
@@ -958,7 +965,7 @@ impl LxmRouter {
|
||||
|
||||
/// Returns the expiry (Unix epoch seconds) of the valid ticket for `destination_hash`.
|
||||
///
|
||||
/// Python reference: `LXMRouter.get_outbound_ticket_expiry` — LXMRouter.py:1125-1131.
|
||||
/// Python reference: `LXMRouter.get_outbound_ticket_expiry`.
|
||||
pub fn get_outbound_ticket_expiry(&self, destination_hash: &[u8; 16]) -> Option<f64> {
|
||||
let now = now_f64();
|
||||
self.ticket_store
|
||||
@@ -966,19 +973,16 @@ impl LxmRouter {
|
||||
.map(|t| t.expires)
|
||||
}
|
||||
|
||||
/// Snapshot of all stored tickets (including expired / used entries).
|
||||
///
|
||||
/// Python reference: `LXMRouter.get_inbound_tickets` — LXMRouter.py:1133-1136.
|
||||
/// Borrow all locally issued inbound tickets, across destinations. Expired
|
||||
/// entries remain visible until culled. This does not include learned outbound tickets.
|
||||
pub fn get_inbound_tickets(&self) -> &[Ticket] {
|
||||
self.ticket_store.inbound()
|
||||
}
|
||||
|
||||
/// Cancel an outbound message before it is sent.
|
||||
///
|
||||
/// Removes the message from `pending_outbound` (or `pending_deferred_stamps`) if it is still
|
||||
/// in a cancellable state. Returns `true` if the message was found and cancelled.
|
||||
///
|
||||
/// Python reference: `LXMRouter.cancel_outbound` — LXMRouter.py:474-487.
|
||||
/// Remove a matching message from the router's outbound or deferred-stamp queue.
|
||||
/// Returns `true` when found, regardless of its prior state. A matching active
|
||||
/// stamp worker receives a cooperative cancellation request. The embedding
|
||||
/// runtime must separately cancel any Link/Resource work it already owns.
|
||||
pub fn cancel_outbound(&mut self, message_hash: &[u8; 32]) -> bool {
|
||||
if let Some(pos) = self
|
||||
.pending_outbound
|
||||
@@ -1051,8 +1055,8 @@ impl LxmRouter {
|
||||
/// Python's router retains each one's announce data in Reticulum so its
|
||||
/// identity outlives its path (LXMRouter.py:2761). Send each as
|
||||
/// `TransportQuery::RetainDestination` through the control plane, which
|
||||
/// forwards to a shared instance. At most the newest 256 are kept between
|
||||
/// calls.
|
||||
/// forwards to a shared instance. Up to 256 distinct destinations are kept
|
||||
/// in insertion order; a repeat delivery does not refresh an existing entry's position.
|
||||
pub fn take_destination_retains(&mut self) -> Vec<[u8; 16]> {
|
||||
self.destination_retains.drain(..).collect()
|
||||
}
|
||||
@@ -1107,9 +1111,10 @@ impl LxmRouter {
|
||||
true
|
||||
}
|
||||
|
||||
/// Get the outbound-delivery progress (0.0..=1.0) for a pending message.
|
||||
/// Get the recorded progress for a queued or deferred message. The value is
|
||||
/// returned unchanged; caller-written metadata is not clamped here.
|
||||
///
|
||||
/// Python reference: `LXMRouter.get_outbound_progress` — LXMRouter.py:489-495.
|
||||
/// Python reference: `LXMRouter.get_outbound_progress`.
|
||||
pub fn get_outbound_progress(&self, message_hash: &[u8; 32]) -> Option<f64> {
|
||||
self.pending_outbound
|
||||
.iter()
|
||||
@@ -1124,42 +1129,37 @@ impl LxmRouter {
|
||||
|
||||
/// Get the cached required stamp cost for a destination (delivery).
|
||||
///
|
||||
/// Returns `None` if no announce has advertised a cost for this destination.
|
||||
///
|
||||
/// Python reference: `LXMRouter.get_outbound_lxm_stamp_cost` — LXMRouter.py:1138-1147.
|
||||
/// Returns the cached entry unchanged, without an expiry check. Use
|
||||
/// [`Self::get_stamp_cost`] to exclude expired entries. Unlike Python's
|
||||
/// same-named message-ID lookup, this API takes a destination hash.
|
||||
pub fn get_outbound_lxm_stamp_cost(&self, destination_hash: &[u8; 16]) -> Option<u8> {
|
||||
self.outbound_stamp_costs
|
||||
.get(destination_hash)
|
||||
.map(|e| e.cost)
|
||||
}
|
||||
|
||||
/// Get the propagation stamp cost for a message queued for propagation-node delivery.
|
||||
///
|
||||
/// Returns the per-message `stamp_cost` recorded on the pending message when it was enqueued.
|
||||
///
|
||||
/// Python reference: `LXMRouter.get_outbound_lxm_propagation_stamp_cost` — LXMRouter.py:1149-1156.
|
||||
/// Return the recipient stamp cost recorded on a deferred message.
|
||||
/// Despite this method's name, it reads only `pending_deferred_stamps` and
|
||||
/// does not return the separate propagation-node admission stamp target.
|
||||
pub fn get_outbound_lxm_propagation_stamp_cost(&self, message_hash: &[u8; 32]) -> Option<u8> {
|
||||
self.pending_deferred_stamps
|
||||
.get(message_hash)
|
||||
.and_then(|m| m.stamp_cost())
|
||||
}
|
||||
|
||||
/// Return whether a message or propagation transient ID has already been
|
||||
/// delivered locally.
|
||||
///
|
||||
/// Python reference: `LXMRouter.has_message` — LXMRouter.py:1667-1669.
|
||||
/// Check the local-delivery dedupe cache for a message or transient ID.
|
||||
/// Durable discard/deletion decisions can also populate it; presence does
|
||||
/// not prove a message file exists. This lookup does not check expiry.
|
||||
pub fn has_message(&self, transient_id: &PropagationTransientId) -> bool {
|
||||
self.propagation_store.is_locally_delivered(transient_id)
|
||||
}
|
||||
|
||||
/// Atomically admit one already-decoded inbound message and invoke the
|
||||
/// router callback at most once.
|
||||
///
|
||||
/// Both ordinary packet/Resource delivery and propagation download must
|
||||
/// use this actor-owned gate before any application-visible side effect.
|
||||
/// A propagation message may carry a ciphertext-derived `transient_id`
|
||||
/// distinct from its signed message hash; both identifiers are retained
|
||||
/// so a later delivery through another representation is still deduped.
|
||||
/// Mark a message ID delivered in memory and invoke the registered callback.
|
||||
/// With `allow_duplicate = false`, an ID already in the local-delivery cache
|
||||
/// returns `false`; with `true`, repeated calls may invoke the callback again.
|
||||
/// This compatibility helper does not verify the message, persist local
|
||||
/// effects or record a distinct ciphertext transient ID. Use the reservation
|
||||
/// and durable-receipt commit path for application admission.
|
||||
pub fn deliver_inbound(&mut self, message: &LxMessage, allow_duplicate: bool) -> bool {
|
||||
let message_id = message.message_id();
|
||||
if !allow_duplicate && self.propagation_store.is_locally_delivered(&message_id) {
|
||||
@@ -1172,8 +1172,10 @@ impl LxmRouter {
|
||||
true
|
||||
}
|
||||
|
||||
/// Reserve before local disk/DB work; no ticket learning, dedupe publication
|
||||
/// or callback occurs until commit. An aborted write leaves retries possible.
|
||||
/// Reserve a message ID before local disk/DB work. An existing reservation
|
||||
/// for that ID returns `None`; this does not check the delivered cache or
|
||||
/// authenticate the message. No ticket learning, dedupe publication or callback
|
||||
/// occurs here. Return the reservation to this instance to abort or commit it.
|
||||
pub fn reserve_inbound(&mut self, message: &LxMessage) -> Option<InboundReservation> {
|
||||
let message_id = message.message_id();
|
||||
if self.inbound_reservations.contains_key(&message_id) {
|
||||
@@ -1191,6 +1193,12 @@ impl LxmRouter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Complete a matching reservation after the adapter has obtained a durable
|
||||
/// receipt. Records both message and transient IDs; learns a ticket only from
|
||||
/// a matching verified message with a committed/duplicate disposition.
|
||||
/// Returns whether the new-commit delivery path ran; `false` also covers
|
||||
/// duplicates, discards and mismatched reservations. The caller establishes
|
||||
/// identity/node scope and durable effects before invoking this method.
|
||||
pub fn commit_inbound(
|
||||
&mut self,
|
||||
reservation: InboundReservation,
|
||||
@@ -1249,6 +1257,10 @@ impl LxmRouter {
|
||||
true
|
||||
}
|
||||
|
||||
/// Decode/decrypt a paper URI and pass it to [`Self::deliver_inbound`] without
|
||||
/// signature verification or durable persistence. The returned message is
|
||||
/// unverified, and a registered callback may already have run. For verified
|
||||
/// durable admission, decode separately and use the reservation/commit path.
|
||||
pub fn ingest_lxm_uri<F>(
|
||||
&mut self,
|
||||
uri: &str,
|
||||
@@ -1262,9 +1274,11 @@ impl LxmRouter {
|
||||
Ok(message)
|
||||
}
|
||||
|
||||
/// Register a router-wide callback fired on every inbound message delivery.
|
||||
/// Replace the router-wide callback used by inbound delivery/commit helpers.
|
||||
/// It runs synchronously in the calling thread; duplicate/discard behavior
|
||||
/// depends on the helper used.
|
||||
///
|
||||
/// Python reference: `LXMRouter.register_delivery_callback` — LXMRouter.py:358-359.
|
||||
/// Python reference: `LXMRouter.register_delivery_callback`.
|
||||
pub fn register_delivery_callback<F>(&mut self, callback: F)
|
||||
where
|
||||
F: Fn(&LxMessage) + Send + 'static,
|
||||
@@ -1273,9 +1287,9 @@ impl LxmRouter {
|
||||
}
|
||||
|
||||
/// Load persisted runtime state (stamp costs, tickets, dedup sets) from
|
||||
/// `state_dir`. Missing files are treated as empty state. Dedup-cache
|
||||
/// timestamps are restored as persisted so age-based expiry survives
|
||||
/// restarts.
|
||||
/// `state_dir`. Missing files are treated as empty state; other load errors
|
||||
/// propagate after any earlier fields have already been replaced. Dedup-cache
|
||||
/// timestamps are restored so age-based expiry survives restarts.
|
||||
pub fn load_state(&mut self, state_dir: &std::path::Path) -> std::io::Result<()> {
|
||||
use crate::persist;
|
||||
self.outbound_stamp_costs = persist::load_stamp_costs(state_dir)?;
|
||||
@@ -1323,8 +1337,9 @@ impl LxmRouter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Persist runtime state to `state_dir` using MessagePack. Safe to call
|
||||
/// periodically; each file is written atomically via rename.
|
||||
/// Persist runtime state to `state_dir` using MessagePack. Each file is
|
||||
/// replaced atomically; the set is not a single transaction. Serialize writes
|
||||
/// so an older snapshot cannot overwrite newer state.
|
||||
pub fn save_state(&self, state_dir: &std::path::Path) -> std::io::Result<()> {
|
||||
self.state_snapshot().save_state(state_dir)
|
||||
}
|
||||
@@ -1351,9 +1366,10 @@ impl LxmRouter {
|
||||
}
|
||||
|
||||
/// Return authoritative policies for peers that have not processed the
|
||||
/// current propagation-store generation. This is an O(peers) scheduler
|
||||
/// query; exact message eligibility is intentionally deferred to the
|
||||
/// sync task's off-loop offer preparation.
|
||||
/// current propagation-store generation. Prefers eligible alive peers; if
|
||||
/// none are alive, returns eligible unresponsive peers. Snapshots clone peer
|
||||
/// policy/handled-ID state and are sorted by peer hash. Exact message
|
||||
/// eligibility is checked during offer preparation.
|
||||
///
|
||||
/// The method does not mutate peer state, allowing a single shared sync
|
||||
/// task to accept one policy before the daemon marks that peer started.
|
||||
@@ -1385,10 +1401,11 @@ impl LxmRouter {
|
||||
true
|
||||
}
|
||||
|
||||
/// Add a peer from announce data.
|
||||
///
|
||||
/// The peer is added only when autopeer is enabled, the router is below
|
||||
/// `max_peers`, and the announce hop count is within `autopeer_maxdepth`.
|
||||
/// Add or refresh a peer from announce data. New peers count toward
|
||||
/// `max_peers`; static peers bypass autopeer and hop-depth gates.
|
||||
/// Other peers require autopeer enabled and, when hops are known, an allowed
|
||||
/// depth. Excess peering cost is refused and can remove an existing peer on
|
||||
/// a non-stale policy announce. The caller supplies authenticated, finite data.
|
||||
pub fn autopeer(&mut self, candidate: AutopeerCandidate) -> bool {
|
||||
let AutopeerCandidate {
|
||||
destination_hash,
|
||||
@@ -1540,9 +1557,9 @@ impl LxmRouter {
|
||||
|
||||
/// Mark pending propagated messages due after the configured propagation node announces.
|
||||
///
|
||||
/// Mirrors LXMF 0.9.8's propagation announce handler. The announce app_data
|
||||
/// must be a valid propagation-node announce before any retry backoff is
|
||||
/// cleared.
|
||||
/// Requires the configured destination and app data accepted by
|
||||
/// [`crate::handlers::parse_pn_announce_data`] before clearing retry backoff.
|
||||
/// The caller verifies the announce's identity and authenticity.
|
||||
pub fn trigger_outbound_for_propagation_node_announce(
|
||||
&mut self,
|
||||
destination_hash: [u8; 16],
|
||||
@@ -1576,7 +1593,8 @@ impl LxmRouter {
|
||||
self.config.max_peers = max;
|
||||
}
|
||||
|
||||
/// Propagation storage limit in kilobytes.
|
||||
/// Set the advertised per-transfer propagation limit in decimal kB.
|
||||
/// This does not set total storage capacity or update a separate node owner.
|
||||
pub fn set_propagation_limit(&mut self, limit_kb: usize) {
|
||||
self.config.propagation_limit_kb = limit_kb;
|
||||
}
|
||||
@@ -1588,7 +1606,7 @@ impl LxmRouter {
|
||||
|
||||
/// Build propagation-node announce app_data (msgpack).
|
||||
///
|
||||
/// Python reference: LXMRouter.get_propagation_node_app_data — LXMRouter.py:306-318.
|
||||
/// Python reference: LXMRouter.get_propagation_node_app_data.
|
||||
pub fn get_propagation_node_app_data(&self) -> Vec<u8> {
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
@@ -1634,9 +1652,9 @@ impl LxmRouter {
|
||||
|
||||
/// Validate a stamp, accepting a matching ticket hash as a bypass.
|
||||
///
|
||||
/// A ticket is matched by comparing the first 16 bytes of
|
||||
/// `SHA-256(ticket.token || message_id)` against the stamp prefix;
|
||||
/// otherwise falls back to PoW validation.
|
||||
/// A ticket matches only when the complete stamp equals the 16-byte
|
||||
/// truncated hash of `ticket.token || message_id`. A nonmatching stamp must
|
||||
/// be exactly 32 bytes for PoW validation; a matching prefix alone is no ticket bypass.
|
||||
pub fn validate_stamp_with_tickets(
|
||||
&self,
|
||||
message_id: &[u8; 32],
|
||||
@@ -1677,7 +1695,9 @@ impl LxmRouter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Summarise propagation-node state for a control status request.
|
||||
/// Summarise router-held propagation configuration, index and peer counters.
|
||||
/// Returns `None` when propagation is disabled. This does not query a separate
|
||||
/// live node or filesystem; the embedding runtime supplies those totals.
|
||||
///
|
||||
/// Python reference: LXMRouter.compile_stats.
|
||||
pub fn control_status(&self) -> Option<NodeStats> {
|
||||
@@ -1794,11 +1814,10 @@ impl LxmRouter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drain pending outbound messages into [`OutboundAction`]s.
|
||||
///
|
||||
/// A delivery that later fails externally (e.g. unknown destination key)
|
||||
/// should be re-queued via [`send`][Self::send] with `delivery_attempts`
|
||||
/// incremented.
|
||||
/// Move eligible outbound messages into [`OutboundAction`]s, subject to
|
||||
/// retry times and the per-call processing limit. Other messages remain queued.
|
||||
/// The caller owns emitted deliveries, including proof tracking and retries;
|
||||
/// requeue retryable failures through [`Self::try_send`] after updating attempts.
|
||||
#[tracing::instrument(
|
||||
level = "debug",
|
||||
name = "router.process_outbound",
|
||||
@@ -1930,12 +1949,9 @@ impl LxmRouter {
|
||||
actions
|
||||
}
|
||||
|
||||
/// Process outbound messages while keeping Direct deliveries in the router
|
||||
/// queue until LinkDeliveryManager reports a terminal result.
|
||||
///
|
||||
/// This mirrors Python's `LXMRouter.process_outbound` ownership model for
|
||||
/// Direct messages while preserving [`Self::process_outbound`] for older
|
||||
/// embedders that still take ownership of Direct messages themselves.
|
||||
/// Plan Direct deliveries while retaining their originals in the router queue.
|
||||
/// The caller executes plans, reports terminal Link results to the router and
|
||||
/// handles non-Direct actions. This method does not poll a Link manager itself.
|
||||
pub fn process_outbound_with_direct<F>(&mut self, mut direct_input: F) -> Vec<OutboundAction>
|
||||
where
|
||||
F: FnMut(&LxMessage, f64) -> DirectDeliveryPlanInput,
|
||||
@@ -2096,10 +2112,11 @@ impl LxmRouter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Send single-packet opportunistic actions via the configured transport.
|
||||
///
|
||||
/// Direct and Propagated actions require a Reticulum link and are handled by
|
||||
/// `LinkDeliveryManager` / propagation helpers in the embedding runtime.
|
||||
/// Compatibility executor without a destination encryptor. With transport
|
||||
/// configured, Opportunistic actions fail encryption and are requeued.
|
||||
/// Direct/Propagated actions are consumed without delivery; without transport,
|
||||
/// all supplied actions are discarded. Handle delivery actions in the embedder
|
||||
/// or use [`Self::execute_actions_with_encryptor`] for Opportunistic work.
|
||||
pub fn execute_actions(&mut self, actions: Vec<OutboundAction>) {
|
||||
self.execute_actions_with_encryptor(actions, |dest_hash, _plaintext| {
|
||||
Err(MessageError::PackFailed(format!(
|
||||
@@ -2115,6 +2132,12 @@ impl LxmRouter {
|
||||
/// Python encrypts Opportunistic LXMF packet payloads with the recipient
|
||||
/// destination identity before handing bytes to Reticulum. Core cannot
|
||||
/// infer destination keys, so embeddings must provide the encryptor.
|
||||
///
|
||||
/// This consumes the action list. Direct/Propagated actions are discarded,
|
||||
/// and without a configured transport all actions are discarded. Dispatch
|
||||
/// those methods separately before calling. Successful packet enqueueing does
|
||||
/// not retain a message for delivery-proof tracking; the embedding runtime
|
||||
/// must own that lifecycle when delivery confirmation is required.
|
||||
pub fn execute_actions_with_encryptor<F>(
|
||||
&mut self,
|
||||
actions: Vec<OutboundAction>,
|
||||
@@ -2204,7 +2227,10 @@ impl LxmRouter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Advance one scheduler tick: drain outbound, then run periodic jobs.
|
||||
/// Advance deferred stamps and periodic jobs using the compatibility executor.
|
||||
/// Direct messages stay queued; Propagated actions are consumed without delivery,
|
||||
/// and Opportunistic work lacks destination encryption. This is not a complete
|
||||
/// delivery driver; use explicit action processing in an embedding runtime.
|
||||
pub fn tick(&mut self) {
|
||||
self.processing_count += 1;
|
||||
|
||||
@@ -2217,8 +2243,9 @@ impl LxmRouter {
|
||||
self.run_periodic_jobs();
|
||||
}
|
||||
|
||||
/// Advance one scheduler tick using caller-supplied destination encryption
|
||||
/// for Opportunistic packet actions.
|
||||
/// Advance stamps, Opportunistic actions and periodic jobs with destination
|
||||
/// encryption. Direct messages stay queued; Propagated actions are consumed
|
||||
/// without delivery. For other methods or proof tracking, drive actions explicitly.
|
||||
pub fn tick_with_encryptor<F>(&mut self, encrypt_fn: F)
|
||||
where
|
||||
F: FnMut([u8; 16], &[u8]) -> Result<Vec<u8>, MessageError>,
|
||||
@@ -2234,13 +2261,11 @@ impl LxmRouter {
|
||||
self.run_periodic_jobs();
|
||||
}
|
||||
|
||||
/// Drive the periodic job machinery for embedders that process outbound
|
||||
/// themselves via `process_outbound_with_direct` instead of calling
|
||||
/// [`Self::tick`]. Without this the jobloop counters never advance and
|
||||
/// transient-cache cleaning, store culls, and peer rotation never run.
|
||||
/// Time-gated to Python's `PROCESSING_INTERVAL` so callers may invoke it
|
||||
/// every loop pass regardless of their tick rate (lxmd: 4 s, Ratspeak:
|
||||
/// 500 ms) without skewing the jobloop cadences.
|
||||
/// Drive periodic jobs when the embedder processes outbound actions itself.
|
||||
/// Advances the job counter at most once per `0.9 * PROCESSING_INTERVAL`
|
||||
/// wall-clock seconds; missed intervals are not replayed. Jobs clean transient
|
||||
/// caches/throttles and, when propagation is enabled, cull the router index
|
||||
/// and rotate peers. This does not drive outbound work or a separate node store.
|
||||
pub fn run_jobs_tick(&mut self) {
|
||||
let now = now_f64();
|
||||
if now - self.last_jobs_tick < PROCESSING_INTERVAL as f64 * 0.9 {
|
||||
@@ -2306,7 +2331,8 @@ pub enum OutboundAction {
|
||||
message: LxMessage,
|
||||
prop_hash: [u8; 16],
|
||||
},
|
||||
/// Small enough for single-packet delivery.
|
||||
/// Opportunistic packet action. Final encryption and packet-size admission
|
||||
/// remain the executor's responsibility.
|
||||
DeliverOpportunistic {
|
||||
message: LxMessage,
|
||||
dest_hash: [u8; 16],
|
||||
|
||||
@@ -8,8 +8,10 @@
|
||||
//! workblock. Only the expand-round count differs per kind (see
|
||||
//! `STAMP_WORKBLOCK_EXPAND_ROUNDS{,_PN,_PEERING}` in constants.rs).
|
||||
//!
|
||||
//! Validity check: `SHA-256(workblock || stamp)` must have >= `cost` leading
|
||||
//! zero bits. Matches Python's `int.from_bytes(result) <= (1 << (256-cost))`.
|
||||
//! Rust validation requires at least `cost` leading zero bits in
|
||||
//! `SHA-256(workblock || stamp)`. Python uses an inclusive numeric threshold,
|
||||
//! `result <= 1 << (256 - cost)`; the exact equality boundary differs for
|
||||
//! nonzero cost.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
@@ -80,11 +82,10 @@ pub fn stamp_valid(stamp: &[u8; 32], cost: u8, workblock: &[u8]) -> bool {
|
||||
stamp_value(workblock, stamp) >= cost as u32
|
||||
}
|
||||
|
||||
/// Give-up bound for stamp searches: 64× the expected `2^cost` work, so the
|
||||
/// failure probability for an honest cost is ~e^-64 while a hostile cost can
|
||||
/// no longer pin a thread forever. Costs ≥ 58 (cap would overflow u64) are
|
||||
/// unsatisfiable on real hardware and fail immediately. Python has no cap and
|
||||
/// blocks until success — deliberate divergence, see fix-registry.
|
||||
/// Attempt budget for [`generate_stamp`] and [`generate_stamp_cancellable`]:
|
||||
/// `64 * 2^cost`. Returns `None` for costs at least 58 because the budget would
|
||||
/// overflow `u64`. This limits attempts, not elapsed time. Deferred stamp
|
||||
/// workers use explicit cancellation and do not use this budget.
|
||||
pub fn stamp_iteration_cap(cost: u8) -> Option<u64> {
|
||||
if cost >= 58 {
|
||||
return None;
|
||||
@@ -94,13 +95,15 @@ pub fn stamp_iteration_cap(cost: u8) -> Option<u64> {
|
||||
|
||||
/// Single-threaded brute-force stamp search. Bounded by
|
||||
/// [`stamp_iteration_cap`]; returns `None` when the cap is exhausted or the
|
||||
/// cost is unsatisfiable.
|
||||
/// requested cost has no supported iteration budget.
|
||||
pub fn generate_stamp(material: &[u8], cost: u8, expand_rounds: usize) -> Option<([u8; 32], u32)> {
|
||||
generate_stamp_cancellable(material, cost, expand_rounds, &AtomicBool::new(false))
|
||||
}
|
||||
|
||||
/// Synchronous bounded worker entry. Cancellation revokes work without claiming
|
||||
/// that an async task abort stopped this closure or released its byte owners.
|
||||
/// Synchronous search with the [`stamp_iteration_cap`] attempt budget.
|
||||
/// Checks cancellation before workblock construction and every 1,000 attempts;
|
||||
/// workblock construction itself is not interrupted. Run on a blocking worker
|
||||
/// when called from async code.
|
||||
pub fn generate_stamp_cancellable(
|
||||
material: &[u8],
|
||||
cost: u8,
|
||||
@@ -179,7 +182,7 @@ pub fn validate_stamp(
|
||||
stamp_valid(stamp, cost, &workblock)
|
||||
}
|
||||
|
||||
/// Python reference: LXStamper.py:48-51 (`validate_peering_key`).
|
||||
/// Python reference: `LXStamper.validate_peering_key`.
|
||||
///
|
||||
/// `peering_id` = self_identity_hash || remote_identity_hash (32 bytes typical).
|
||||
/// Uses `STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING` for workblock generation.
|
||||
@@ -191,7 +194,7 @@ pub fn validate_peering_key(peering_id: &[u8], peering_key: &[u8; 32], target_co
|
||||
stamp_valid(peering_key, target_cost, &workblock)
|
||||
}
|
||||
|
||||
/// Python reference: LXStamper.py:53-65 (`validate_pn_stamp`).
|
||||
/// Python reference: `LXStamper.validate_pn_stamp`.
|
||||
///
|
||||
/// `transient_data = lxm_data || stamp` where stamp is the last 32 bytes.
|
||||
/// Uses `STAMP_WORKBLOCK_EXPAND_ROUNDS_PN` for workblock generation.
|
||||
@@ -222,7 +225,9 @@ pub fn validate_pn_stamp(transient_data: &[u8], target_cost: u8) -> Option<Propa
|
||||
Some((transient_id, lxm_data.to_vec(), value, stamp))
|
||||
}
|
||||
|
||||
/// Cancellation handle for a deferred PoW task.
|
||||
/// Cooperative cancellation handle for a deferred PoW task.
|
||||
/// Call `cancel()` to request cancellation; dropping this handle or the result
|
||||
/// receiver does not stop the worker.
|
||||
#[derive(Clone)]
|
||||
pub struct DeferredStampHandle {
|
||||
cancel: Arc<AtomicBool>,
|
||||
@@ -247,6 +252,11 @@ pub enum DeferredStampResult {
|
||||
/// Spawn a deferred stamp-generation task on a blocking worker.
|
||||
///
|
||||
/// Returns a cancellation handle and a oneshot receiver for the result.
|
||||
/// The search has no iteration cap; see [`spawn_deferred_stamp_on`] for its
|
||||
/// cancellation contract.
|
||||
///
|
||||
/// # Panics
|
||||
/// Panics when called outside a Tokio runtime.
|
||||
#[tracing::instrument(
|
||||
level = "debug",
|
||||
name = "stamper.compute",
|
||||
@@ -269,8 +279,13 @@ pub fn spawn_deferred_stamp(
|
||||
spawn_deferred_stamp_on(&handle, message_id, cost, expand_rounds)
|
||||
}
|
||||
|
||||
/// Handle-explicit variant: callable from `spawn_blocking` threads (no
|
||||
/// implicit runtime context) — the manager tick runs there.
|
||||
/// Spawn on an explicit runtime handle, without requiring a current runtime
|
||||
/// context on the calling thread.
|
||||
///
|
||||
/// After workblock construction, a nonzero-cost search checks cancellation
|
||||
/// between batches of 1,000 attempts and runs until success or cancellation.
|
||||
/// It does not apply [`stamp_iteration_cap`]. Keep the cancellation handle and
|
||||
/// call `cancel()` when abandoning the result.
|
||||
pub fn spawn_deferred_stamp_on(
|
||||
runtime: &tokio::runtime::Handle,
|
||||
message_id: [u8; 32],
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! LXMF Propagation Sync Protocol -- Offer/Get between peers.
|
||||
//! Propagation offer/response values and local sync-session bookkeeping.
|
||||
//!
|
||||
//! The network task in [`crate::propagation_sync`] follows this exchange:
|
||||
//!
|
||||
//! 1. Peer A opens a Link to Peer B.
|
||||
//! 2. A sends Offer { transient_ids }.
|
||||
//! 2. A sends `/offer` with `[peering_key, transient_ids]`.
|
||||
//! 3. B responds with one of:
|
||||
//! - `true`: peer wants ALL offered messages.
|
||||
//! - `false`: peer already has everything.
|
||||
@@ -9,7 +11,11 @@
|
||||
//! - integer error code: 0xF0 NoIdentity, 0xF1 NoAccess, 0xF3 InvalidKey,
|
||||
//! 0xF4 InvalidData, 0xF5 InvalidStamp, 0xF6 Throttled.
|
||||
//! 4. A sends requested messages via Resource transfer.
|
||||
//! 5. B stores and sends proof.
|
||||
//! 5. Resource proof reports transport completion; application admission is a
|
||||
//! separate responsibility.
|
||||
//!
|
||||
//! [`SyncGet`] and [`SyncSession`] are local helpers. They do not implement the
|
||||
//! authenticated `/offer` admission policy in [`crate::propagation_admission`].
|
||||
//!
|
||||
//! Python reference: LXMPeer.py (offer_response).
|
||||
|
||||
@@ -23,10 +29,13 @@ use crate::types::PropagationTransientId;
|
||||
pub const SYNC_MSG_OFFER: u16 = 0x0001;
|
||||
pub const SYNC_MSG_GET: u16 = 0x0002;
|
||||
|
||||
/// Offer message: "I have these messages".
|
||||
/// Local offer data: a peering stamp and the transient IDs available for sync.
|
||||
///
|
||||
/// Python wire: `[peering_key, unhandled_ids]`. `peering_key` is the raw stamp
|
||||
/// bytes (Python `self.peering_key[0]`), required by the receiver for access control.
|
||||
/// The `/offer` request uses `[peering_key, unhandled_ids]` with a MessagePack
|
||||
/// binary key and binary IDs. This type's `MessageBase::pack` uses the default
|
||||
/// Serde representation, which encodes its byte vectors as integer arrays.
|
||||
/// [`crate::propagation_sync`] constructs the required binary wire values
|
||||
/// explicitly when sending the request.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SyncOffer {
|
||||
pub peering_key: Vec<u8>,
|
||||
@@ -66,7 +75,8 @@ impl MessageBase for SyncOffer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get message: "Send me these messages".
|
||||
/// Local wanted-ID list used by [`SyncSession`]. This wrapper is not the
|
||||
/// `/offer` wire response; use [`OfferResponse`] for that response.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SyncGet {
|
||||
pub wanted_ids: Vec<Vec<u8>>,
|
||||
@@ -103,7 +113,7 @@ impl MessageBase for SyncGet {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parsed offer response from a propagation node. Python: LXMPeer.py:396-439.
|
||||
/// Parsed offer response from a propagation node. See Python `LXMPeer.offer_response`.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum OfferResponse {
|
||||
WantAll,
|
||||
@@ -231,7 +241,8 @@ impl SyncSession {
|
||||
}
|
||||
}
|
||||
|
||||
/// Process a received offer; returns a SyncGet for IDs we don't have.
|
||||
/// Select 32-byte IDs absent from the local store and enter Receiving state.
|
||||
/// This helper does not validate the peering key or enforce admission policy.
|
||||
pub fn process_offer(&mut self, offer: &SyncOffer, our_store: &PropagationStore) -> SyncGet {
|
||||
let wanted: Vec<Vec<u8>> = offer
|
||||
.transient_ids
|
||||
|
||||
@@ -47,7 +47,9 @@ impl Ticket {
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
/// Decode a signed inbound Python-compatible ticket field.
|
||||
/// Decode a Python-compatible ticket field with a finite future expiry and
|
||||
/// a 16-byte token. The caller must authenticate the containing message and
|
||||
/// bind `destination_hash` to its sender before storing the learned ticket.
|
||||
pub fn decode_field(destination_hash: [u8; 16], encoded: &[u8], now: f64) -> Option<Self> {
|
||||
let mut cursor = std::io::Cursor::new(encoded);
|
||||
let value = rmpv::decode::read_value(&mut cursor).ok()?;
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::constants::DESTINATION_LENGTH;
|
||||
/// Reticulum destination hash, as carried in LXMF wire messages.
|
||||
pub type DestinationHash = [u8; DESTINATION_LENGTH];
|
||||
|
||||
/// Reticulum identity hash, used for peer and ticket identity binding.
|
||||
/// Reticulum identity hash. Ticket stores use delivery destination hashes instead.
|
||||
pub type IdentityHash = [u8; DESTINATION_LENGTH];
|
||||
|
||||
/// Canonical LXMF message id / SHA-256 digest.
|
||||
|
||||
@@ -5,7 +5,7 @@ publish = false
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
license-file.workspace = true
|
||||
autobins = false
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! LXMF daemon configuration and runner.
|
||||
//! LXMF daemon configuration and inbound-hook helpers.
|
||||
//!
|
||||
//! Python reference: LXMF/Utilities/lxmd.py.
|
||||
|
||||
@@ -11,9 +11,8 @@ use rns_runtime::config::{Config, ConfigSection};
|
||||
|
||||
/// Normalized view of Python `lxmd.apply_config()` behavior.
|
||||
///
|
||||
/// This intentionally mirrors Python's active_configuration keys and units.
|
||||
/// It is kept separate from [`DaemonConfig`] while the daemon still has legacy
|
||||
/// Rust fields and storage layout.
|
||||
/// Values retain Python's configuration units before conversion into
|
||||
/// [`DaemonConfig`], including decimal KB/MB and announce intervals in seconds.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct PythonLxmdConfig {
|
||||
pub display_name: String,
|
||||
@@ -190,7 +189,7 @@ pub struct DaemonConfig {
|
||||
pub enforce_stamps: bool,
|
||||
pub message_storage_limit: Option<usize>,
|
||||
pub from_static_only: bool,
|
||||
/// Max accepted inbound delivery transfer size in KB. Python reference:
|
||||
/// Max accepted inbound delivery transfer size in decimal KB. Python reference:
|
||||
/// `delivery_transfer_max_accepted_size` in `lxmd.py`.
|
||||
pub delivery_transfer_max_accepted_size: f64,
|
||||
}
|
||||
@@ -407,8 +406,9 @@ pub fn execute_on_inbound(command: &str, message_path: &str) -> std::io::Result<
|
||||
execute_on_inbound_with_event(command, message_path, "")
|
||||
}
|
||||
|
||||
/// Durable propagation outbox events may replay after a crash. Hooks can use
|
||||
/// this stable identifier for their own idempotency boundary.
|
||||
/// Execute an inbound hook with `event_id` in the `LXMF_EVENT_ID` environment
|
||||
/// variable when the identifier is nonempty. Durable propagation outbox events
|
||||
/// may replay after a crash; the hook can use the identifier to deduplicate them.
|
||||
pub fn execute_on_inbound_with_event(
|
||||
command: &str,
|
||||
message_path: &str,
|
||||
@@ -523,9 +523,9 @@ fn split_command_line(command: &str) -> std::io::Result<Vec<String>> {
|
||||
Ok(parts)
|
||||
}
|
||||
|
||||
/// Persist a received message before invoking the configured hook. Keeping
|
||||
/// both operations in one blocking job prevents the hook from racing the
|
||||
/// atomic file write and keeps process execution off the async daemon loop.
|
||||
/// Persist a received message, then invoke the configured hook after the write
|
||||
/// succeeds. This function blocks; async callers must run it on a blocking
|
||||
/// worker. A hook error is returned after the message has already been saved.
|
||||
pub fn persist_inbound_and_execute(
|
||||
message_path: &std::path::Path,
|
||||
packed: &[u8],
|
||||
|
||||
@@ -79,11 +79,12 @@ pub struct Args {
|
||||
#[arg(long)]
|
||||
pub exampleconfig: bool,
|
||||
|
||||
/// Run as a system service (no interactive output).
|
||||
/// Default to warning-level logging for service use; -v/-q override this.
|
||||
/// The process remains in the foreground.
|
||||
#[arg(short = 's', long)]
|
||||
pub service: bool,
|
||||
|
||||
/// Display local node status and exit.
|
||||
/// Query node status over Reticulum and exit (use `--remote` for another node).
|
||||
#[arg(long)]
|
||||
pub status: bool,
|
||||
|
||||
@@ -107,7 +108,7 @@ pub struct Args {
|
||||
#[arg(short = 'r', long, value_name = "DEST_HASH")]
|
||||
pub remote: Option<String>,
|
||||
|
||||
/// Identity path used for remote query operations.
|
||||
/// Identity path used for local or remote control queries.
|
||||
#[arg(long, value_name = "PATH")]
|
||||
pub identity: Option<PathBuf>,
|
||||
|
||||
@@ -115,22 +116,24 @@ pub struct Args {
|
||||
#[arg(long, num_args = 1..=2, value_names = ["DEST_HASH", "CONTENT"])]
|
||||
pub send: Option<Vec<String>>,
|
||||
|
||||
/// Read outgoing --send content from a UTF-8 file instead of argv.
|
||||
/// Read outgoing `--send` content from a UTF-8 file instead of argv.
|
||||
#[arg(long, value_name = "PATH")]
|
||||
pub send_file: Option<PathBuf>,
|
||||
|
||||
/// Delivery method for --send.
|
||||
/// Delivery method for `--send`.
|
||||
#[arg(long, value_enum, default_value_t = SendMethod::Opportunistic)]
|
||||
pub send_method: SendMethod,
|
||||
|
||||
/// Link/resource completion timeout for --send.
|
||||
/// Nominal wait in seconds for each `--send` completion phase. Each poll
|
||||
/// includes a one-second sleep; discovery and work between polls add time.
|
||||
#[arg(long, default_value_t = 90)]
|
||||
pub send_timeout_secs: u64,
|
||||
|
||||
/// Attach custom LXMF fields to the outgoing --send message. Accepts a
|
||||
/// JSON object mapping field-id -> base64(value). Example:
|
||||
/// --send-fields-json '{"1":"aGVsbG8=","42":"AAECA/8="}'
|
||||
/// Only meaningful alongside --send.
|
||||
/// Attach binary LXMF fields to `--send`. Accepts a JSON object mapping
|
||||
/// decimal field IDs (0–255) to base64-encoded bytes. Example:
|
||||
/// `--send-fields-json '{"200":"aGVsbG8=","201":"AAECA/8="}'`.
|
||||
/// Choose IDs agreed with the receiving application. This option does not
|
||||
/// construct native structured MessagePack fields. Only used with `--send`.
|
||||
#[arg(long, value_name = "JSON")]
|
||||
pub send_fields_json: Option<String>,
|
||||
}
|
||||
@@ -203,7 +206,8 @@ autopeer_maxdepth = 6
|
||||
# Let configured static peers bypass sequential validation and inbound limits.
|
||||
# static_peers_bypass_sequential = yes
|
||||
|
||||
# Maximum concurrent inbound propagation sync transfers.
|
||||
# Threshold for new inbound propagation sync offers. Already accepted offers
|
||||
# and static-peer bypass can exceed this value.
|
||||
# max_inbound_syncs = 3
|
||||
|
||||
# message_storage_limit = 500
|
||||
@@ -253,9 +257,9 @@ loglevel = 4
|
||||
}
|
||||
|
||||
/// Parse a plaintext destination-hash list: one 16-byte hex value per line.
|
||||
/// Missing files return empty. Like Python `lxmd.py`, this accepts only raw
|
||||
/// 32-byte hex lines; comments and inline comments are ignored only because
|
||||
/// their raw line length is not exactly 32 bytes.
|
||||
/// Read errors return an empty list. Each line must contain exactly 32 ASCII
|
||||
/// hexadecimal characters; a trailing CR is allowed for CRLF files. Whitespace
|
||||
/// and comments are not stripped, so lines containing them are skipped.
|
||||
///
|
||||
/// Python reference: `lxmd.py` reads `ignored` / `allowed` from the config dir.
|
||||
pub fn load_hash_list(path: &Path) -> Vec<[u8; 16]> {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Pure `lxmd` runtime helpers extracted from the binary.
|
||||
//! `lxmd` path selection, control-command preflight, and status formatting.
|
||||
//!
|
||||
//! This module keeps daemon path handling and other pure helpers out of the
|
||||
//! binary so CLI behavior can be tested directly.
|
||||
//! Path selection reads environment variables and checks the filesystem;
|
||||
//! these helpers do not start the daemon runtime.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
|
||||
@@ -70,9 +70,14 @@ def verify(directory: Path, tag: str) -> None:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--tag", required=True)
|
||||
parser.add_argument("--directory", type=Path, required=True)
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Check the three release archives, then write SHA256SUMS."
|
||||
)
|
||||
parser.add_argument("--tag", required=True, help="release version in vX.Y.Z form, as used in archive names")
|
||||
parser.add_argument(
|
||||
"--directory", type=Path, required=True,
|
||||
help="directory containing only the three platform archives; SHA256SUMS is written here after validation",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
verify(args.directory, args.tag)
|
||||
|
||||
|
||||
@@ -211,10 +211,10 @@ def check_candidate_tag(tag: str, version: str) -> None:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
tags = parser.add_mutually_exclusive_group()
|
||||
tags.add_argument("--release-tag")
|
||||
tags.add_argument("--candidate-tag")
|
||||
tags.add_argument("--release-tag", help="also verify the existing annotated vX.Y.Z tag matches the workspace version and HEAD")
|
||||
tags.add_argument("--candidate-tag", help="also verify vX.Y.Z matches the workspace version and has no local tag yet")
|
||||
args = parser.parse_args()
|
||||
|
||||
version, reticulum_version = check_packages(metadata())
|
||||
|
||||
@@ -274,10 +274,15 @@ def render_snapshot(
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--metadata-only", action="store_true")
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Compare current public APIs with the stored snapshots, or refresh them after review."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--metadata-only", action="store_true",
|
||||
help="validate metadata, package inventory and stored snapshot hashes without generating API output; incompatible with --update",
|
||||
)
|
||||
parser.add_argument("--update", action="store_true",
|
||||
help="refresh snapshots from the working tree to commit alongside source changes")
|
||||
help="regenerate snapshots and update their counts/hashes in api/stability.json; review the diff before committing")
|
||||
parser.add_argument("--snapshot-source-commit",
|
||||
help="optional HEAD guard for --update; includes uncommitted source changes")
|
||||
args = parser.parse_args()
|
||||
|
||||
@@ -122,12 +122,14 @@ def render_contract() -> str:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Compare current library Cargo metadata with api/snapshots/manifest-contract.json."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--print",
|
||||
action="store_true",
|
||||
dest="print_contract",
|
||||
help="print the current canonical contract for reviewed application",
|
||||
help="print current Cargo contract JSON instead of comparing it with the saved snapshot",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
rendered = render_contract()
|
||||
|
||||
Reference in new issue
Block a user