Initial commit: v0.9.0 release

This commit is contained in:
DeFiDude committed 2026-05-06 02:32:54 -06:00
commit 70cdc99d57
178 files changed
+93545

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
permissions:
contents: read
jobs:
test:
name: Test (${{ matrix.os }})
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Install system deps (Linux)
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- name: Test (default features)
run: cargo test --workspace
- name: Test BLE interface features (Linux)
if: runner.os == 'Linux'
run: cargo test -p rns-interface --features ble,ble_peer
lint:
name: Lint
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy, rustfmt
- name: Install system deps
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- run: cargo fmt --all -- --check
- run: cargo clippy --workspace --all-targets -- -D warnings
- run: cargo clippy -p rns-interface --features ble,ble_peer --all-targets -- -D warnings
+99
View File
@@ -0,0 +1,99 @@
name: Release
on:
push:
tags:
- "v*"
workflow_dispatch:
inputs:
tag_name:
description: "Release tag to create or update"
required: true
permissions:
contents: read
env:
RELEASE_TAG: ${{ github.event.inputs.tag_name || github.ref_name }}
PACKAGE_ROOT: rsReticulum
RETICULUM_BINS: rnsd-rs rnstatus-rs rnpath-rs rnid-rs rnprobe-rs rncp-rs rnsh-rs rnodeconf-rs
jobs:
build:
name: Build ${{ matrix.artifact_suffix }}
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
artifact_suffix: linux-x86_64
archive: tar.gz
- os: macos-latest
artifact_suffix: macos
archive: tar.gz
- os: windows-latest
artifact_suffix: windows-x86_64
archive: zip
runs-on: ${{ matrix.os }}
env:
ARCHIVE_NAME: rsReticulum-${{ github.event.inputs.tag_name || github.ref_name }}-${{ matrix.artifact_suffix }}
steps:
- uses: actions/checkout@v4
with:
ref: ${{ env.RELEASE_TAG }}
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Install system deps (Linux)
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- name: Build release binaries
run: cargo build -p rns-tools --release --bins
- name: Stage archive contents
shell: bash
run: |
set -euo pipefail
mkdir -p "dist/${PACKAGE_ROOT}/bin"
for bin in ${RETICULUM_BINS}; do
if [[ "${RUNNER_OS}" == "Windows" ]]; then
cp "target/release/${bin}.exe" "dist/${PACKAGE_ROOT}/bin/${bin}.exe"
else
cp "target/release/${bin}" "dist/${PACKAGE_ROOT}/bin/${bin}"
fi
done
cp README.md LICENSE "dist/${PACKAGE_ROOT}/"
- name: Create tar archive
if: runner.os != 'Windows'
shell: bash
run: tar -czf "${ARCHIVE_NAME}.tar.gz" -C dist "${PACKAGE_ROOT}"
- name: Create zip archive
if: runner.os == 'Windows'
shell: pwsh
run: Compress-Archive -Path "dist/${env:PACKAGE_ROOT}" -DestinationPath "${env:ARCHIVE_NAME}.zip" -Force
- uses: actions/upload-artifact@v4
with:
name: ${{ env.ARCHIVE_NAME }}
path: |
*.tar.gz
*.zip
if-no-files-found: error
publish:
name: Publish GitHub release
needs: build
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/download-artifact@v4
with:
path: release-assets
merge-multiple: true
- name: Generate checksums
working-directory: release-assets
run: sha256sum * > SHA256SUMS
- uses: softprops/action-gh-release@v2
with:
tag_name: ${{ env.RELEASE_TAG }}
prerelease: true
files: release-assets/*
+9
View File
@@ -0,0 +1,9 @@
/target/
*.swp
.DS_Store
__pycache__/
*.pyc
/interop_artifacts/
/rust_artifacts/
proptest-regressions/
/tools/
Generated
+2826
View File
File diff suppressed because it is too large. Load diff
+89
View File
@@ -0,0 +1,89 @@
[workspace]
resolver = "2"
members = [
"crates/rns-crypto",
"crates/rns-wire",
"crates/rns-identity",
"crates/rns-transport",
"crates/rns-link",
"crates/rns-protocol",
"crates/rns-interface",
"crates/rns-runtime",
"crates/rns-tools",
"crates/rns-ratkey",
]
[workspace.package]
version = "0.9.0"
edition = "2024"
license = "AGPL-3.0-or-later"
rust-version = "1.85"
[workspace.dependencies]
# Crypto
x25519-dalek = { version = "2", features = ["static_secrets"] }
ed25519-dalek = { version = "2", features = ["hazmat", "rand_core"] }
aes = "0.8"
cbc = { version = "0.1", features = ["alloc"] }
hkdf = "0.12"
hmac = "0.12"
sha2 = "0.10"
subtle = "2"
zeroize = { version = "1", features = ["derive"] }
rand = "0.8"
rand_core = { version = "0.6", features = ["getrandom"] }
# Encoding
base64 = "0.22"
# Serialization
rmp-serde = "1"
rmpv = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# Async
tokio = { version = "1", features = ["full"] }
# Compression
bzip2 = "0.5"
# Serial
serialport = "4"
# BLE
btleplug = "0.11"
# Networking
if-addrs = "0.13"
socket2 = { version = "0.5", features = ["all"] }
# CLI
clap = { version = "4", features = ["derive"] }
# Logging
tracing = "0.1"
tracing-subscriber = "0.3"
# Error handling
thiserror = "2"
# Misc
hex = "0.4"
byteorder = "1"
bytes = "1"
nix = { version = "0.29", features = ["term", "fs"] }
# Testing
proptest = "1"
# Workspace crates
rns-crypto = { path = "crates/rns-crypto", default-features = false }
rns-wire = { path = "crates/rns-wire", default-features = false }
rns-identity = { path = "crates/rns-identity" }
rns-transport = { path = "crates/rns-transport" }
rns-link = { path = "crates/rns-link" }
rns-protocol = { path = "crates/rns-protocol" }
rns-interface = { path = "crates/rns-interface" }
rns-runtime = { path = "crates/rns-runtime" }
rns-ratkey = { path = "crates/rns-ratkey" }
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
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.
Preamble
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.
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.
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.
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.
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 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/>.
+245
View File
@@ -0,0 +1,245 @@
<div align="center">
# rsReticulum
**A Rust implementation of Reticulum.**
[![License: AGPL-3.0-or-later](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue.svg)](LICENSE)
[![Rust 1.85+](https://img.shields.io/badge/rust-1.85%2B-orange.svg)](https://www.rust-lang.org)
[![Reticulum 1.2.2](https://img.shields.io/badge/target-Reticulum%201.2.2-success.svg)](https://reticulum.network/)
[![Status](https://img.shields.io/badge/status-experimental-yellow.svg)](#feature-status)
[Reticulum Manual](https://reticulum.network/manual/) |
[Ratspeak](https://github.com/ratspeak/Ratspeak) |
[rsLXMF](https://github.com/ratspeak/rsLXMF) |
[Reticulum](https://github.com/markqvist/Reticulum)
</div>
---
rsReticulum is a Rust implementation of Reticulum. This is not a fork of
Reticulum; it is Reticulum written in a different language, focused on staying
interoperable. It is not the source-of-truth implementation, do not treat it as one.
Commands are intentionally namespaced for Rust with `*-rs` command names, so
rsReticulum can live beside other Reticulum tools on `PATH` without worry.
## Contents
- [Build It](#build-it)
- [Tool Usage](#tool-usage)
- [Configuration](#configuration)
- [Interface Support](#interface-support)
- [Compatibility Notes](#compatibility-notes)
- [Contributing](#contributing)
- [License](#license)
## Build It
### macOS
Install Rust with `rustup`, then install Apple's command-line build tools:
```bash
xcode-select --install
```
Build the tools:
```bash
cd rsReticulum
cargo build --release
```
### Linux, Raspberry Pi, and VPS Hosts
##### Install Rust with `rustup`, then install the needed packages:
Debian, Ubuntu, and Raspberry Pi OS:
```bash
sudo apt update
sudo apt install -y build-essential pkg-config libudev-dev
```
Fedora:
```bash
sudo dnf install gcc make pkgconf-pkg-config systemd-devel
```
Arch:
```bash
sudo pacman -S --needed base-devel pkgconf systemd
```
##### Build the tools:
```bash
cd rsReticulum
cargo build --release
```
### Windows
Install Rust with the MSVC toolchain. If Rust or Cargo asks for Visual Studio
Build Tools, install the "Desktop development with C++" workload.
Build from PowerShell:
```powershell
cd rsReticulum
cargo build --release
```
After the build, use the commands below with `./target/release/<tool>` on
macOS/Linux or `.\target\release\<tool>.exe` on Windows.
## Tool Usage
The `rns-tools` crate builds Rust-namespaced Reticulum utilities:
| Binary | Purpose |
| --- | --- |
| rnsd-rs | Shared Reticulum daemon. Owns interfaces and local control sockets. |
| rnstatus-rs | Interface, announce, path, link, and aggregate status. |
| rnpath-rs | Path lookup, path table inspection, rates, drops, and blackhole actions. |
| rnid-rs | Identity generation, inspection, signing, verification, encryption, decryption, and export. |
| rnprobe-rs | Destination probe utility with loss and round-trip reporting. |
| rncp-rs | File transfer utility with send, listen, and authenticated fetch modes. |
| rnodeconf-rs | RNode inspection, safe configuration, EEPROM backup, and trust utility. |
| rnsh-rs | Reticulum shell listener/client. |
#### Commands:
```text
rnsd-rs [-c CONFIG_DIR] [-v|-q]... [--service] [--exampleconfig] [--version]
rnstatus-rs [--all] [--sort rate|traffic|rx|tx|rxs|txs|announces|arx|atx|held]
[--reverse] [--announce-stats] [--link-stats] [--totals] [--json]
[--discovered|-D] [-m [-I SECONDS]] [FILTER]
[-R <transport_hash> -i <identity_file>]
rnpath-rs [--table|--rates] [destination_hash] [--max HOPS]
rnpath-rs <destination_hash>
rnprobe-rs [-s SIZE] [-n COUNT] [-t TIMEOUT] [-w WAIT] [--json] <destination_hash>
rnid-rs generate|show|sign|verify|encrypt|decrypt|export ...
rncp-rs <file> <destination_hash>
rncp-rs -l [-b SECONDS] [-s DEST_DIR] [-a <allowed_hash>]...
rncp-rs -l -F [-j <jail_dir>] [-a <allowed_hash>|-n]...
rncp-rs -f <destination_hash> <remote_path> [-s DEST_DIR]
```
Add the release `bin/` directory or `target/release` to `PATH` if
you want to call them without a path prefix.
`rncp-rs` follows the established listener authentication model: without `-n`,
incoming senders must match `-a <hash>` or an `allowed_identities` file.
`rncp-rs -F` can serve fetch requests to authenticated clients; use
`-j <jail>` to bound file access unless unrestricted fetch paths are
intentional.
`rnodeconf-rs` in the current build only covers safe inspection/device setting paths, EEPROM
dump/backup, and trusted-key storage.
## Configuration
`rnsd-rs` reads Reticulum INI config from `<config-dir>/config`. If no config
directory is supplied, the default is:
| Platform | Default config file |
| --- | --- |
| Linux/macOS | `/etc/rsReticulum/config`, then `~/.config/rsReticulum/config`, then `~/.rsReticulum/config` |
| Windows | `%APPDATA%\rsReticulum\config` |
Generate the annotated starter file:
```bash
rnsd-rs --exampleconfig
```
Minimal TCP client example:
```ini
[reticulum]
share_instance = yes
instance_control_socket = yes
enable_transport = no
[interfaces]
[[Default TCP]]
type = TCPClientInterface
enabled = yes
target_host = rns.ratspeak.org
target_port = 4242
```
Existing Python Reticulum configs should work if every requested interface
is implemented here. Unknown or not-yet-wired interfaces should be removed or
disabled until support lands.
The default shared-instance data/control ports are `37428`/`37429`. Ratspeak
uses app-private `37430`/`37431` ports. If you run two daemons at the same
time, give one config a distinct port pair to avoid confliction, like:
```ini
[reticulum]
shared_instance_port = 37432
instance_control_port = 37433
```
## Interface Support
###### Note: This is alpha, if something doesn't work, open an issue with enough context/information to help contribute to fixing it.
| Interface | Current behavior |
| --- | --- |
| TCP client/server | Config-backed IPv4 and IPv6 paths. |
| UDP | Config-backed unicast and multicast paths. |
| Auto | Config-backed UDP discovery plus TCP fallback. |
| Local shared instance | Config-backed TCP loopback or Unix socket depending on platform. |
| I2P | Config-backed SAM v3.1 path. |
| Pipe | Config-backed subprocess stdio pipe. |
| Backbone | Config-backed high-latency WAN-style tunnel. |
| Serial, KISS, RNode, RNode Multi, AX.25 KISS | Config-backed with the `serial` feature. |
| BLE RNode | Config-backed with the `ble` feature. |
| Bluetooth Peer | Runtime API used by Ratspeak. |
| Android USB-OTG | Runtime API for Android app embeddings. |
| Weave | Not implemented. |
| Bluetooth Classic RFCOMM | Not implemented. |
## Compatibility Notes
Most daemon and utility flows are implemented for the public `*-rs` tools:
`rnsd-rs`, `rnstatus-rs`, `rnpath-rs`, `rnid-rs`, `rnprobe-rs`, `rncp-rs`,
`rnsh-rs`, and `rnodeconf-rs`.
Known gaps and intentional limits:
- `rnx`, `rnir`, `rnpkg`, `rngit`, and `git-remote-rns` are not implemented. There is on-going work in progress for supporting these.
- `rnodeconf-rs` is partial; safe inspection/configuration and EEPROM
dump/backup are furthest along. Firmware flashing, autoinstall/update, ROM
bootstrap, destructive EEPROM wipe, and full signing-key management are not
implemented.
- `rnstatus-rs` covers the practical operator surface, but does not implement
every display/API behavior from upstream.
- `rnpath-rs` remote mode is read-only for table/rates, including destination
filters, apart from the remote blackhole-list query path. Remote mutations
and remote active path requests are full gaps.
- `rncp-rs` implements the listener `-b` announce interval. `-P/--phy-rates`
is not supported for the time being.
- `rns-ratkey` hardware identity support is feature-gated and still has known
hardware-verification gaps before it should be described as release-ready.
## Contributing
If the issue or contribution belongs upstream as well, start there. Python LXMF
and Reticulum remain the reference implementations.
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).
+29
View File
@@ -0,0 +1,29 @@
[package]
name = "rns-crypto"
description = "Cryptographic primitives for Reticulum"
version.workspace = true
edition.workspace = true
license.workspace = true
[features]
default = ["std"]
std = []
[dependencies]
x25519-dalek = { workspace = true }
ed25519-dalek = { workspace = true }
aes = { workspace = true }
cbc = { workspace = true }
hkdf = { workspace = true }
hmac = { workspace = true }
sha2 = { workspace = true }
subtle = { workspace = true }
rand = { workspace = true }
rand_core = { workspace = true }
zeroize = { workspace = true }
thiserror = { workspace = true }
[dev-dependencies]
hex = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
+181
View File
@@ -0,0 +1,181 @@
//! AES-CBC, no padding (callers use [`crate::pkcs7`]). Key length selects:
//! 16 → AES-128, 32 → AES-256. Wire negotiates AES-256; AES-128 kept for
//! legacy Token material.
use aes::{Aes128, Aes256};
use alloc::vec::Vec;
use cbc::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
use cbc::{Decryptor, Encryptor};
use thiserror::Error;
/// Errors surfaced by [`encrypt`] and [`decrypt`].
#[derive(Debug, Error)]
pub enum AesCbcError {
/// Key must be exactly 16 bytes (AES-128) or 32 bytes (AES-256).
#[error("invalid key length: expected 16 or 32, got {0}")]
InvalidKeyLength(usize),
/// IV must be exactly 16 bytes.
#[error("invalid IV length: expected 16, got {0}")]
InvalidIvLength(usize),
/// Input length is not a non-zero multiple of 16.
#[error("input not aligned to 16-byte block boundary")]
NotBlockAligned,
/// Underlying cipher reported a decrypt failure.
#[error("decryption failed")]
DecryptionFailed,
/// Underlying cipher reported an encrypt failure.
#[error("encryption failed")]
EncryptionFailed,
}
/// AES-CBC encrypt. Caller pads; `plaintext.len()` must be a non-zero
/// multiple of 16. IV must be 16 bytes.
pub fn encrypt(key: &[u8], iv: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, AesCbcError> {
if iv.len() != 16 {
return Err(AesCbcError::InvalidIvLength(iv.len()));
}
if plaintext.is_empty() || !plaintext.len().is_multiple_of(16) {
return Err(AesCbcError::NotBlockAligned);
}
let mut buf = plaintext.to_vec();
match key.len() {
16 => {
let enc = Encryptor::<Aes128>::new_from_slices(key, iv)
.map_err(|_| AesCbcError::InvalidKeyLength(key.len()))?;
enc.encrypt_padded_mut::<cbc::cipher::block_padding::NoPadding>(
&mut buf,
plaintext.len(),
)
.map_err(|_| AesCbcError::EncryptionFailed)?;
}
32 => {
let enc = Encryptor::<Aes256>::new_from_slices(key, iv)
.map_err(|_| AesCbcError::InvalidKeyLength(key.len()))?;
enc.encrypt_padded_mut::<cbc::cipher::block_padding::NoPadding>(
&mut buf,
plaintext.len(),
)
.map_err(|_| AesCbcError::EncryptionFailed)?;
}
n => return Err(AesCbcError::InvalidKeyLength(n)),
}
Ok(buf)
}
/// AES-CBC decrypt. Output is still PKCS7-padded; caller strips it.
pub fn decrypt(key: &[u8], iv: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, AesCbcError> {
if iv.len() != 16 {
return Err(AesCbcError::InvalidIvLength(iv.len()));
}
if ciphertext.is_empty() || !ciphertext.len().is_multiple_of(16) {
return Err(AesCbcError::NotBlockAligned);
}
let mut buf = ciphertext.to_vec();
match key.len() {
16 => {
let dec = Decryptor::<Aes128>::new_from_slices(key, iv)
.map_err(|_| AesCbcError::InvalidKeyLength(key.len()))?;
dec.decrypt_padded_mut::<cbc::cipher::block_padding::NoPadding>(&mut buf)
.map_err(|_| AesCbcError::DecryptionFailed)?;
}
32 => {
let dec = Decryptor::<Aes256>::new_from_slices(key, iv)
.map_err(|_| AesCbcError::InvalidKeyLength(key.len()))?;
dec.decrypt_padded_mut::<cbc::cipher::block_padding::NoPadding>(&mut buf)
.map_err(|_| AesCbcError::DecryptionFailed)?;
}
n => return Err(AesCbcError::InvalidKeyLength(n)),
}
Ok(buf)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_roundtrip() {
let key = [0x42u8; 32];
let iv = [0x01u8; 16];
let plaintext = [0xABu8; 16];
let ct = encrypt(&key, &iv, &plaintext).unwrap();
assert_eq!(ct.len(), 16);
assert_ne!(&ct[..], &plaintext[..]);
let pt = decrypt(&key, &iv, &ct).unwrap();
assert_eq!(&pt[..], &plaintext[..]);
}
#[test]
fn test_roundtrip_multi_block() {
let key = [0x42u8; 32];
let iv = [0x01u8; 16];
let plaintext = [0xABu8; 48];
let ct = encrypt(&key, &iv, &plaintext).unwrap();
assert_eq!(ct.len(), 48);
let pt = decrypt(&key, &iv, &ct).unwrap();
assert_eq!(&pt[..], &plaintext[..]);
}
#[test]
fn test_invalid_key_length() {
// 24-byte (AES-192) keys are not part of the RNS Token spec.
let key = [0u8; 24];
let iv = [0u8; 16];
let data = [0u8; 16];
assert!(encrypt(&key, &iv, &data).is_err());
}
#[test]
fn test_not_block_aligned() {
let key = [0u8; 32];
let iv = [0u8; 16];
let data = [0u8; 15];
assert!(encrypt(&key, &iv, &data).is_err());
}
#[test]
fn test_aes128_roundtrip() {
let key = [0x42u8; 16];
let iv = [0x01u8; 16];
let plaintext = [0xABu8; 16];
let ct = encrypt(&key, &iv, &plaintext).unwrap();
assert_eq!(ct.len(), 16);
assert_ne!(&ct[..], &plaintext[..]);
let pt = decrypt(&key, &iv, &ct).unwrap();
assert_eq!(&pt[..], &plaintext[..]);
}
#[test]
fn test_aes128_multi_block() {
let key = [0x42u8; 16];
let iv = [0x01u8; 16];
let plaintext = [0xABu8; 48];
let ct = encrypt(&key, &iv, &plaintext).unwrap();
assert_eq!(ct.len(), 48);
let pt = decrypt(&key, &iv, &ct).unwrap();
assert_eq!(&pt[..], &plaintext[..]);
}
/// Different key sizes must produce different ciphertexts for the same input.
#[test]
fn test_aes128_vs_aes256_distinct_ciphertexts() {
let key128 = [0x42u8; 16];
let key256 = [0x42u8; 32];
let iv = [0x01u8; 16];
let plaintext = [0xABu8; 16];
let ct128 = encrypt(&key128, &iv, &plaintext).unwrap();
let ct256 = encrypt(&key256, &iv, &plaintext).unwrap();
assert_ne!(ct128, ct256);
}
}
+173
View File
@@ -0,0 +1,173 @@
//! Ed25519 signing and verification.
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use rand_core::OsRng;
use thiserror::Error;
use zeroize::Zeroize;
/// Errors surfaced by Ed25519 sign/verify.
#[derive(Debug, Error)]
pub enum Ed25519Error {
/// `verify` rejected the signature.
#[error("signature verification failed")]
VerificationFailed,
/// Public key bytes were not a valid Ed25519 point.
#[error("invalid public key bytes")]
InvalidPublicKey,
/// Signature bytes could not be decoded as an Ed25519 signature.
#[error("invalid signature bytes")]
InvalidSignature,
}
/// Ed25519 private key (32-byte seed).
///
/// Key material is zeroized on drop.
pub struct Ed25519PrivateKey {
key: SigningKey,
}
impl Zeroize for Ed25519PrivateKey {
fn zeroize(&mut self) {
// Assignment drops the prior `SigningKey` (ZeroizeOnDrop), leaving a zero seed.
self.key = SigningKey::from_bytes(&[0u8; 32]);
}
}
impl Drop for Ed25519PrivateKey {
fn drop(&mut self) {
self.zeroize();
}
}
/// Ed25519 public key (32 bytes, compressed Edwards point).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Ed25519PublicKey {
key: VerifyingKey,
}
impl Ed25519PrivateKey {
/// Generate a random key from the OS CSPRNG.
pub fn generate() -> Self {
Self {
key: SigningKey::generate(&mut OsRng),
}
}
/// Construct from a 32-byte seed.
pub fn from_bytes(seed: &[u8; 32]) -> Self {
Self {
key: SigningKey::from_bytes(seed),
}
}
/// Return the 32-byte seed.
pub fn to_bytes(&self) -> [u8; 32] {
self.key.to_bytes()
}
/// Derive the corresponding public key.
pub fn public_key(&self) -> Ed25519PublicKey {
Ed25519PublicKey {
key: self.key.verifying_key(),
}
}
/// Produce a 64-byte Ed25519 signature (R || S) over `message`.
pub fn sign(&self, message: &[u8]) -> [u8; 64] {
let sig = self.key.sign(message);
sig.to_bytes()
}
}
impl Ed25519PublicKey {
/// Parse a 32-byte compressed Edwards point.
pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self, Ed25519Error> {
let key = VerifyingKey::from_bytes(bytes).map_err(|_| Ed25519Error::InvalidPublicKey)?;
Ok(Self { key })
}
/// Return the 32-byte encoded public key.
pub fn to_bytes(&self) -> [u8; 32] {
self.key.to_bytes()
}
/// Verify a 64-byte Ed25519 signature over `message`.
pub fn verify(&self, message: &[u8], signature: &[u8; 64]) -> Result<(), Ed25519Error> {
let sig = Signature::from_bytes(signature);
self.key
.verify(message, &sig)
.map_err(|_| Ed25519Error::VerificationFailed)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_key_generation() {
let prv = Ed25519PrivateKey::generate();
let pub_key = prv.public_key();
assert_ne!(pub_key.to_bytes(), [0u8; 32]);
}
#[test]
fn test_sign_verify() {
let prv = Ed25519PrivateKey::generate();
let pub_key = prv.public_key();
let msg = b"test message";
let sig = prv.sign(msg);
assert!(pub_key.verify(msg, &sig).is_ok());
}
#[test]
fn test_wrong_message() {
let prv = Ed25519PrivateKey::generate();
let pub_key = prv.public_key();
let sig = prv.sign(b"correct");
assert!(pub_key.verify(b"wrong", &sig).is_err());
}
#[test]
fn test_wrong_key() {
let prv1 = Ed25519PrivateKey::generate();
let prv2 = Ed25519PrivateKey::generate();
let msg = b"test";
let sig = prv1.sign(msg);
assert!(prv2.public_key().verify(msg, &sig).is_err());
}
#[test]
fn test_deterministic_from_seed() {
let seed = [42u8; 32];
let prv1 = Ed25519PrivateKey::from_bytes(&seed);
let prv2 = Ed25519PrivateKey::from_bytes(&seed);
let msg = b"deterministic";
assert_eq!(prv1.sign(msg), prv2.sign(msg));
assert_eq!(prv1.public_key().to_bytes(), prv2.public_key().to_bytes());
}
#[test]
fn test_seed_roundtrip() {
let prv = Ed25519PrivateKey::generate();
let seed = prv.to_bytes();
let prv2 = Ed25519PrivateKey::from_bytes(&seed);
assert_eq!(prv.public_key().to_bytes(), prv2.public_key().to_bytes());
}
#[test]
fn test_public_key_roundtrip() {
let prv = Ed25519PrivateKey::generate();
let pub_bytes = prv.public_key().to_bytes();
let pub_key = Ed25519PublicKey::from_bytes(&pub_bytes).unwrap();
assert_eq!(pub_key.to_bytes(), pub_bytes);
let msg = b"roundtrip";
let sig = prv.sign(msg);
assert!(pub_key.verify(msg, &sig).is_ok());
}
}
+88
View File
@@ -0,0 +1,88 @@
//! HKDF-SHA256 key derivation (RFC 5869).
use alloc::vec;
use alloc::vec::Vec;
use hkdf::Hkdf;
use sha2::Sha256;
use thiserror::Error;
/// Per RFC 5869, HKDF-SHA256 can emit at most 255 * HashLen = 8160 bytes.
const MAX_OUTPUT_LENGTH: usize = 255 * 32;
/// Errors surfaced by [`hkdf_sha256`].
#[derive(Debug, Error)]
pub enum HkdfError {
/// Requested output length exceeds the RFC 5869 cap (8160 bytes).
#[error("requested length {0} exceeds maximum HKDF output of {MAX_OUTPUT_LENGTH} bytes")]
OutputTooLong(usize),
/// Underlying HKDF expand call returned an error.
#[error("HKDF expansion failed")]
ExpansionFailed,
}
/// HKDF-SHA256 key derivation (RFC 5869).
///
/// `length` is capped at 8160 bytes. `salt = None` uses 32 zero bytes as
/// specified by the RFC; `info = None` uses an empty context string.
pub fn hkdf_sha256(
length: usize,
ikm: &[u8],
salt: Option<&[u8]>,
info: Option<&[u8]>,
) -> Result<Vec<u8>, HkdfError> {
if length > MAX_OUTPUT_LENGTH {
return Err(HkdfError::OutputTooLong(length));
}
let hk = Hkdf::<Sha256>::new(salt, ikm);
let mut okm = vec![0u8; length];
hk.expand(info.unwrap_or(b""), &mut okm)
.map_err(|_| HkdfError::ExpansionFailed)?;
Ok(okm)
}
/// Derive the 64-byte session key used for RNS link encryption:
/// `HKDF-SHA256(length=64, ikm=shared_secret, salt=identity_hash, info=None)`.
pub fn derive_key_64(shared_secret: &[u8], salt: &[u8]) -> Result<[u8; 64], HkdfError> {
let okm = hkdf_sha256(64, shared_secret, Some(salt), None)?;
let mut out = [0u8; 64];
out.copy_from_slice(&okm);
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_hkdf_rfc5869_vector1() {
// RFC 5869 Test Case 1.
let ikm = hex::decode("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b").unwrap();
let salt = hex::decode("000102030405060708090a0b0c").unwrap();
let info = hex::decode("f0f1f2f3f4f5f6f7f8f9").unwrap();
let okm = hkdf_sha256(42, &ikm, Some(&salt), Some(&info)).unwrap();
let expected =
"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865";
assert_eq!(hex::encode(&okm), expected);
}
#[test]
fn test_hkdf_max_length_exceeded() {
let result = hkdf_sha256(MAX_OUTPUT_LENGTH + 1, b"test", None, None);
assert!(result.is_err());
}
#[test]
fn test_hkdf_no_salt() {
let result = hkdf_sha256(32, b"test_ikm", None, None);
assert!(result.is_ok());
assert_eq!(result.unwrap().len(), 32);
}
#[test]
fn test_derive_key_64() {
let key = derive_key_64(b"shared_secret", b"salt_value").unwrap();
assert_eq!(key.len(), 64);
}
}
+60
View File
@@ -0,0 +1,60 @@
//! HMAC-SHA256 tag computation and constant-time verification.
use hmac::{Hmac, Mac};
use sha2::Sha256;
type HmacSha256 = Hmac<Sha256>;
/// HMAC-SHA256 (RFC 2104), returning the 32-byte tag.
pub fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
let mut mac = HmacSha256::new_from_slice(key).expect("HMAC-SHA256 accepts any key length");
mac.update(data);
mac.finalize().into_bytes().into()
}
/// Verify an HMAC-SHA256 tag in constant time.
pub fn hmac_verify(key: &[u8], data: &[u8], expected: &[u8; 32]) -> bool {
use subtle::ConstantTimeEq;
let computed = hmac_sha256(key, data);
computed.ct_eq(expected).into()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_hmac_sha256_rfc4231_vector1() {
// RFC 4231 Test Case 1.
let key = [0x0b; 20];
let data = b"Hi There";
let expected = "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7";
assert_eq!(hex::encode(hmac_sha256(&key, data)), expected);
}
#[test]
fn test_hmac_sha256_rfc4231_vector2() {
// RFC 4231 Test Case 2.
let key = b"Jefe";
let data = b"what do ya want for nothing?";
let expected = "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843";
assert_eq!(hex::encode(hmac_sha256(key, data)), expected);
}
#[test]
fn test_hmac_verify_correct() {
let key = b"test_key";
let data = b"test_data";
let mac = hmac_sha256(key, data);
assert!(hmac_verify(key, data, &mac));
}
#[test]
fn test_hmac_verify_wrong() {
let key = b"test_key";
let data = b"test_data";
let mut mac = hmac_sha256(key, data);
mac[0] ^= 1;
assert!(!hmac_verify(key, data, &mac));
}
}
+30
View File
@@ -0,0 +1,30 @@
//! Cryptographic primitives for Reticulum. Constants, derivation inputs, and
//! wire-visible byte layouts match the Python reference (`RNS/Cryptography/`)
//! exactly — downstream interop depends on it. `no_std + alloc` when `std` is off.
#![cfg_attr(not(feature = "std"), no_std)]
#![warn(missing_docs)]
extern crate alloc;
pub mod aes_cbc;
pub mod ed25519;
pub mod hkdf;
pub mod hmac;
pub mod pkcs7;
pub mod random;
pub mod sha;
pub mod token;
pub mod x25519;
pub use token::TOKEN_OVERHEAD;
use alloc::string::String;
use core::fmt::Write;
/// Lower-case hex encoding of `bytes`.
pub fn hex_encode(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for b in bytes {
let _ = write!(&mut out, "{b:02x}");
}
out
}
+127
View File
@@ -0,0 +1,127 @@
//! PKCS7 padding for 16-byte block ciphers (AES-CBC).
use alloc::vec::Vec;
use thiserror::Error;
const BLOCK_SIZE: usize = 16;
/// Errors surfaced by [`unpad`].
#[derive(Debug, Error)]
pub enum Pkcs7Error {
/// Trailing byte is zero or greater than the 16-byte block size.
#[error("invalid padding: padding byte value {0} exceeds block size {BLOCK_SIZE}")]
InvalidPaddingValue(u8),
/// The declared padding length doesn't match the trailing bytes.
#[error("invalid padding: inconsistent padding bytes")]
InconsistentPadding,
/// Input contained zero bytes.
#[error("invalid padding: empty input")]
EmptyInput,
}
/// Apply PKCS7 padding for a 16-byte block size.
///
/// Block-aligned inputs are still padded — a full 0x10 block is appended,
/// per the RFC 5652 construction.
pub fn pad(data: &[u8]) -> Vec<u8> {
let pad_len = BLOCK_SIZE - (data.len() % BLOCK_SIZE);
let mut out = Vec::with_capacity(data.len() + pad_len);
out.extend_from_slice(data);
out.extend(core::iter::repeat_n(pad_len as u8, pad_len));
out
}
/// Strip PKCS7 padding for a 16-byte block size.
///
/// All padding bytes are validated; a mismatch returns an error.
pub fn unpad(data: &[u8]) -> Result<&[u8], Pkcs7Error> {
if data.is_empty() {
return Err(Pkcs7Error::EmptyInput);
}
let pad_byte = data[data.len() - 1];
if pad_byte == 0 || pad_byte as usize > BLOCK_SIZE {
return Err(Pkcs7Error::InvalidPaddingValue(pad_byte));
}
let pad_len = pad_byte as usize;
if pad_len > data.len() {
return Err(Pkcs7Error::InvalidPaddingValue(pad_byte));
}
let start = data.len() - pad_len;
for &b in &data[start..] {
if b != pad_byte {
return Err(Pkcs7Error::InconsistentPadding);
}
}
Ok(&data[..start])
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
#[test]
fn test_pad_block_aligned() {
// Block-aligned input gets a full 0x10 padding block.
let input = [0u8; 16];
let padded = pad(&input);
assert_eq!(padded.len(), 32);
assert!(padded[16..].iter().all(|&b| b == 16));
}
#[test]
fn test_pad_one_byte() {
let padded = pad(b"a");
assert_eq!(padded.len(), 16);
assert_eq!(padded[0], b'a');
assert!(padded[1..].iter().all(|&b| b == 15));
}
#[test]
fn test_pad_fifteen_bytes() {
let input = [0x41u8; 15];
let padded = pad(&input);
assert_eq!(padded.len(), 16);
assert_eq!(padded[15], 1);
}
#[test]
fn test_roundtrip() {
for len in 0..64 {
let data = vec![0xABu8; len];
let padded = pad(&data);
let unpadded = unpad(&padded).unwrap();
assert_eq!(unpadded, &data[..]);
}
}
#[test]
fn test_unpad_empty() {
assert!(unpad(b"").is_err());
}
#[test]
fn test_unpad_invalid_zero() {
let mut data = [0u8; 16];
data[15] = 0;
assert!(unpad(&data).is_err());
}
#[test]
fn test_unpad_invalid_too_large() {
let mut data = [0u8; 16];
data[15] = 17;
assert!(unpad(&data).is_err());
}
#[test]
fn test_unpad_inconsistent_padding() {
// Last byte declares 4 pad bytes, but data[12] is not 4.
let mut data = vec![0x41u8; 16];
data[15] = 4;
data[14] = 4;
data[13] = 4;
data[12] = 99;
assert!(matches!(unpad(&data), Err(Pkcs7Error::InconsistentPadding)));
}
}
+52
View File
@@ -0,0 +1,52 @@
//! OS-CSPRNG-backed random byte helpers.
use alloc::vec;
use alloc::vec::Vec;
use rand::RngCore;
use rand_core::OsRng;
/// Cryptographically secure random bytes from the OS CSPRNG.
pub fn random_bytes(len: usize) -> Vec<u8> {
let mut buf = vec![0u8; len];
OsRng.fill_bytes(&mut buf);
buf
}
/// 16 random bytes, sized for AES IVs and truncated hashes.
pub fn random_16() -> [u8; 16] {
let mut buf = [0u8; 16];
OsRng.fill_bytes(&mut buf);
buf
}
/// 32 random bytes.
pub fn random_32() -> [u8; 32] {
let mut buf = [0u8; 32];
OsRng.fill_bytes(&mut buf);
buf
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_random_bytes_length() {
assert_eq!(random_bytes(0).len(), 0);
assert_eq!(random_bytes(16).len(), 16);
assert_eq!(random_bytes(64).len(), 64);
}
#[test]
fn test_random_not_zero() {
let r = random_32();
assert!(r.iter().any(|&b| b != 0));
}
#[test]
fn test_random_unique() {
let a = random_32();
let b = random_32();
assert_ne!(a, b);
}
}
+80
View File
@@ -0,0 +1,80 @@
//! SHA-256 / SHA-512 digests.
use sha2::{Digest, Sha256, Sha512};
/// SHA-256 hash.
pub fn sha256(data: &[u8]) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(data);
hasher.finalize().into()
}
/// SHA-512 hash.
pub fn sha512(data: &[u8]) -> [u8; 64] {
let mut hasher = Sha512::new();
hasher.update(data);
hasher.finalize().into()
}
/// SHA-256 truncated to 128 bits, used for destination and identity hashes.
pub fn truncated_hash(data: &[u8]) -> [u8; 16] {
let full = sha256(data);
let mut out = [0u8; 16];
out.copy_from_slice(&full[..16]);
out
}
/// Alias for [`sha256`].
pub fn full_hash(data: &[u8]) -> [u8; 32] {
sha256(data)
}
/// SHA-256 of an app-name string truncated to 80 bits.
pub fn name_hash(name: &str) -> [u8; 10] {
let full = sha256(name.as_bytes());
let mut out = [0u8; 10];
out.copy_from_slice(&full[..10]);
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_sha256_empty() {
let hash = sha256(b"");
let expected = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
assert_eq!(hex::encode(hash), expected);
}
#[test]
fn test_sha256_hello() {
let hash = sha256(b"hello");
let expected = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824";
assert_eq!(hex::encode(hash), expected);
}
#[test]
fn test_sha512_empty() {
let hash = sha512(b"");
let expected = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e";
assert_eq!(hex::encode(hash), expected);
}
#[test]
fn test_truncated_hash() {
let hash = truncated_hash(b"test");
assert_eq!(hash.len(), 16);
let full = sha256(b"test");
assert_eq!(&hash[..], &full[..16]);
}
#[test]
fn test_name_hash() {
let hash = name_hash("test.app");
assert_eq!(hash.len(), 10);
let full = sha256(b"test.app");
assert_eq!(&hash[..], &full[..10]);
}
}
+253
View File
@@ -0,0 +1,253 @@
//! RNS encryption token: AES-256-CBC + HMAC-SHA256 over an IV-prefixed ciphertext.
use alloc::vec::Vec;
use thiserror::Error;
use crate::aes_cbc;
use crate::hmac::{hmac_sha256, hmac_verify};
use crate::pkcs7;
use crate::random::random_16;
/// IV (16) + HMAC (32). A token is this plus the PKCS7-padded ciphertext.
pub const TOKEN_OVERHEAD: usize = 48;
/// Errors surfaced by [`encrypt`] and [`decrypt`].
#[derive(Debug, Error)]
pub enum TokenError {
/// Key must be 32 or 64 bytes.
#[error("invalid key length: expected 32 or 64, got {0}")]
InvalidKeyLength(usize),
/// Token is shorter than [`TOKEN_OVERHEAD`] so cannot contain IV + HMAC.
#[error("token too short for decryption")]
TooShort,
/// HMAC tag did not validate.
#[error("authentication failed")]
AuthenticationFailed,
/// Underlying AES-CBC decrypt returned an error.
#[error("decryption failed")]
DecryptionFailed,
/// Underlying AES-CBC encrypt returned an error.
#[error("encryption failed")]
EncryptionFailed,
}
/// Split a token key into `(signing_key, encryption_key)`.
/// 64 → 32/32 (AES-256 + HMAC-SHA256); 32 → 16/16 (AES-128, legacy).
fn split_key(key: &[u8]) -> Result<(&[u8], &[u8]), TokenError> {
match key.len() {
64 => Ok((&key[..32], &key[32..])),
32 => Ok((&key[..16], &key[16..])),
n => Err(TokenError::InvalidKeyLength(n)),
}
}
/// Token encrypt (Modified Fernet — no version byte, no timestamp).
/// Wire: `IV(16) || AES-CBC(PKCS7(plaintext)) || HMAC-SHA256(IV || ciphertext)(32)`.
pub fn encrypt(plaintext: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
let (signing_key, encryption_key) = split_key(key)?;
let iv = random_16();
let padded = pkcs7::pad(plaintext);
let ciphertext =
aes_cbc::encrypt(encryption_key, &iv, &padded).map_err(|_| TokenError::EncryptionFailed)?;
let mut signed_parts = Vec::with_capacity(16 + ciphertext.len());
signed_parts.extend_from_slice(&iv);
signed_parts.extend_from_slice(&ciphertext);
let mac = hmac_sha256(signing_key, &signed_parts);
let mut token = signed_parts;
token.extend_from_slice(&mac);
Ok(token)
}
/// Token decrypt. All failure modes collapse to `AuthenticationFailed`
/// (padding-oracle defence). HMAC comparison is constant-time.
pub fn decrypt(token: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
let (signing_key, encryption_key) = split_key(key)?;
// Minimum well-formed token: IV(16) + one AES block(16) + HMAC(32).
if token.len() < 64 {
return Err(TokenError::AuthenticationFailed);
}
let split_point = token.len() - 32;
let signed_parts = &token[..split_point];
let received_hmac: &[u8; 32] = token[split_point..].try_into().unwrap();
if !hmac_verify(signing_key, signed_parts, received_hmac) {
return Err(TokenError::AuthenticationFailed);
}
let iv = &signed_parts[..16];
let ciphertext = &signed_parts[16..];
if ciphertext.is_empty() || !ciphertext.len().is_multiple_of(16) {
return Err(TokenError::AuthenticationFailed);
}
let padded = aes_cbc::decrypt(encryption_key, iv, ciphertext)
.map_err(|_| TokenError::AuthenticationFailed)?;
let plaintext = pkcs7::unpad(&padded).map_err(|_| TokenError::AuthenticationFailed)?;
Ok(plaintext.to_vec())
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
#[test]
fn test_encrypt_decrypt_roundtrip() {
let key = [0x42u8; 64];
let plaintext = b"hello, reticulum!";
let token = encrypt(plaintext, &key).unwrap();
let decrypted = decrypt(&token, &key).unwrap();
assert_eq!(&decrypted, plaintext);
}
#[test]
fn test_encrypt_produces_correct_structure() {
let key = [0x42u8; 64];
let plaintext = b"test";
let token = encrypt(plaintext, &key).unwrap();
// IV(16) + ciphertext(16) + HMAC(32) = 64.
assert_eq!(token.len(), 64);
}
#[test]
fn test_encrypt_empty() {
let key = [0x42u8; 64];
let token = encrypt(b"", &key).unwrap();
assert_eq!(token.len(), 64);
let decrypted = decrypt(&token, &key).unwrap();
assert!(decrypted.is_empty());
}
#[test]
fn test_encrypt_block_aligned() {
let key = [0x42u8; 64];
// Block-aligned input forces a full extra padding block.
let plaintext = [0xABu8; 16];
let token = encrypt(&plaintext, &key).unwrap();
assert_eq!(token.len(), 80);
let decrypted = decrypt(&token, &key).unwrap();
assert_eq!(&decrypted, &plaintext);
}
#[test]
fn test_wrong_key_fails() {
let key1 = [0x42u8; 64];
let key2 = [0x43u8; 64];
let plaintext = b"secret";
let token = encrypt(plaintext, &key1).unwrap();
assert!(decrypt(&token, &key2).is_err());
}
#[test]
fn test_tampered_ciphertext_fails() {
let key = [0x42u8; 64];
let plaintext = b"secret";
let mut token = encrypt(plaintext, &key).unwrap();
// Offset 20 lies inside the ciphertext, after the 16-byte IV.
token[20] ^= 0xFF;
assert!(decrypt(&token, &key).is_err());
}
#[test]
fn test_tampered_hmac_fails() {
let key = [0x42u8; 64];
let plaintext = b"secret";
let mut token = encrypt(plaintext, &key).unwrap();
let last = token.len() - 1;
token[last] ^= 0xFF;
assert!(decrypt(&token, &key).is_err());
}
#[test]
fn test_too_short_token() {
let key = [0x42u8; 64];
assert!(decrypt(&[0u8; 63], &key).is_err());
}
#[test]
fn test_invalid_key_length() {
assert!(encrypt(b"test", &[0u8; 48]).is_err());
assert!(decrypt(&[0u8; 64], &[0u8; 48]).is_err());
}
#[test]
fn test_various_lengths() {
let key = [0x42u8; 64];
for len in 0..256 {
let plaintext = vec![0xABu8; len];
let token = encrypt(&plaintext, &key).unwrap();
let decrypted = decrypt(&token, &key).unwrap();
assert_eq!(decrypted, plaintext, "failed for length {len}");
}
}
#[test]
fn test_unique_ciphertexts() {
// Random IV must produce distinct ciphertexts for the same input.
let key = [0x42u8; 64];
let plaintext = b"same input";
let t1 = encrypt(plaintext, &key).unwrap();
let t2 = encrypt(plaintext, &key).unwrap();
assert_ne!(t1, t2);
}
/// Legacy AES-128 round-trip via 32-byte key (Python `Token.py:62-65`).
#[test]
fn test_encrypt_decrypt_roundtrip_aes128() {
let key = [0x42u8; 32];
let plaintext = b"hello legacy reticulum";
let token = encrypt(plaintext, &key).unwrap();
let decrypted = decrypt(&token, &key).unwrap();
assert_eq!(&decrypted, plaintext);
}
#[test]
fn test_encrypt_aes128_structure() {
let key = [0x42u8; 32];
let plaintext = b"test";
let token = encrypt(plaintext, &key).unwrap();
assert_eq!(token.len(), 64);
}
#[test]
fn test_aes128_tampered_ciphertext_fails() {
let key = [0x42u8; 32];
let plaintext = b"secret";
let mut token = encrypt(plaintext, &key).unwrap();
token[20] ^= 0xFF;
assert!(decrypt(&token, &key).is_err());
}
/// A token under one key size must not decrypt with the other.
#[test]
fn test_token_key_size_isolation() {
let key128 = [0x42u8; 32];
let key256 = [0x42u8; 64];
let plaintext = b"isolated";
let t128 = encrypt(plaintext, &key128).unwrap();
let t256 = encrypt(plaintext, &key256).unwrap();
assert!(decrypt(&t128, &key256).is_err());
assert!(decrypt(&t256, &key128).is_err());
}
}
+121
View File
@@ -0,0 +1,121 @@
//! X25519 Diffie-Hellman primitives.
use rand_core::OsRng;
use x25519_dalek::{PublicKey, StaticSecret};
use zeroize::Zeroize;
/// X25519 private key (32 bytes, clamped scalar).
///
/// Key material is zeroized on drop.
pub struct X25519PrivateKey {
secret: StaticSecret,
}
impl Zeroize for X25519PrivateKey {
fn zeroize(&mut self) {
// Assignment drops the prior `StaticSecret` (ZeroizeOnDrop), leaving a zero scalar.
self.secret = StaticSecret::from([0u8; 32]);
}
}
impl Drop for X25519PrivateKey {
fn drop(&mut self) {
self.zeroize();
}
}
/// X25519 public key (32 bytes, u-coordinate).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct X25519PublicKey {
key: PublicKey,
}
impl X25519PrivateKey {
/// Generate a random key from the OS CSPRNG.
pub fn generate() -> Self {
Self {
secret: StaticSecret::random_from_rng(OsRng),
}
}
/// Construct from a 32-byte scalar.
pub fn from_bytes(bytes: &[u8; 32]) -> Self {
Self {
secret: StaticSecret::from(*bytes),
}
}
/// Return the 32-byte scalar.
pub fn to_bytes(&self) -> [u8; 32] {
self.secret.to_bytes()
}
/// Derive the corresponding public key.
pub fn public_key(&self) -> X25519PublicKey {
X25519PublicKey {
key: PublicKey::from(&self.secret),
}
}
/// Compute the shared secret with `peer` via X25519 Diffie-Hellman.
pub fn exchange(&self, peer: &X25519PublicKey) -> [u8; 32] {
self.secret.diffie_hellman(&peer.key).to_bytes()
}
}
impl X25519PublicKey {
/// Parse a 32-byte u-coordinate.
pub fn from_bytes(bytes: &[u8; 32]) -> Self {
Self {
key: PublicKey::from(*bytes),
}
}
/// Return the 32-byte u-coordinate.
pub fn to_bytes(&self) -> [u8; 32] {
self.key.to_bytes()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_key_generation() {
let prv = X25519PrivateKey::generate();
let pub_key = prv.public_key();
assert_ne!(pub_key.to_bytes(), [0u8; 32]);
}
#[test]
fn test_key_roundtrip() {
let prv = X25519PrivateKey::generate();
let bytes = prv.to_bytes();
let prv2 = X25519PrivateKey::from_bytes(&bytes);
assert_eq!(prv.public_key().to_bytes(), prv2.public_key().to_bytes());
}
#[test]
fn test_ecdh_agreement() {
let alice_prv = X25519PrivateKey::generate();
let alice_pub = alice_prv.public_key();
let bob_prv = X25519PrivateKey::generate();
let bob_pub = bob_prv.public_key();
let alice_shared = alice_prv.exchange(&bob_pub);
let bob_shared = bob_prv.exchange(&alice_pub);
assert_eq!(alice_shared, bob_shared);
}
#[test]
fn test_from_known_bytes() {
let prv_bytes = [42u8; 32];
let prv = X25519PrivateKey::from_bytes(&prv_bytes);
let pub_key = prv.public_key();
let pub_key2 = X25519PrivateKey::from_bytes(&prv_bytes).public_key();
assert_eq!(pub_key.to_bytes(), pub_key2.to_bytes());
}
}
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "rns-identity"
description = "Identity, Destination, and Announce system for Reticulum"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
rns-crypto = { workspace = true, features = ["std"] }
rns-wire = { workspace = true, features = ["std"] }
zeroize = { workspace = true }
thiserror = { workspace = true }
rmp-serde = { workspace = true }
rmpv = { workspace = true }
serde = { workspace = true }
rand = { workspace = true }
tracing = { workspace = true }
hex = { workspace = true }
[dev-dependencies]
proptest = { workspace = true }
+441
View File
@@ -0,0 +1,441 @@
use rns_crypto::sha::truncated_hash;
use thiserror::Error;
use tracing::trace;
use crate::identity::Identity;
use crate::name_hash::name_hash;
// Announce field sizes, fixed by the wire format.
const PUBKEY_SIZE: usize = 64;
const NAME_HASH_SIZE: usize = 10;
const RANDOM_HASH_SIZE: usize = 10;
const SIGNATURE_SIZE: usize = 64;
const RATCHET_SIZE: usize = 32;
const MIN_ANNOUNCE_SIZE: usize = PUBKEY_SIZE + NAME_HASH_SIZE + RANDOM_HASH_SIZE + SIGNATURE_SIZE;
#[derive(Debug, Error)]
pub enum AnnounceError {
#[error("announce data too short: {0} bytes (minimum {MIN_ANNOUNCE_SIZE})")]
TooShort(usize),
#[error("signature verification failed")]
SignatureInvalid,
#[error("destination hash mismatch")]
HashMismatch,
#[error("identity has no private key for signing")]
NoPrivateKey,
#[error("invalid public key in announce")]
InvalidPublicKey,
#[error("hash collision detected for destination")]
HashCollision,
}
/// Parsed announce data.
#[derive(Debug, Clone)]
pub struct AnnounceData {
pub public_key: [u8; 64],
pub name_hash: [u8; 10],
pub random_hash: [u8; 10],
pub ratchet: Option<[u8; 32]>,
pub signature: [u8; 64],
pub app_data: Option<Vec<u8>>,
}
impl AnnounceData {
/// Create and sign an announce for a destination.
///
/// The `random_hash` is `random(5) || timestamp_be(5)` so receivers can
/// detect replays without a shared clock.
pub fn create(
identity: &Identity,
app_name: &str,
app_data: Option<&[u8]>,
ratchet_pub: Option<&[u8; 32]>,
) -> Result<Self, AnnounceError> {
let public_key = identity.get_public_key();
let nh = name_hash(app_name);
let random_bytes = rns_crypto::random::random_bytes(5);
let ts = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let ts_bytes = ts.to_be_bytes();
let mut random_hash = [0u8; 10];
random_hash[..5].copy_from_slice(&random_bytes);
// Low 5 bytes of the u64 timestamp; wraps ~every 34 000 years.
random_hash[5..].copy_from_slice(&ts_bytes[3..8]);
let dest_hash = crate::destination::Destination::hash_from_name_and_identity(
app_name,
Some(&identity.hash),
);
let mut signed_data = Vec::new();
signed_data.extend_from_slice(&dest_hash);
signed_data.extend_from_slice(&public_key);
signed_data.extend_from_slice(&nh);
signed_data.extend_from_slice(&random_hash);
if let Some(r) = ratchet_pub {
signed_data.extend_from_slice(r);
}
if let Some(ad) = app_data {
signed_data.extend_from_slice(ad);
}
let signature = identity
.sign(&signed_data)
.ok_or(AnnounceError::NoPrivateKey)?;
Ok(Self {
public_key,
name_hash: nh,
random_hash,
ratchet: ratchet_pub.copied(),
signature,
app_data: app_data.map(|d| d.to_vec()),
})
}
/// Serialise the announce into its on-wire packet payload.
///
/// Layout: `pub_key(64) || name_hash(10) || random_hash(10) || [ratchet(32)] || signature(64) || [app_data]`.
pub fn pack(&self) -> Vec<u8> {
let size = PUBKEY_SIZE
+ NAME_HASH_SIZE
+ RANDOM_HASH_SIZE
+ if self.ratchet.is_some() {
RATCHET_SIZE
} else {
0
}
+ SIGNATURE_SIZE
+ self.app_data.as_ref().map_or(0, |d| d.len());
let mut out = Vec::with_capacity(size);
out.extend_from_slice(&self.public_key);
out.extend_from_slice(&self.name_hash);
out.extend_from_slice(&self.random_hash);
if let Some(ref r) = self.ratchet {
out.extend_from_slice(r);
}
out.extend_from_slice(&self.signature);
if let Some(ref ad) = self.app_data {
out.extend_from_slice(ad);
}
out
}
/// Parse an announce from packet payload bytes.
///
/// `has_ratchet` must match the packet header's context flag; the ratchet
/// field is not self-delimiting.
pub fn unpack(data: &[u8], has_ratchet: bool) -> Result<Self, AnnounceError> {
let min_size = if has_ratchet {
MIN_ANNOUNCE_SIZE + RATCHET_SIZE
} else {
MIN_ANNOUNCE_SIZE
};
if data.len() < min_size {
return Err(AnnounceError::TooShort(data.len()));
}
let mut pos = 0;
let mut public_key = [0u8; 64];
public_key.copy_from_slice(&data[pos..pos + 64]);
pos += 64;
let mut nh = [0u8; 10];
nh.copy_from_slice(&data[pos..pos + 10]);
pos += 10;
let mut random_hash = [0u8; 10];
random_hash.copy_from_slice(&data[pos..pos + 10]);
pos += 10;
let ratchet = if has_ratchet {
let mut r = [0u8; 32];
r.copy_from_slice(&data[pos..pos + 32]);
pos += 32;
Some(r)
} else {
None
};
let mut signature = [0u8; 64];
signature.copy_from_slice(&data[pos..pos + 64]);
pos += 64;
let app_data = if pos < data.len() {
Some(data[pos..].to_vec())
} else {
None
};
Ok(Self {
public_key,
name_hash: nh,
random_hash,
ratchet,
signature,
app_data,
})
}
/// Validate an announce against the destination hash from the packet header.
pub fn validate(&self, packet_dest_hash: &[u8; 16]) -> Result<Identity, AnnounceError> {
self.validate_with_known_key(packet_dest_hash, None)
}
/// Validate and optionally enforce first-seen key binding.
///
/// If `known_public_key` is supplied and differs from the announced key,
/// the announce is rejected as a potential hash-collision hijack.
pub fn validate_with_known_key(
&self,
packet_dest_hash: &[u8; 16],
known_public_key: Option<&[u8; 64]>,
) -> Result<Identity, AnnounceError> {
let identity = Identity::from_public_key(&self.public_key)
.map_err(|_| AnnounceError::InvalidPublicKey)?;
let mut signed_data = Vec::new();
signed_data.extend_from_slice(packet_dest_hash);
signed_data.extend_from_slice(&self.public_key);
signed_data.extend_from_slice(&self.name_hash);
signed_data.extend_from_slice(&self.random_hash);
if let Some(ref r) = self.ratchet {
signed_data.extend_from_slice(r);
}
if let Some(ref ad) = self.app_data {
signed_data.extend_from_slice(ad);
}
trace!(
signed_data_len = signed_data.len(),
signed_data_head = hex::encode(&signed_data[..std::cmp::min(32, signed_data.len())]),
signed_data_tail = hex::encode(&signed_data[signed_data.len().saturating_sub(16)..]),
identity_hash = hex::encode(identity.hash),
"announce: verifying signature"
);
if !identity.verify(&signed_data, &self.signature) {
return Err(AnnounceError::SignatureInvalid);
}
// Destination hash = SHA-256(name_hash || identity_hash) truncated to 16 bytes.
let expected_hash = {
let mut material = Vec::with_capacity(26);
material.extend_from_slice(&self.name_hash);
material.extend_from_slice(&identity.hash);
truncated_hash(&material)
};
if &expected_hash != packet_dest_hash {
trace!(
expected = hex::encode(expected_hash),
actual = hex::encode(packet_dest_hash),
name_hash = hex::encode(self.name_hash),
identity_hash = hex::encode(identity.hash),
"announce: destination hash mismatch"
);
return Err(AnnounceError::HashMismatch);
}
// First-seen key binding: a valid signature on a different public key
// for an already-known destination hash implies a collision attack.
if let Some(known_key) = known_public_key
&& known_key != &self.public_key
{
tracing::error!(
dest = hex::encode(packet_dest_hash),
"announce has valid signature and destination hash, but public key \
differs from already known key — possible hash collision attack, rejecting"
);
return Err(AnnounceError::HashCollision);
}
Ok(identity)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_and_validate_announce() {
let id = Identity::new();
let app_name = "test.announce";
let announce = AnnounceData::create(&id, app_name, Some(b"hello"), None).unwrap();
let dest_hash =
crate::destination::Destination::hash_from_name_and_identity(app_name, Some(&id.hash));
let validated_id = announce.validate(&dest_hash).unwrap();
assert_eq!(validated_id.hash, id.hash);
}
#[test]
fn test_create_and_validate_with_ratchet() {
let id = Identity::new();
let ratchet_pub = rns_crypto::random::random_32();
let announce = AnnounceData::create(&id, "test.ratchet", None, Some(&ratchet_pub)).unwrap();
assert!(announce.ratchet.is_some());
let dest_hash = crate::destination::Destination::hash_from_name_and_identity(
"test.ratchet",
Some(&id.hash),
);
announce.validate(&dest_hash).unwrap();
}
#[test]
fn test_pack_unpack_roundtrip() {
let id = Identity::new();
let announce = AnnounceData::create(&id, "test.pack", Some(b"data"), None).unwrap();
let packed = announce.pack();
let unpacked = AnnounceData::unpack(&packed, false).unwrap();
assert_eq!(announce.public_key, unpacked.public_key);
assert_eq!(announce.name_hash, unpacked.name_hash);
assert_eq!(announce.random_hash, unpacked.random_hash);
assert_eq!(announce.signature, unpacked.signature);
assert_eq!(announce.app_data, unpacked.app_data);
}
#[test]
fn test_pack_unpack_with_ratchet() {
let id = Identity::new();
let ratchet = rns_crypto::random::random_32();
let announce = AnnounceData::create(&id, "test.pack", None, Some(&ratchet)).unwrap();
let packed = announce.pack();
let unpacked = AnnounceData::unpack(&packed, true).unwrap();
assert_eq!(announce.ratchet, unpacked.ratchet);
assert_eq!(announce.signature, unpacked.signature);
}
#[test]
fn test_tampered_signature_fails() {
let id = Identity::new();
let mut announce = AnnounceData::create(&id, "test.tamper", None, None).unwrap();
announce.signature[0] ^= 0xFF;
let dest_hash = crate::destination::Destination::hash_from_name_and_identity(
"test.tamper",
Some(&id.hash),
);
assert!(announce.validate(&dest_hash).is_err());
}
#[test]
fn test_wrong_dest_hash_fails() {
let id = Identity::new();
let announce = AnnounceData::create(&id, "test.wrong", None, None).unwrap();
let wrong_hash = [0xFF; 16];
assert!(announce.validate(&wrong_hash).is_err());
}
#[test]
fn test_announce_too_short() {
assert!(AnnounceData::unpack(&[0u8; 10], false).is_err());
}
#[test]
fn test_hash_collision_defense_same_key_accepted() {
let id = Identity::new();
let app_name = "test.collision";
let announce = AnnounceData::create(&id, app_name, None, None).unwrap();
let dest_hash =
crate::destination::Destination::hash_from_name_and_identity(app_name, Some(&id.hash));
let known_key = id.get_public_key();
assert!(
announce
.validate_with_known_key(&dest_hash, Some(&known_key))
.is_ok()
);
}
#[test]
fn test_hash_collision_defense_different_key_rejected() {
let id = Identity::new();
let app_name = "test.collision2";
let announce = AnnounceData::create(&id, app_name, None, None).unwrap();
let dest_hash =
crate::destination::Destination::hash_from_name_and_identity(app_name, Some(&id.hash));
let other_id = Identity::new();
let other_key = other_id.get_public_key();
let result = announce.validate_with_known_key(&dest_hash, Some(&other_key));
assert!(matches!(result, Err(AnnounceError::HashCollision)));
}
#[test]
fn test_hash_collision_defense_no_known_key_accepted() {
let id = Identity::new();
let app_name = "test.collision3";
let announce = AnnounceData::create(&id, app_name, None, None).unwrap();
let dest_hash =
crate::destination::Destination::hash_from_name_and_identity(app_name, Some(&id.hash));
assert!(announce.validate_with_known_key(&dest_hash, None).is_ok());
}
use proptest::prelude::*;
type AnnounceBytes = (
[u8; 64], // public_key
[u8; 10], // name_hash
[u8; 10], // random_hash
[u8; 64], // signature
Option<[u8; 32]>, // ratchet
Option<Vec<u8>>, // app_data
);
fn any_announce_bytes() -> impl Strategy<Value = AnnounceBytes> {
(
any::<[u8; 64]>(),
any::<[u8; 10]>(),
any::<[u8; 10]>(),
any::<[u8; 64]>(),
proptest::option::of(any::<[u8; 32]>()),
// Empty app_data is omitted on the wire and parses back as None,
// so generate only None or Some(non-empty) for a clean roundtrip.
proptest::option::of(proptest::collection::vec(any::<u8>(), 1..=256)),
)
}
proptest! {
#[test]
fn proptest_announce_pack_unpack_roundtrip(
(public_key, name_hash, random_hash, signature, ratchet, app_data)
in any_announce_bytes(),
) {
let has_ratchet = ratchet.is_some();
let announce = AnnounceData {
public_key,
name_hash,
random_hash,
ratchet,
signature,
app_data: app_data.clone(),
};
let packed = announce.pack();
let unpacked = AnnounceData::unpack(&packed, has_ratchet).unwrap();
prop_assert_eq!(unpacked.public_key, public_key);
prop_assert_eq!(unpacked.name_hash, name_hash);
prop_assert_eq!(unpacked.random_hash, random_hash);
prop_assert_eq!(unpacked.ratchet, ratchet);
prop_assert_eq!(unpacked.signature, signature);
prop_assert_eq!(&unpacked.app_data, &app_data);
// Canonical form: re-pack must yield identical bytes.
prop_assert_eq!(unpacked.pack(), packed);
}
}
}
+859
View File
@@ -0,0 +1,859 @@
use std::collections::HashMap;
use rns_crypto::sha::truncated_hash;
use rns_crypto::token;
use thiserror::Error;
use crate::identity::Identity;
use crate::name_hash::name_hash;
/// Callback invoked on incoming data packets: `fn(plaintext, raw_packet)`.
pub type PacketCallback = Box<dyn Fn(&[u8], &[u8]) + Send + Sync>;
/// Callback invoked when a new link is established: `fn(link_id)`.
pub type LinkEstablishedCallback = Box<dyn Fn([u8; 16]) + Send + Sync>;
/// Callback deciding whether to emit a proof for a given packet.
pub type ProofRequestedCallback = Box<dyn Fn(&[u8]) -> bool + Send + Sync>;
pub struct RequestHandler {
pub path: String,
pub allow: AllowPolicy,
/// Identity hashes permitted when `allow == AllowList`.
pub allowed_list: Vec<[u8; 16]>,
pub auto_compress: bool,
}
/// Default app data for announces: static bytes or a dynamic generator.
pub enum DefaultAppData {
Static(Vec<u8>),
Dynamic(Box<dyn Fn() -> Option<Vec<u8>> + Send + Sync>),
}
struct PathResponseCache {
timestamp: f64,
announce_data: Vec<u8>,
}
// Path-response dedup window (seconds). Matches upstream default.
const PR_TAG_WINDOW: f64 = 30.0;
/// Destination type (matches wire format `DestinationType`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum DestType {
/// Asymmetric encryption via identity (ECDH + AES-256).
Single = 0x00,
/// Symmetric encryption with pre-shared key.
Group = 0x01,
/// No encryption (plaintext).
Plain = 0x02,
/// Internal per-link ephemeral encryption.
Link = 0x03,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Direction {
In,
Out,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum ProofStrategy {
ProveNone = 0x21,
ProveApp = 0x22,
ProveAll = 0x23,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum AllowPolicy {
AllowNone = 0x00,
AllowAll = 0x01,
AllowList = 0x02,
}
#[derive(Debug, Error)]
pub enum DestinationError {
#[error("SINGLE destination requires an identity")]
MissingIdentity,
#[error("outbound SINGLE destination requires an identity")]
OutboundMissingIdentity,
#[error("PLAIN destination cannot have an identity")]
PlainWithIdentity,
#[error("encryption not available for this destination type")]
EncryptionUnavailable,
#[error("decryption failed")]
DecryptionFailed,
#[error("only SINGLE destinations can be proved")]
ProveNotSingle,
#[error("identity error: {0}")]
Identity(#[from] crate::identity::IdentityError),
}
pub struct Destination {
pub dest_type: DestType,
pub direction: Direction,
pub hash: [u8; 16],
pub name_hash: [u8; 10],
pub app_name: String,
pub proof_strategy: ProofStrategy,
/// If set, incoming data is signature-checked but not decrypted.
pub only_validate_signature: bool,
group_key: Option<Vec<u8>>,
// Identity auto-generated for an IN destination when none was supplied;
// callers retrieve it via [`auto_identity`] or [`take_auto_identity`].
auto_identity: Option<Identity>,
packet_callback: Option<PacketCallback>,
link_established_callback: Option<LinkEstablishedCallback>,
proof_requested_callback: Option<ProofRequestedCallback>,
// Keyed by SHA-256(path)[:16].
request_handlers: HashMap<[u8; 16], RequestHandler>,
pub links: Vec<[u8; 16]>,
pub accept_link_requests: bool,
default_app_data: Option<DefaultAppData>,
pub ratchets_enabled: bool,
/// When set, non-ratchet ciphertexts are rejected.
pub ratchets_enforced: bool,
/// OUT: remote peer's most recent ratchet public key, used for forward-secret encryption.
pub remote_ratchet_pub: Option<[u8; 32]>,
/// IN: our current ratchet public key, advertised in announces.
pub local_ratchet_pub: Option<[u8; 32]>,
path_responses: HashMap<Vec<u8>, PathResponseCache>,
}
impl Destination {
/// Create a new destination.
///
/// For SINGLE/GROUP inbound destinations, a new identity is generated
/// automatically when `identity` is `None`; retrieve it via
/// [`Destination::auto_identity`].
///
/// See [`Destination::compute_hash`] for the hash derivation.
pub fn new(
identity: Option<&Identity>,
direction: Direction,
dest_type: DestType,
app_name: &str,
) -> Result<Self, DestinationError> {
match dest_type {
DestType::Single | DestType::Group => {
let (id_ref, auto_id, hash_name) = match identity {
Some(id) => (id.hash, None, app_name.to_string()),
None => {
if direction == Direction::In {
let new_id = Identity::new();
let hash = new_id.hash;
let hash_name = format!("{app_name}.{}", hex::encode(hash));
(hash, Some(new_id), hash_name)
} else {
return Err(DestinationError::OutboundMissingIdentity);
}
}
};
let nh = name_hash(&hash_name);
let hash = Self::compute_hash(&nh, Some(&id_ref));
Ok(Self {
dest_type,
direction,
hash,
name_hash: nh,
app_name: app_name.to_string(),
proof_strategy: ProofStrategy::ProveNone,
only_validate_signature: false,
group_key: None,
auto_identity: auto_id,
packet_callback: None,
link_established_callback: None,
proof_requested_callback: None,
request_handlers: HashMap::new(),
links: Vec::new(),
accept_link_requests: true,
default_app_data: None,
ratchets_enabled: false,
ratchets_enforced: false,
remote_ratchet_pub: None,
local_ratchet_pub: None,
path_responses: HashMap::new(),
})
}
DestType::Plain => {
if identity.is_some() {
return Err(DestinationError::PlainWithIdentity);
}
let nh = name_hash(app_name);
let hash = Self::compute_hash(&nh, None);
Ok(Self {
dest_type,
direction,
hash,
name_hash: nh,
app_name: app_name.to_string(),
proof_strategy: ProofStrategy::ProveNone,
only_validate_signature: false,
group_key: None,
auto_identity: None,
packet_callback: None,
link_established_callback: None,
proof_requested_callback: None,
request_handlers: HashMap::new(),
links: Vec::new(),
accept_link_requests: true,
default_app_data: None,
ratchets_enabled: false,
ratchets_enforced: false,
remote_ratchet_pub: None,
local_ratchet_pub: None,
path_responses: HashMap::new(),
})
}
DestType::Link => {
// LINK destinations are constructed by the link layer itself.
let nh = name_hash(app_name);
let hash = Self::compute_hash(&nh, identity.map(|i| &i.hash));
Ok(Self {
dest_type,
direction,
hash,
name_hash: nh,
app_name: app_name.to_string(),
proof_strategy: ProofStrategy::ProveNone,
only_validate_signature: false,
group_key: None,
auto_identity: None,
packet_callback: None,
link_established_callback: None,
proof_requested_callback: None,
request_handlers: HashMap::new(),
links: Vec::new(),
accept_link_requests: true,
default_app_data: None,
ratchets_enabled: false,
ratchets_enforced: false,
remote_ratchet_pub: None,
local_ratchet_pub: None,
path_responses: HashMap::new(),
})
}
}
}
/// Compute a destination hash.
///
/// - SINGLE/GROUP: `SHA-256(name_hash || identity_hash)[:16]`
/// - PLAIN: `SHA-256(name_hash)[:16]`
pub fn compute_hash(nh: &[u8; 10], identity_hash: Option<&[u8; 16]>) -> [u8; 16] {
match identity_hash {
Some(ih) => {
let mut material = [0u8; 26];
material[..10].copy_from_slice(nh);
material[10..].copy_from_slice(ih);
truncated_hash(&material)
}
None => truncated_hash(nh),
}
}
pub fn hash_from_name_and_identity(
app_name: &str,
identity_hash: Option<&[u8; 16]>,
) -> [u8; 16] {
let nh = name_hash(app_name);
Self::compute_hash(&nh, identity_hash)
}
pub fn set_proof_strategy(&mut self, strategy: ProofStrategy) {
self.proof_strategy = strategy;
}
/// Set the pre-shared key used for GROUP encryption.
pub fn set_group_key(&mut self, key: Vec<u8>) {
self.group_key = Some(key);
}
/// Identity auto-generated at construction (IN + SINGLE/GROUP without a caller-provided identity).
pub fn auto_identity(&self) -> Option<&Identity> {
self.auto_identity.as_ref()
}
pub fn take_auto_identity(&mut self) -> Option<Identity> {
self.auto_identity.take()
}
pub fn set_only_validate_signature(&mut self, only_validate: bool) {
self.only_validate_signature = only_validate;
}
/// Produce a proof over `packet_hash` for this (SINGLE) destination.
///
/// `implicit_proof = true` emits the 64-byte signature alone; otherwise
/// the output is `packet_hash || signature`.
pub fn prove(
&self,
packet_hash: &[u8],
identity: &Identity,
implicit_proof: bool,
) -> Result<Vec<u8>, DestinationError> {
if self.dest_type != DestType::Single {
return Err(DestinationError::ProveNotSingle);
}
identity
.prove(packet_hash, implicit_proof)
.map_err(DestinationError::Identity)
}
/// Encrypt data for this destination.
///
/// For SINGLE destinations a `remote_ratchet_pub` replaces the identity's
/// X25519 key in the ECDH exchange, giving forward secrecy.
pub fn encrypt(
&self,
plaintext: &[u8],
identity: &Identity,
remote_ratchet_pub: Option<&[u8; 32]>,
) -> Result<Vec<u8>, DestinationError> {
match self.dest_type {
DestType::Plain => Ok(plaintext.to_vec()),
DestType::Single => identity
.encrypt(plaintext, remote_ratchet_pub)
.map_err(DestinationError::Identity),
DestType::Group => {
let key = self
.group_key
.as_ref()
.ok_or(DestinationError::EncryptionUnavailable)?;
token::encrypt(plaintext, key).map_err(|_| DestinationError::DecryptionFailed)
}
DestType::Link => Err(DestinationError::EncryptionUnavailable),
}
}
pub fn decrypt(
&self,
ciphertext: &[u8],
identity: &Identity,
) -> Result<Vec<u8>, DestinationError> {
self.decrypt_with_ratchets(ciphertext, identity, None)
}
/// Decrypt data, trying each ratchet private key before the identity key.
pub fn decrypt_with_ratchets(
&self,
ciphertext: &[u8],
identity: &Identity,
ratchet_keys: Option<&[[u8; 32]]>,
) -> Result<Vec<u8>, DestinationError> {
match self.dest_type {
DestType::Plain => Ok(ciphertext.to_vec()),
DestType::Single => {
let ratchet_refs: Option<Vec<&[u8; 32]>> = if self.ratchets_enabled {
ratchet_keys.map(|keys| keys.iter().collect())
} else {
None
};
let enforce = self.ratchets_enforced;
identity
.decrypt(ciphertext, ratchet_refs.as_deref(), enforce)
.map_err(DestinationError::Identity)
}
DestType::Group => {
let key = self
.group_key
.as_ref()
.ok_or(DestinationError::EncryptionUnavailable)?;
token::decrypt(ciphertext, key).map_err(|_| DestinationError::DecryptionFailed)
}
DestType::Link => Err(DestinationError::EncryptionUnavailable),
}
}
/// Record the remote peer's ratchet public key, learnt from an announce.
pub fn set_remote_ratchet(&mut self, pub_key: [u8; 32]) {
self.remote_ratchet_pub = Some(pub_key);
}
/// Set our outbound ratchet public key from the ratchet ring.
pub fn set_local_ratchet(&mut self, pub_key: [u8; 32]) {
self.local_ratchet_pub = Some(pub_key);
}
/// Return the local ratchet public key if ratchets are enabled here.
pub fn get_ratchet_for_announce(&self) -> Option<[u8; 32]> {
if self.ratchets_enabled {
self.local_ratchet_pub
} else {
None
}
}
pub fn set_packet_callback(&mut self, callback: PacketCallback) {
self.packet_callback = Some(callback);
}
pub fn set_link_established_callback(&mut self, callback: LinkEstablishedCallback) {
self.link_established_callback = Some(callback);
}
/// Callback invoked under `ProveApp` strategy; returning `true` emits a proof.
pub fn set_proof_requested_callback(&mut self, callback: ProofRequestedCallback) {
self.proof_requested_callback = Some(callback);
}
pub fn on_link_established(&self, link_id: [u8; 16]) {
if let Some(ref cb) = self.link_established_callback {
cb(link_id);
}
}
/// Register a request handler. Returns `false` if `path` is empty.
pub fn register_request_handler(
&mut self,
path: &str,
allow: AllowPolicy,
allowed_list: Option<Vec<[u8; 16]>>,
auto_compress: bool,
) -> bool {
if path.is_empty() {
return false;
}
let path_hash = truncated_hash(path.as_bytes());
self.request_handlers.insert(
path_hash,
RequestHandler {
path: path.to_string(),
allow,
allowed_list: allowed_list.unwrap_or_default(),
auto_compress,
},
);
true
}
pub fn deregister_request_handler(&mut self, path: &str) -> bool {
let path_hash = truncated_hash(path.as_bytes());
self.request_handlers.remove(&path_hash).is_some()
}
pub fn get_request_handler(&self, path_hash: &[u8; 16]) -> Option<&RequestHandler> {
self.request_handlers.get(path_hash)
}
pub fn check_request_allowed(
&self,
path_hash: &[u8; 16],
remote_identity_hash: Option<&[u8; 16]>,
) -> bool {
match self.request_handlers.get(path_hash) {
None => false,
Some(handler) => match handler.allow {
AllowPolicy::AllowNone => false,
AllowPolicy::AllowAll => true,
AllowPolicy::AllowList => {
if let Some(id_hash) = remote_identity_hash {
handler.allowed_list.iter().any(|h| h == id_hash)
} else {
false
}
}
},
}
}
/// Decrypt and dispatch an incoming packet.
///
/// LINKREQUEST (`0x02`) bypasses decryption and is handled by
/// [`Destination::incoming_link_request`]; DATA (`0x00`) packets
/// additionally fire the packet callback.
pub fn receive(
&self,
packet_type: u8,
data: &[u8],
identity: &Identity,
) -> Result<Option<Vec<u8>>, DestinationError> {
if packet_type == 0x02 {
return Ok(Some(data.to_vec()));
}
let plaintext = self.decrypt(data, identity)?;
if packet_type == 0x00
&& let Some(ref cb) = self.packet_callback
{
cb(&plaintext, data);
}
Ok(Some(plaintext))
}
pub fn should_prove(&self, packet_data: &[u8]) -> bool {
match self.proof_strategy {
ProofStrategy::ProveNone => false,
ProofStrategy::ProveAll => true,
ProofStrategy::ProveApp => {
if let Some(ref cb) = self.proof_requested_callback {
cb(packet_data)
} else {
false
}
}
}
}
pub fn incoming_link_request(&mut self, link_id: [u8; 16]) -> bool {
if !self.accept_link_requests {
return false;
}
self.links.push(link_id);
true
}
pub fn set_accepts_links(&mut self, accept: bool) {
self.accept_link_requests = accept;
}
/// Enable ratchet forward secrecy. If `enforce`, non-ratchet inbound ciphertext is rejected.
pub fn enable_ratchets(&mut self, enforce: bool) {
self.ratchets_enabled = true;
self.ratchets_enforced = enforce;
}
pub fn disable_ratchets(&mut self) {
self.ratchets_enabled = false;
self.ratchets_enforced = false;
}
pub fn ratchets_active(&self) -> bool {
self.ratchets_enabled
}
pub fn set_default_app_data(&mut self, app_data: DefaultAppData) {
self.default_app_data = Some(app_data);
}
pub fn clear_default_app_data(&mut self) {
self.default_app_data = None;
}
/// Return the current default app data, evaluating a dynamic generator if present.
pub fn resolve_app_data(&self) -> Option<Vec<u8>> {
match &self.default_app_data {
None => None,
Some(DefaultAppData::Static(data)) => Some(data.clone()),
Some(DefaultAppData::Dynamic(generator)) => generator(),
}
}
/// Build signed announce data for this destination and return `(announce_bytes, has_ratchet)`.
///
/// Wire layout:
/// - `announce_data = public_key(64) || name_hash(10) || random_hash(10) || [ratchet(32)] || signature(64) || [app_data]`
/// - `signed_data = dest_hash(16) || public_key(64) || name_hash(10) || random_hash(10) || [ratchet(32)] || [app_data]`
pub fn create_announce(
&mut self,
identity: &Identity,
app_data: Option<&[u8]>,
ratchet: Option<&[u8; 32]>,
tag: Option<&[u8]>,
now: f64,
) -> Result<(Vec<u8>, bool), DestinationError> {
if self.dest_type != DestType::Single {
return Err(DestinationError::EncryptionUnavailable);
}
if self.direction != Direction::In {
return Err(DestinationError::EncryptionUnavailable);
}
self.path_responses
.retain(|_, v| now <= v.timestamp + PR_TAG_WINDOW);
if let Some(tag_bytes) = tag
&& let Some(cached) = self.path_responses.get(tag_bytes)
{
return Ok((cached.announce_data.clone(), ratchet.is_some()));
}
let effective_app_data = app_data
.map(|d| d.to_vec())
.or_else(|| self.resolve_app_data());
let public_key = identity.get_public_key();
let random_bytes: [u8; 5] = rns_crypto::random::random_bytes(5).try_into().unwrap();
let ts_int = now as u64;
// Low 5 bytes of the u64 timestamp; wraps ~every 34 000 years.
let ts_bytes = &ts_int.to_be_bytes()[3..8];
let mut random_hash = [0u8; 10];
random_hash[..5].copy_from_slice(&random_bytes);
random_hash[5..].copy_from_slice(ts_bytes);
let has_ratchet = ratchet.is_some();
let mut signed_data = Vec::with_capacity(16 + 64 + 10 + 10 + 32 + 256);
signed_data.extend_from_slice(&self.hash);
signed_data.extend_from_slice(&public_key);
signed_data.extend_from_slice(&self.name_hash);
signed_data.extend_from_slice(&random_hash);
if let Some(r) = ratchet {
signed_data.extend_from_slice(r);
}
if let Some(ref ad) = effective_app_data {
signed_data.extend_from_slice(ad);
}
let signature = identity
.sign(&signed_data)
.ok_or(DestinationError::EncryptionUnavailable)?;
// `dest_hash` lives in the packet header, not the announce body.
let mut announce_data = Vec::with_capacity(64 + 10 + 10 + 32 + 64 + 256);
announce_data.extend_from_slice(&public_key);
announce_data.extend_from_slice(&self.name_hash);
announce_data.extend_from_slice(&random_hash);
if let Some(r) = ratchet {
announce_data.extend_from_slice(r);
}
announce_data.extend_from_slice(&signature);
if let Some(ref ad) = effective_app_data {
announce_data.extend_from_slice(ad);
}
if let Some(tag_bytes) = tag {
self.path_responses.insert(
tag_bytes.to_vec(),
PathResponseCache {
timestamp: now,
announce_data: announce_data.clone(),
},
);
}
Ok((announce_data, has_ratchet))
}
pub fn announce_packet(
&mut self,
identity: &Identity,
app_data: Option<&[u8]>,
ratchet: Option<&[u8; 32]>,
path_response: bool,
tag: Option<&[u8]>,
now: f64,
) -> Result<Vec<u8>, DestinationError> {
let (announce_data, has_ratchet) =
self.create_announce(identity, app_data, ratchet, tag, now)?;
let context = if path_response {
rns_wire::context::PacketContext::PathResponse
} else {
rns_wire::context::PacketContext::None
};
let flags = rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: has_ratchet,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Single,
packet_type: rns_wire::flags::PacketType::Announce,
};
let header = rns_wire::header::PacketHeader {
flags,
hops: 0,
transport_id: None,
destination_hash: self.hash,
context,
};
let mut raw = header.pack();
raw.extend_from_slice(&announce_data);
Ok(raw)
}
pub fn remove_link(&mut self, link_id: &[u8; 16]) {
self.links.retain(|id| id != link_id);
}
pub fn link_count(&self) -> usize {
self.links.len()
}
/// Hex-encoded destination hash for logging.
pub fn hex_hash(&self) -> String {
hex::encode(self.hash)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_single_destination() {
let id = Identity::new();
let dest =
Destination::new(Some(&id), Direction::In, DestType::Single, "test.app").unwrap();
assert_eq!(dest.dest_type, DestType::Single);
assert_ne!(dest.hash, [0u8; 16]);
}
#[test]
fn test_plain_destination() {
let dest = Destination::new(None, Direction::In, DestType::Plain, "test.app").unwrap();
assert_eq!(dest.dest_type, DestType::Plain);
}
#[test]
fn test_plain_with_identity_fails() {
let id = Identity::new();
assert!(Destination::new(Some(&id), Direction::In, DestType::Plain, "test.app").is_err());
}
#[test]
fn test_single_in_without_identity_auto_creates() {
let dest = Destination::new(None, Direction::In, DestType::Single, "test.app").unwrap();
assert!(dest.auto_identity().is_some());
assert!(dest.auto_identity().unwrap().has_private_key());
assert_ne!(dest.hash, [0u8; 16]);
let auto_hash = dest.auto_identity().unwrap().hash;
let python_hash_name = format!("test.app.{}", hex::encode(auto_hash));
let expected_name_hash = name_hash(&python_hash_name);
assert_eq!(dest.name_hash, expected_name_hash);
assert_eq!(
dest.hash,
Destination::compute_hash(&expected_name_hash, Some(&auto_hash))
);
assert_ne!(
dest.name_hash,
name_hash("test.app"),
"Python includes the generated identity hash in the name aspects before hashing"
);
}
#[test]
fn test_single_out_without_identity_fails() {
assert!(Destination::new(None, Direction::Out, DestType::Single, "test.app").is_err());
}
#[test]
fn test_dest_hash_deterministic() {
let id = Identity::new();
let dest1 =
Destination::new(Some(&id), Direction::In, DestType::Single, "test.app").unwrap();
let dest2 =
Destination::new(Some(&id), Direction::Out, DestType::Single, "test.app").unwrap();
assert_eq!(dest1.hash, dest2.hash);
}
#[test]
fn test_dest_hash_computation() {
let id = Identity::new();
let nh = name_hash("test.app");
let expected = Destination::compute_hash(&nh, Some(&id.hash));
let dest =
Destination::new(Some(&id), Direction::In, DestType::Single, "test.app").unwrap();
assert_eq!(dest.hash, expected);
}
#[test]
fn test_plain_dest_hash() {
let nh = name_hash("test.plain");
let expected = rns_crypto::sha::sha256(&nh);
let dest = Destination::new(None, Direction::In, DestType::Plain, "test.plain").unwrap();
assert_eq!(&dest.hash[..], &expected[..16]);
}
#[test]
fn test_different_apps_different_hashes() {
let id = Identity::new();
let d1 = Destination::new(Some(&id), Direction::In, DestType::Single, "app.one").unwrap();
let d2 = Destination::new(Some(&id), Direction::In, DestType::Single, "app.two").unwrap();
assert_ne!(d1.hash, d2.hash);
}
#[test]
fn test_hash_from_name_and_identity() {
let id = Identity::new();
let dest =
Destination::new(Some(&id), Direction::In, DestType::Single, "test.app").unwrap();
let computed = Destination::hash_from_name_and_identity("test.app", Some(&id.hash));
assert_eq!(dest.hash, computed);
}
#[test]
fn test_only_validate_signature_flag() {
let id = Identity::new();
let mut dest =
Destination::new(Some(&id), Direction::In, DestType::Single, "test.app").unwrap();
assert!(!dest.only_validate_signature);
dest.set_only_validate_signature(true);
assert!(dest.only_validate_signature);
}
#[test]
fn test_prove() {
let id = Identity::new();
let dest =
Destination::new(Some(&id), Direction::In, DestType::Single, "test.app").unwrap();
let packet_hash = rns_crypto::sha::sha256(b"test packet");
let proof = dest.prove(&packet_hash, &id, true).unwrap();
assert_eq!(proof.len(), 64);
let proof = dest.prove(&packet_hash, &id, false).unwrap();
assert_eq!(proof.len(), 32 + 64);
}
#[test]
fn test_prove_plain_fails() {
let dest = Destination::new(None, Direction::In, DestType::Plain, "test.app").unwrap();
let id = Identity::new();
assert!(dest.prove(b"test", &id, true).is_err());
}
#[test]
fn test_encrypt_with_ratchet() {
let id = Identity::new();
let dest =
Destination::new(Some(&id), Direction::Out, DestType::Single, "test.app").unwrap();
let ratchet_prv = rns_crypto::x25519::X25519PrivateKey::generate();
let ratchet_pub = ratchet_prv.public_key().to_bytes();
let plaintext = b"ratcheted message";
let ct = dest.encrypt(plaintext, &id, Some(&ratchet_pub)).unwrap();
assert!(id.decrypt(&ct, None, false).is_err());
let ratchet_prv_bytes = ratchet_prv.to_bytes();
let ratchets: Vec<&[u8; 32]> = vec![&ratchet_prv_bytes];
let pt = id.decrypt(&ct, Some(&ratchets), false).unwrap();
assert_eq!(&pt[..], plaintext);
}
#[test]
fn test_take_auto_identity() {
let mut dest = Destination::new(None, Direction::In, DestType::Single, "test.app").unwrap();
assert!(dest.auto_identity().is_some());
let taken = dest.take_auto_identity();
assert!(taken.is_some());
assert!(taken.unwrap().has_private_key());
assert!(dest.auto_identity().is_none());
}
}
+461
View File
@@ -0,0 +1,461 @@
use rns_crypto::ed25519::{Ed25519Error, Ed25519PrivateKey, Ed25519PublicKey};
use rns_crypto::hkdf::derive_key_64;
use rns_crypto::sha::truncated_hash;
use rns_crypto::token;
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use zeroize::{Zeroize, Zeroizing};
use crate::persistence;
use std::path::Path;
/// HKDF-derived key length: 32 bytes AES key || 32 bytes HMAC key.
pub const DERIVED_KEY_LENGTH: usize = 64;
/// Per-message overhead of `Identity::encrypt` before PKCS7 padding:
/// ephemeral X25519 public (32) + Token framing (48).
pub const IDENTITY_OVERHEAD: usize = 32 + rns_crypto::TOKEN_OVERHEAD;
#[derive(Debug, Error)]
pub enum IdentityError {
#[error("invalid private key length: expected 64, got {0}")]
InvalidPrivateKeyLength(usize),
#[error("invalid public key length: expected 64, got {0}")]
InvalidPublicKeyLength(usize),
#[error("signature verification failed")]
VerificationFailed,
#[error("decryption failed")]
DecryptionFailed,
#[error("ed25519 error: {0}")]
Ed25519(#[from] Ed25519Error),
#[error("io error: {0}")]
Io(#[from] std::io::Error),
}
/// A Reticulum identity: X25519 keypair for encryption + Ed25519 keypair for signing.
///
/// Wire representation:
/// - Private (64 B): `X25519_prv(32) || Ed25519_seed(32)`
/// - Public (64 B): `X25519_pub(32) || Ed25519_pub(32)`
/// - Hash (16 B): `SHA-256(public_64)[:16]`
pub struct Identity {
prv: Option<X25519PrivateKey>,
sig_prv: Option<Ed25519PrivateKey>,
pub_key: X25519PublicKey,
sig_pub: Ed25519PublicKey,
pub hash: [u8; 16],
}
impl Default for Identity {
fn default() -> Self {
Self::new()
}
}
impl Identity {
pub fn new() -> Self {
let prv = X25519PrivateKey::generate();
let sig_prv = Ed25519PrivateKey::generate();
let pub_key = prv.public_key();
let sig_pub = sig_prv.public_key();
let hash = Self::compute_hash(&pub_key, &sig_pub);
Self {
prv: Some(prv),
sig_prv: Some(sig_prv),
pub_key,
sig_pub,
hash,
}
}
pub fn from_private_key(key: &[u8]) -> Result<Self, IdentityError> {
if key.len() != 64 {
return Err(IdentityError::InvalidPrivateKeyLength(key.len()));
}
let mut x_bytes = Zeroizing::new([0u8; 32]);
x_bytes.copy_from_slice(&key[..32]);
let mut ed_bytes = Zeroizing::new([0u8; 32]);
ed_bytes.copy_from_slice(&key[32..]);
let prv = X25519PrivateKey::from_bytes(&x_bytes);
let sig_prv = Ed25519PrivateKey::from_bytes(&ed_bytes);
let pub_key = prv.public_key();
let sig_pub = sig_prv.public_key();
let hash = Self::compute_hash(&pub_key, &sig_pub);
Ok(Self {
prv: Some(prv),
sig_prv: Some(sig_prv),
pub_key,
sig_pub,
hash,
})
}
/// Construct a verify/encrypt-only identity from its 64-byte public key.
pub fn from_public_key(key: &[u8]) -> Result<Self, IdentityError> {
if key.len() != 64 {
return Err(IdentityError::InvalidPublicKeyLength(key.len()));
}
let mut x_bytes = [0u8; 32];
x_bytes.copy_from_slice(&key[..32]);
let mut ed_bytes = [0u8; 32];
ed_bytes.copy_from_slice(&key[32..]);
let pub_key = X25519PublicKey::from_bytes(&x_bytes);
let sig_pub = Ed25519PublicKey::from_bytes(&ed_bytes)?;
let hash = Self::compute_hash(&pub_key, &sig_pub);
Ok(Self {
prv: None,
sig_prv: None,
pub_key,
sig_pub,
hash,
})
}
/// Load an identity from file, accepting either the current msgpack envelope
/// or a legacy raw 64-byte private key.
pub fn from_file(path: &Path) -> Result<Self, IdentityError> {
let data = std::fs::read(path)?;
if let Ok(persisted) = rmp_serde::from_slice::<IdentityPersisted>(&data) {
return Self::from_private_key(&persisted.private_key);
}
Self::from_private_key(&data)
}
/// Persist the identity as the raw 64-byte private key used by the Python
/// reference implementation, so identity files are interchangeable.
pub fn to_file(&self, path: &Path) -> Result<(), IdentityError> {
let key = self
.get_private_key()
.ok_or(IdentityError::DecryptionFailed)?;
persistence::atomic_write(path, &*key)?;
Ok(())
}
/// Return the 64-byte private key (`X25519_prv || Ed25519_seed`), zeroised on drop.
pub fn get_private_key(&self) -> Option<Zeroizing<[u8; 64]>> {
let prv = self.prv.as_ref()?;
let sig_prv = self.sig_prv.as_ref()?;
let mut key = Zeroizing::new([0u8; 64]);
key[..32].copy_from_slice(&prv.to_bytes());
key[32..].copy_from_slice(&sig_prv.to_bytes());
Some(key)
}
/// Return the 64-byte public key (`X25519_pub || Ed25519_pub`).
pub fn get_public_key(&self) -> [u8; 64] {
let mut key = [0u8; 64];
key[..32].copy_from_slice(&self.pub_key.to_bytes());
key[32..].copy_from_slice(&self.sig_pub.to_bytes());
key
}
pub fn has_private_key(&self) -> bool {
self.prv.is_some() && self.sig_prv.is_some()
}
pub fn get_signing_key(&self) -> Option<Ed25519PrivateKey> {
self.sig_prv
.as_ref()
.map(|k| Ed25519PrivateKey::from_bytes(&k.to_bytes()))
}
/// Sign `message` with the Ed25519 key; `None` if this is a public-only identity.
pub fn sign(&self, message: &[u8]) -> Option<[u8; 64]> {
self.sig_prv.as_ref().map(|key| key.sign(message))
}
pub fn verify(&self, message: &[u8], signature: &[u8; 64]) -> bool {
self.sig_pub.verify(message, signature).is_ok()
}
/// Encrypt `plaintext` for this identity using ECIES.
///
/// Output layout: `ephemeral_X25519_pub(32) || IV(16) || AES-256-CBC(PKCS7(pt)) || HMAC(32)`.
///
/// Passing a `ratchet` public key substitutes it for the identity's X25519
/// public key in the ECDH, giving forward secrecy against later key
/// compromise.
pub fn encrypt(
&self,
plaintext: &[u8],
ratchet: Option<&[u8; 32]>,
) -> Result<Vec<u8>, IdentityError> {
let ephemeral = X25519PrivateKey::generate();
let ephemeral_pub = ephemeral.public_key();
let target = match ratchet {
Some(r) => X25519PublicKey::from_bytes(r),
None => self.pub_key.clone(),
};
let mut shared = ephemeral.exchange(&target);
let derived =
derive_key_64(&shared, &self.hash).map_err(|_| IdentityError::DecryptionFailed);
shared.zeroize();
let derived = derived?;
let ciphertext =
token::encrypt(plaintext, &derived).map_err(|_| IdentityError::DecryptionFailed)?;
let mut result = Vec::with_capacity(32 + ciphertext.len());
result.extend_from_slice(&ephemeral_pub.to_bytes());
result.extend_from_slice(&ciphertext);
Ok(result)
}
/// Decrypt ciphertext addressed to this identity, trying each ratchet key
/// before falling back to the identity key (unless `enforce_ratchets`).
pub fn decrypt(
&self,
ciphertext: &[u8],
ratchets: Option<&[&[u8; 32]]>,
enforce_ratchets: bool,
) -> Result<Vec<u8>, IdentityError> {
if ciphertext.len() < 32 {
return Err(IdentityError::DecryptionFailed);
}
let mut peer_pub_bytes = [0u8; 32];
peer_pub_bytes.copy_from_slice(&ciphertext[..32]);
let peer_pub = X25519PublicKey::from_bytes(&peer_pub_bytes);
let ct = &ciphertext[32..];
if let Some(ratchets) = ratchets {
for ratchet in ratchets {
let ratchet_prv = X25519PrivateKey::from_bytes(ratchet);
let mut shared = ratchet_prv.exchange(&peer_pub);
let derived_result = derive_key_64(&shared, &self.hash);
shared.zeroize();
if let Ok(derived) = derived_result
&& let Ok(plaintext) = token::decrypt(ct, &derived)
{
return Ok(plaintext);
}
}
}
if enforce_ratchets {
return Err(IdentityError::DecryptionFailed);
}
let prv = self.prv.as_ref().ok_or(IdentityError::DecryptionFailed)?;
let mut shared = prv.exchange(&peer_pub);
let derived_result =
derive_key_64(&shared, &self.hash).map_err(|_| IdentityError::DecryptionFailed);
shared.zeroize();
let derived = derived_result?;
let plaintext =
token::decrypt(ct, &derived).map_err(|_| IdentityError::DecryptionFailed)?;
Ok(plaintext)
}
/// Sign `packet_hash` and return proof bytes.
///
/// `implicit_proof = true` returns the 64-byte signature alone; `false`
/// returns `packet_hash(32) || signature(64)` (96 bytes).
pub fn prove(
&self,
packet_hash: &[u8],
implicit_proof: bool,
) -> Result<Vec<u8>, IdentityError> {
let signature = self
.sign(packet_hash)
.ok_or(IdentityError::DecryptionFailed)?;
if implicit_proof {
Ok(signature.to_vec())
} else {
let mut proof_data = Vec::with_capacity(packet_hash.len() + 64);
proof_data.extend_from_slice(packet_hash);
proof_data.extend_from_slice(&signature);
Ok(proof_data)
}
}
fn compute_hash(pub_key: &X25519PublicKey, sig_pub: &Ed25519PublicKey) -> [u8; 16] {
let mut combined = [0u8; 64];
combined[..32].copy_from_slice(&pub_key.to_bytes());
combined[32..].copy_from_slice(&sig_pub.to_bytes());
truncated_hash(&combined)
}
}
// Msgpack envelope wrapping the raw 64-byte private key on disk.
#[derive(Serialize, Deserialize)]
struct IdentityPersisted {
private_key: Vec<u8>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_generate_identity() {
let id = Identity::new();
assert!(id.has_private_key());
assert_ne!(id.hash, [0u8; 16]);
}
#[test]
fn test_private_key_roundtrip() {
let id1 = Identity::new();
let prv = id1.get_private_key().unwrap();
let id2 = Identity::from_private_key(&*prv).unwrap();
assert_eq!(id1.hash, id2.hash);
assert_eq!(id1.get_public_key(), id2.get_public_key());
}
#[test]
fn test_public_key_roundtrip() {
let id1 = Identity::new();
let pub_key = id1.get_public_key();
let id2 = Identity::from_public_key(&pub_key).unwrap();
assert_eq!(id1.hash, id2.hash);
assert!(!id2.has_private_key());
}
#[test]
fn test_sign_verify() {
let id = Identity::new();
let msg = b"hello reticulum";
let sig = id.sign(msg).unwrap();
assert!(id.verify(msg, &sig));
}
#[test]
fn test_sign_verify_wrong_message() {
let id = Identity::new();
let sig = id.sign(b"correct").unwrap();
assert!(!id.verify(b"wrong", &sig));
}
#[test]
fn test_encrypt_decrypt() {
let id = Identity::new();
let plaintext = b"secret message";
let ct = id.encrypt(plaintext, None).unwrap();
let pt = id.decrypt(&ct, None, false).unwrap();
assert_eq!(&pt, plaintext);
}
#[test]
fn test_encrypt_decrypt_with_ratchet() {
let id = Identity::new();
let ratchet_prv = rns_crypto::x25519::X25519PrivateKey::generate();
let ratchet_pub = ratchet_prv.public_key().to_bytes();
let ratchet_prv_bytes = ratchet_prv.to_bytes();
let plaintext = b"ratcheted message";
let ct = id.encrypt(plaintext, Some(&ratchet_pub)).unwrap();
assert!(id.decrypt(&ct, None, false).is_err());
let ratchets: Vec<&[u8; 32]> = vec![&ratchet_prv_bytes];
let pt = id.decrypt(&ct, Some(&ratchets), false).unwrap();
assert_eq!(&pt, plaintext);
}
#[test]
fn test_cross_identity_encrypt_decrypt() {
let sender = Identity::new();
let receiver = Identity::new();
let plaintext = b"from sender to receiver";
let ct = receiver.encrypt(plaintext, None).unwrap();
let pt = receiver.decrypt(&ct, None, false).unwrap();
assert_eq!(&pt, plaintext);
assert!(sender.decrypt(&ct, None, false).is_err());
}
#[test]
fn test_public_key_only_cannot_sign() {
let id = Identity::new();
let pub_id = Identity::from_public_key(&id.get_public_key()).unwrap();
assert!(pub_id.sign(b"test").is_none());
}
#[test]
fn test_hash_is_truncated_sha256() {
let id = Identity::new();
let full = rns_crypto::sha::sha256(&id.get_public_key());
assert_eq!(&id.hash[..], &full[..16]);
}
#[test]
fn test_file_roundtrip() {
let dir = std::env::temp_dir().join("reticulum_identity_test_msgpack");
let _ = std::fs::create_dir_all(&dir);
let path = dir.join("test_identity");
let id1 = Identity::new();
id1.to_file(&path).unwrap();
let id2 = Identity::from_file(&path).unwrap();
assert_eq!(id1.hash, id2.hash);
assert_eq!(id1.get_public_key(), id2.get_public_key());
assert_eq!(id1.get_private_key(), id2.get_private_key());
let _ = std::fs::remove_file(&path);
let _ = std::fs::remove_dir(&dir);
}
#[test]
fn test_file_backward_compat_raw() {
let dir = std::env::temp_dir().join("reticulum_identity_test_compat");
let _ = std::fs::create_dir_all(&dir);
let path = dir.join("raw_identity");
let id1 = Identity::new();
let key = id1.get_private_key().unwrap();
// Legacy format: raw 64-byte private key, no msgpack envelope.
std::fs::write(&path, &key).unwrap();
let id2 = Identity::from_file(&path).unwrap();
assert_eq!(id1.hash, id2.hash);
assert_eq!(id1.get_public_key(), id2.get_public_key());
let _ = std::fs::remove_file(&path);
let _ = std::fs::remove_dir(&dir);
}
#[test]
fn test_prove_implicit() {
let id = Identity::new();
let packet_hash = rns_crypto::sha::sha256(b"test packet");
let proof = id.prove(&packet_hash, true).unwrap();
assert_eq!(proof.len(), 64);
let mut sig = [0u8; 64];
sig.copy_from_slice(&proof);
assert!(id.verify(&packet_hash, &sig));
}
#[test]
fn test_prove_explicit() {
let id = Identity::new();
let packet_hash = rns_crypto::sha::sha256(b"test packet");
let proof = id.prove(&packet_hash, false).unwrap();
assert_eq!(proof.len(), 32 + 64);
assert_eq!(&proof[..32], &packet_hash);
let mut sig = [0u8; 64];
sig.copy_from_slice(&proof[32..]);
assert!(id.verify(&packet_hash, &sig));
}
#[test]
fn test_prove_no_private_key_fails() {
let id = Identity::new();
let pub_id = Identity::from_public_key(&id.get_public_key()).unwrap();
assert!(pub_id.prove(b"test", true).is_err());
}
}
+139
View File
@@ -0,0 +1,139 @@
use rns_crypto::hkdf::hkdf_sha256;
use rns_crypto::sha::sha256;
use thiserror::Error;
// Fixed IFAC HKDF salt. Shared with the Python reference; changing it breaks interop.
const IFAC_SALT: &str = "adf54d882c9a9b80771eb4995d702d4a3e733391b2a0f53f416d9f907e55cff8";
#[derive(Debug, Error)]
pub enum IfacError {
#[error("HKDF derivation failed: {0}")]
HkdfFailed(#[from] rns_crypto::hkdf::HkdfError),
#[error("invalid IFAC salt hex")]
InvalidSalt,
}
/// Derive the 64-byte IFAC (Interface Access Control) key.
///
/// `ifac_origin` concatenates `SHA-256(network_name)` and `SHA-256(passphrase)`
/// for whichever fields are `Some(_)` (a `None` field is omitted, so `None`
/// and `Some("")` differ), then HKDF-SHA256 expands it under the fixed salt.
/// First 32 bytes → X25519 private; second 32 → Ed25519 seed.
pub fn derive_ifac_key(
network_name: Option<&str>,
passphrase: Option<&str>,
) -> Result<[u8; 64], IfacError> {
let mut ifac_origin = Vec::new();
if let Some(name) = network_name {
ifac_origin.extend_from_slice(&sha256(name.as_bytes()));
}
if let Some(key) = passphrase {
ifac_origin.extend_from_slice(&sha256(key.as_bytes()));
}
let ifac_origin_hash = sha256(&ifac_origin);
let salt = hex_decode(IFAC_SALT).ok_or(IfacError::InvalidSalt)?;
let derived = hkdf_sha256(64, &ifac_origin_hash, Some(&salt), None)?;
let mut key = [0u8; 64];
key.copy_from_slice(&derived);
Ok(key)
}
/// Build the IFAC identity plus a self-signature over `SHA-256(ifac_key)`.
///
/// Returns `(identity, ifac_key, signature)`.
pub fn derive_ifac_identity(
network_name: Option<&str>,
passphrase: Option<&str>,
) -> Result<(crate::identity::Identity, [u8; 64], [u8; 64]), IfacError> {
let ifac_key = derive_ifac_key(network_name, passphrase)?;
let identity = crate::identity::Identity::from_private_key(&ifac_key)
.map_err(|_| IfacError::InvalidSalt)?;
let key_hash = sha256(&ifac_key);
let signature = identity.sign(&key_hash).ok_or(IfacError::InvalidSalt)?;
Ok((identity, ifac_key, signature))
}
/// Split IFAC key into `(signing_key, masking_key)`, each 32 bytes.
pub fn split_ifac_key(key: &[u8; 64]) -> (&[u8], &[u8]) {
(&key[..32], &key[32..])
}
fn hex_decode(s: &str) -> Option<Vec<u8>> {
if !s.len().is_multiple_of(2) {
return None;
}
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok())
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_ifac_derivation_deterministic() {
let key1 = derive_ifac_key(Some("testnet"), Some("password")).unwrap();
let key2 = derive_ifac_key(Some("testnet"), Some("password")).unwrap();
assert_eq!(key1, key2);
}
#[test]
fn test_ifac_different_inputs_different_keys() {
let key1 = derive_ifac_key(Some("net1"), Some("pass1")).unwrap();
let key2 = derive_ifac_key(Some("net2"), Some("pass2")).unwrap();
assert_ne!(key1, key2);
}
#[test]
fn test_ifac_none_inputs() {
let key = derive_ifac_key(None, None).unwrap();
assert_eq!(key.len(), 64);
}
#[test]
fn test_ifac_key_split() {
let key = derive_ifac_key(Some("test"), Some("test")).unwrap();
let (signing, masking) = split_ifac_key(&key);
assert_eq!(signing.len(), 32);
assert_eq!(masking.len(), 32);
}
#[test]
fn test_ifac_partial_inputs() {
let key_name_only = derive_ifac_key(Some("testnet"), None).unwrap();
let key_both = derive_ifac_key(Some("testnet"), Some("password")).unwrap();
assert_ne!(key_name_only, key_both);
let key_pass_only = derive_ifac_key(None, Some("password")).unwrap();
assert_ne!(key_pass_only, key_both);
}
#[test]
fn test_ifac_none_vs_empty() {
// `None` omits the field from the origin; `Some("")` includes SHA-256("").
let key_none = derive_ifac_key(None, None).unwrap();
let key_empty = derive_ifac_key(Some(""), Some("")).unwrap();
assert_ne!(key_none, key_empty);
}
#[test]
fn test_derive_ifac_identity() {
let (identity, ifac_key, signature) =
derive_ifac_identity(Some("testnet"), Some("password")).unwrap();
assert!(identity.has_private_key());
assert_eq!(ifac_key.len(), 64);
let key_hash = sha256(&ifac_key);
assert!(identity.verify(&key_hash, &signature));
}
}
@@ -0,0 +1,664 @@
use std::collections::HashMap;
use std::io::Cursor;
use std::path::Path;
use crate::persistence;
use rmpv::Value;
/// Record of a destination learnt from a validated announce.
#[derive(Debug, Clone)]
pub struct KnownDestination {
/// Learn time as a Unix timestamp (seconds).
pub timestamp: f64,
/// Packet hash of the announce that introduced the destination.
pub packet_hash: [u8; 32],
/// Concatenated `X25519_pub || Ed25519_pub`.
pub public_key: [u8; 64],
pub app_data: Option<Vec<u8>>,
/// Pinned via `retain()` — `cleanup()` skips this entry regardless of age.
pub retained: bool,
}
/// Table of known destinations, keyed by 16-byte destination hash.
pub struct KnownDestinations {
entries: HashMap<[u8; 16], KnownDestination>,
}
impl KnownDestinations {
pub fn new() -> Self {
Self {
entries: HashMap::new(),
}
}
/// Insert or refresh the entry for `dest_hash`. The `retained` flag is
/// preserved on update so a fresh announce never un-pins an entry.
pub fn remember(
&mut self,
dest_hash: [u8; 16],
timestamp: f64,
packet_hash: [u8; 32],
public_key: [u8; 64],
app_data: Option<Vec<u8>>,
) {
match self.entries.get_mut(&dest_hash) {
Some(existing) => {
existing.timestamp = timestamp;
existing.packet_hash = packet_hash;
existing.public_key = public_key;
existing.app_data = app_data;
// `retained` preserved across refresh.
}
None => {
self.entries.insert(
dest_hash,
KnownDestination {
timestamp,
packet_hash,
public_key,
app_data,
retained: false,
},
);
}
}
}
pub fn get(&self, dest_hash: &[u8; 16]) -> Option<&KnownDestination> {
self.entries.get(dest_hash)
}
pub fn contains(&self, dest_hash: &[u8; 16]) -> bool {
self.entries.contains_key(dest_hash)
}
pub fn recall_app_data(&self, dest_hash: &[u8; 16]) -> Option<Vec<u8>> {
self.entries.get(dest_hash).and_then(|e| e.app_data.clone())
}
/// Linear scan for an entry whose `SHA-256(public_key)[:16]` matches `identity_hash`.
pub fn recall_by_identity(
&self,
identity_hash: &[u8; 16],
) -> Option<(&[u8; 16], &KnownDestination)> {
for (dest_hash, entry) in &self.entries {
let computed_id_hash = rns_crypto::sha::truncated_hash(&entry.public_key);
if &computed_id_hash == identity_hash {
return Some((dest_hash, entry));
}
}
None
}
/// Check membership across this table plus a set of locally-registered
/// destination hashes (the fallback used by transport path resolution).
pub fn is_known_or_registered(
&self,
dest_hash: &[u8; 16],
registered: &std::collections::HashSet<[u8; 16]>,
) -> bool {
self.entries.contains_key(dest_hash) || registered.contains(dest_hash)
}
pub fn remove(&mut self, dest_hash: &[u8; 16]) -> Option<KnownDestination> {
self.entries.remove(dest_hash)
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = (&[u8; 16], &KnownDestination)> {
self.entries.iter()
}
/// Pin `dest_hash` so `cleanup()` will never consider it stale.
pub fn retain(&mut self, dest_hash: &[u8; 16]) {
if let Some(entry) = self.entries.get_mut(dest_hash) {
entry.retained = true;
}
}
/// Release a pin set by `retain()`. The entry's `timestamp` (last-seen
/// announce wall-clock) drives `cleanup()` from now on.
pub fn unretain(&mut self, dest_hash: &[u8; 16]) {
if let Some(entry) = self.entries.get_mut(dest_hash) {
entry.retained = false;
}
}
/// Drop stale entries past `destination_timeout_secs`. `has_path` is a
/// caller-supplied path-table lookup (this crate doesn't depend on
/// rns-transport). Returns the hashes that were dropped.
pub fn cleanup(
&mut self,
now: f64,
destination_timeout_secs: f64,
has_path: impl Fn(&[u8; 16]) -> bool,
) -> Vec<[u8; 16]> {
let mut to_remove = Vec::new();
for (dest_hash, entry) in &self.entries {
// Keep: pinned, or currently routable.
if entry.retained || has_path(dest_hash) {
continue;
}
let age = now - entry.timestamp;
if age > destination_timeout_secs {
to_remove.push(*dest_hash);
}
}
for hash in &to_remove {
self.entries.remove(hash);
}
to_remove
}
/// Atomically write the table to `path` in Python Reticulum's canonical
/// msgpack format. The loader still accepts older Rust `RNS\x03` files.
pub fn save(&self, path: &Path) -> std::io::Result<()> {
let serialized = self.serialize();
persistence::atomic_write(path, &serialized)
}
/// Load the table from `path`; returns an empty table on missing or
/// unparseable input.
pub fn load(path: &Path) -> std::io::Result<Self> {
match persistence::read_file(path)? {
Some(data) => Ok(Self::deserialize(&data).unwrap_or_else(|_| Self::new())),
None => Ok(Self::new()),
}
}
/// Merge `other` into self; existing entries win on key conflict.
pub fn merge(&mut self, other: &KnownDestinations) {
for (hash, entry) in &other.entries {
self.entries.entry(*hash).or_insert_with(|| entry.clone());
}
}
const MAGIC: &'static [u8] = b"RNS\x03";
// Legacy Rust sidecar/on-disk format (little-endian):
// magic: b"RNS\x03"
// count: u32
// count × (dest_hash[16], timestamp: f64, packet_hash[32], public_key[64],
// has_app_data: u8, app_data_len: u32, app_data[app_data_len],
// retained: u8 (0|1))
fn serialize(&self) -> Vec<u8> {
let mut entries = Vec::with_capacity(self.entries.len());
for (hash, entry) in &self.entries {
let app_data = entry
.app_data
.as_ref()
.map(|data| Value::Binary(data.clone()))
.unwrap_or(Value::Nil);
let last_use = if entry.retained { -1i64 } else { 0i64 };
entries.push((
Value::Binary(hash.to_vec()),
Value::Array(vec![
Value::F64(entry.timestamp),
Value::Binary(entry.packet_hash.to_vec()),
Value::Binary(entry.public_key.to_vec()),
app_data,
Value::Integer(last_use.into()),
]),
));
}
let mut buf = Vec::new();
rmpv::encode::write_value(&mut buf, &Value::Map(entries))
.expect("writing msgpack to Vec cannot fail");
buf
}
// Kept as a regression fixture for loading the legacy Rust sidecar format.
#[allow(dead_code)]
fn serialize_legacy_rust(&self) -> Vec<u8> {
let mut buf = Vec::new();
buf.extend_from_slice(Self::MAGIC);
buf.extend_from_slice(&(self.entries.len() as u32).to_le_bytes());
for (hash, entry) in &self.entries {
buf.extend_from_slice(hash);
buf.extend_from_slice(&entry.timestamp.to_le_bytes());
buf.extend_from_slice(&entry.packet_hash);
buf.extend_from_slice(&entry.public_key);
match &entry.app_data {
Some(ad) => {
buf.push(1);
buf.extend_from_slice(&(ad.len() as u32).to_le_bytes());
buf.extend_from_slice(ad);
}
None => {
buf.push(0);
buf.extend_from_slice(&0u32.to_le_bytes());
}
}
buf.push(if entry.retained { 1 } else { 0 });
}
buf
}
fn deserialize(data: &[u8]) -> Result<Self, &'static str> {
if !data.starts_with(Self::MAGIC) {
return Self::deserialize_python_msgpack(data);
}
let data = &data[Self::MAGIC.len()..];
if data.len() < 4 {
return Err("too short");
}
let count =
u32::from_le_bytes(data[..4].try_into().map_err(|_| "corrupt header")?) as usize;
let mut pos = 4;
let mut entries = HashMap::new();
for _ in 0..count {
if pos + 16 + 8 + 32 + 64 + 1 + 4 > data.len() {
return Err("truncated entry");
}
let mut dest_hash = [0u8; 16];
dest_hash.copy_from_slice(&data[pos..pos + 16]);
pos += 16;
let timestamp = f64::from_le_bytes(
data[pos..pos + 8]
.try_into()
.map_err(|_| "corrupt timestamp")?,
);
pos += 8;
let mut packet_hash = [0u8; 32];
packet_hash.copy_from_slice(&data[pos..pos + 32]);
pos += 32;
let mut public_key = [0u8; 64];
public_key.copy_from_slice(&data[pos..pos + 64]);
pos += 64;
let has_app_data = data[pos];
pos += 1;
let ad_len = u32::from_le_bytes(
data[pos..pos + 4]
.try_into()
.map_err(|_| "corrupt app_data length")?,
) as usize;
pos += 4;
let app_data = if has_app_data == 1 {
if pos + ad_len > data.len() {
return Err("truncated app_data");
}
let ad = data[pos..pos + ad_len].to_vec();
pos += ad_len;
Some(ad)
} else {
None
};
if pos + 1 > data.len() {
return Err("truncated retained flag");
}
let retained = data[pos] != 0;
pos += 1;
entries.insert(
dest_hash,
KnownDestination {
timestamp,
packet_hash,
public_key,
app_data,
retained,
},
);
}
Ok(Self { entries })
}
/// Parse Python Reticulum's canonical `storage/known_destinations` file.
///
/// Python writes msgpack as `{dest_hash: [timestamp, packet_hash,
/// public_key, app_data, last_use]}` and transparently upgrades older
/// four-field entries by treating `last_use` as `0`.
fn deserialize_python_msgpack(data: &[u8]) -> Result<Self, &'static str> {
let value = rmpv::decode::read_value(&mut Cursor::new(data))
.map_err(|_| "invalid python known_destinations msgpack")?;
let Value::Map(map) = value else {
return Err("python known_destinations root is not a map");
};
let mut entries = HashMap::new();
for (dest_value, entry_value) in map {
let dest_bytes = Self::msgpack_bytes(&dest_value)?;
if dest_bytes.len() != 16 {
// Python ignores entries whose key is not a truncated hash.
continue;
}
let mut dest_hash = [0u8; 16];
dest_hash.copy_from_slice(&dest_bytes);
let Value::Array(fields) = entry_value else {
return Err("python known_destinations entry is not an array");
};
if fields.len() < 4 {
return Err("python known_destinations entry is too short");
}
let timestamp = Self::msgpack_number(&fields[0])?;
let packet_hash_bytes = Self::msgpack_bytes(&fields[1])?;
let public_key_bytes = Self::msgpack_bytes(&fields[2])?;
let app_data = match &fields[3] {
Value::Nil => None,
value => Some(Self::msgpack_bytes(value)?),
};
let last_use = fields
.get(4)
.map(Self::msgpack_number)
.transpose()?
.unwrap_or(0.0);
if packet_hash_bytes.len() != 32 {
return Err("python known_destinations packet hash has invalid length");
}
if public_key_bytes.len() != 64 {
return Err("python known_destinations public key has invalid length");
}
let mut packet_hash = [0u8; 32];
packet_hash.copy_from_slice(&packet_hash_bytes);
let mut public_key = [0u8; 64];
public_key.copy_from_slice(&public_key_bytes);
entries.insert(
dest_hash,
KnownDestination {
timestamp,
packet_hash,
public_key,
app_data,
retained: last_use < 0.0,
},
);
}
Ok(Self { entries })
}
fn msgpack_bytes(value: &Value) -> Result<Vec<u8>, &'static str> {
match value {
Value::Binary(bytes) => Ok(bytes.clone()),
Value::String(s) => s
.as_str()
.map(|s| s.as_bytes().to_vec())
.ok_or("msgpack string is not valid utf-8"),
_ => Err("msgpack value is not bytes"),
}
}
fn msgpack_number(value: &Value) -> Result<f64, &'static str> {
match value {
Value::F64(value) => Ok(*value),
Value::F32(value) => Ok((*value).into()),
Value::Integer(value) => value
.as_i64()
.map(|value| value as f64)
.or_else(|| value.as_u64().map(|value| value as f64))
.ok_or("msgpack integer does not fit in f64"),
_ => Err("msgpack value is not numeric"),
}
}
}
impl Default for KnownDestinations {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_remember_and_get() {
let mut kd = KnownDestinations::new();
let hash = [0xAA; 16];
kd.remember(hash, 1234.5, [0xBB; 32], [0xCC; 64], Some(b"data".to_vec()));
let entry = kd.get(&hash).unwrap();
assert_eq!(entry.timestamp, 1234.5);
assert_eq!(entry.app_data.as_deref(), Some(b"data".as_slice()));
assert!(!entry.retained);
}
#[test]
fn test_remember_preserves_retained_on_refresh() {
let mut kd = KnownDestinations::new();
let hash = [0xAA; 16];
kd.remember(hash, 100.0, [0; 32], [0; 64], None);
kd.retain(&hash);
assert!(kd.get(&hash).unwrap().retained);
kd.remember(hash, 200.0, [1; 32], [1; 64], Some(b"new".to_vec()));
let entry = kd.get(&hash).unwrap();
assert_eq!(entry.timestamp, 200.0);
assert_eq!(entry.app_data.as_deref(), Some(b"new".as_slice()));
assert!(entry.retained);
}
#[test]
fn test_serialize_deserialize_round_trip() {
let mut kd = KnownDestinations::new();
kd.remember(
[0x01; 16],
100.0,
[0x02; 32],
[0x03; 64],
Some(b"hello".to_vec()),
);
kd.remember([0x04; 16], 200.0, [0x05; 32], [0x06; 64], None);
kd.retain(&[0x04; 16]);
let serialized = kd.serialize();
assert!(
!serialized.starts_with(KnownDestinations::MAGIC),
"public save format must remain Python-compatible msgpack"
);
let kd2 = KnownDestinations::deserialize(&serialized).unwrap();
assert_eq!(kd2.len(), 2);
let e1 = kd2.get(&[0x01; 16]).unwrap();
assert_eq!(e1.timestamp, 100.0);
assert_eq!(e1.app_data.as_deref(), Some(b"hello".as_slice()));
assert!(!e1.retained);
let e2 = kd2.get(&[0x04; 16]).unwrap();
assert!(e2.app_data.is_none());
assert!(e2.retained);
}
#[test]
fn test_deserialize_rejects_unknown_magic() {
let mut buf = b"OLD\x02".to_vec();
buf.extend_from_slice(&0u32.to_le_bytes());
assert!(KnownDestinations::deserialize(&buf).is_err());
}
#[test]
fn test_deserialize_legacy_rust_format() {
let mut kd = KnownDestinations::new();
kd.remember(
[0xAA; 16],
42.0,
[0xBB; 32],
[0xCC; 64],
Some(b"legacy".to_vec()),
);
kd.retain(&[0xAA; 16]);
let serialized = kd.serialize_legacy_rust();
assert!(serialized.starts_with(KnownDestinations::MAGIC));
let loaded = KnownDestinations::deserialize(&serialized).unwrap();
let entry = loaded.get(&[0xAA; 16]).unwrap();
assert_eq!(entry.timestamp, 42.0);
assert_eq!(entry.packet_hash, [0xBB; 32]);
assert_eq!(entry.public_key, [0xCC; 64]);
assert_eq!(entry.app_data.as_deref(), Some(b"legacy".as_slice()));
assert!(entry.retained);
}
#[test]
fn test_file_persistence() {
let dir = std::env::temp_dir().join("reticulum_kd_test");
let _ = std::fs::create_dir_all(&dir);
let path = dir.join("known_destinations");
let mut kd = KnownDestinations::new();
kd.remember(
[0xAA; 16],
42.0,
[0xBB; 32],
[0xCC; 64],
Some(b"test".to_vec()),
);
kd.save(&path).unwrap();
assert!(
!std::fs::read(&path)
.unwrap()
.starts_with(KnownDestinations::MAGIC)
);
let kd2 = KnownDestinations::load(&path).unwrap();
assert_eq!(kd2.len(), 1);
let entry = kd2.get(&[0xAA; 16]).unwrap();
assert_eq!(entry.timestamp, 42.0);
let _ = std::fs::remove_file(&path);
let _ = std::fs::remove_dir(&dir);
}
#[test]
fn test_merge() {
let mut kd1 = KnownDestinations::new();
kd1.remember([0x01; 16], 100.0, [0; 32], [0; 64], None);
kd1.remember([0x02; 16], 200.0, [0; 32], [0; 64], None);
let mut kd2 = KnownDestinations::new();
// Same key as kd1, different payload, to probe conflict resolution.
kd2.remember([0x02; 16], 300.0, [1; 32], [1; 64], None);
kd2.remember([0x03; 16], 400.0, [0; 32], [0; 64], None);
kd1.merge(&kd2);
assert_eq!(kd1.len(), 3);
let e2 = kd1.get(&[0x02; 16]).unwrap();
assert_eq!(e2.timestamp, 200.0);
}
#[test]
fn test_recall_app_data() {
let mut kd = KnownDestinations::new();
let hash1 = [0xAA; 16];
let hash2 = [0xBB; 16];
kd.remember(
hash1,
100.0,
[0; 32],
[0; 64],
Some(b"my app data".to_vec()),
);
kd.remember(hash2, 200.0, [0; 32], [0; 64], None);
assert_eq!(kd.recall_app_data(&hash1), Some(b"my app data".to_vec()));
assert_eq!(kd.recall_app_data(&hash2), None);
assert_eq!(kd.recall_app_data(&[0xCC; 16]), None);
}
#[test]
fn test_retain_unretain_round_trip() {
let mut kd = KnownDestinations::new();
let hash = [0xAA; 16];
kd.remember(hash, 100.0, [0; 32], [0; 64], None);
assert!(!kd.get(&hash).unwrap().retained);
kd.retain(&hash);
assert!(kd.get(&hash).unwrap().retained);
kd.unretain(&hash);
assert!(!kd.get(&hash).unwrap().retained);
}
#[test]
fn test_cleanup_retains_pinned() {
let mut kd = KnownDestinations::new();
let hash = [0xAA; 16];
// Timestamp far in the past, no path, but pinned.
kd.remember(hash, 0.0, [0; 32], [0; 64], None);
kd.retain(&hash);
let removed = kd.cleanup(1_000_000.0, 7.0 * 24.0 * 3600.0, |_| false);
assert!(removed.is_empty());
assert!(kd.contains(&hash));
}
#[test]
fn test_cleanup_keeps_pathed_entries() {
let mut kd = KnownDestinations::new();
let hash = [0xAA; 16];
// Never used, but has a live path — must keep.
kd.remember(hash, 0.0, [0; 32], [0; 64], None);
let removed = kd.cleanup(1_000_000.0, 7.0 * 24.0 * 3600.0, |h| h == &hash);
assert!(removed.is_empty());
assert!(kd.contains(&hash));
}
#[test]
fn test_cleanup_drops_pathless_past_destination_timeout() {
let mut kd = KnownDestinations::new();
let stale_never_used = [0xAA; 16];
let stale_used = [0xBB; 16];
let fresh = [0xCC; 16];
let dest_timeout = 7.0 * 24.0 * 3600.0;
kd.remember(stale_never_used, 0.0, [0; 32], [0; 64], None);
kd.remember(stale_used, 0.0, [0; 32], [0; 64], None);
kd.remember(fresh, dest_timeout - 60.0, [0; 32], [0; 64], None);
// `now` sits one second past the timeout for the stale pair.
let now = dest_timeout + 1.0;
let removed = kd.cleanup(now, dest_timeout, |_| false);
// Both stale arms are reaped under the uniform policy; the fresh
// entry (only ~60 s old at `now`) survives.
assert_eq!(removed.len(), 2);
assert!(removed.contains(&stale_never_used));
assert!(removed.contains(&stale_used));
assert!(kd.contains(&fresh));
}
#[test]
fn test_cleanup_keeps_pathless_well_below_destination_timeout() {
let mut kd = KnownDestinations::new();
let never_used = [0xAA; 16];
let used = [0xBB; 16];
kd.remember(never_used, 0.0, [0; 32], [0; 64], None);
kd.remember(used, 0.0, [0; 32], [0; 64], None);
let removed = kd.cleanup(10.0 * 60.0, 7.0 * 24.0 * 3600.0, |_| false);
assert!(removed.is_empty());
assert!(kd.contains(&never_used));
assert!(kd.contains(&used));
}
}
+12
View File
@@ -0,0 +1,12 @@
//! Reticulum identities, destinations, announces, ratchets, IFAC.
//!
//! Python reference: `RNS/Identity.py`, `RNS/Destination.py`.
pub mod announce;
pub mod destination;
pub mod identity;
pub mod ifac;
pub mod known_destinations;
pub mod name_hash;
pub mod persistence;
pub mod ratchet;
+32
View File
@@ -0,0 +1,32 @@
use rns_crypto::sha::sha256;
/// 80-bit name hash (`SHA-256(app_name)[:10]`).
///
/// `app_name` is the full dotted app/aspect path, e.g. `"lxmf.delivery"`.
pub fn name_hash(app_name: &str) -> [u8; 10] {
let full = sha256(app_name.as_bytes());
let mut out = [0u8; 10];
out.copy_from_slice(&full[..10]);
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_name_hash_basic() {
let h = name_hash("test.app");
assert_eq!(h.len(), 10);
}
#[test]
fn test_name_hash_deterministic() {
assert_eq!(name_hash("lxmf.delivery"), name_hash("lxmf.delivery"));
}
#[test]
fn test_name_hash_different_names() {
assert_ne!(name_hash("app.one"), name_hash("app.two"));
}
}
+68
View File
@@ -0,0 +1,68 @@
use std::fs;
use std::io::Write;
use std::path::Path;
/// Write `data` to `path` via `<path>.tmp` + `rename`, fsyncing first.
///
/// On Unix the temp file is created with mode `0600` so that key material is
/// not world-readable even during the write.
pub fn atomic_write(path: &Path, data: &[u8]) -> std::io::Result<()> {
let tmp_path = path.with_extension("tmp");
{
#[cfg(unix)]
let mut f = {
use std::os::unix::fs::OpenOptionsExt;
std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(&tmp_path)?
};
#[cfg(not(unix))]
let mut f = fs::File::create(&tmp_path)?;
f.write_all(data)?;
f.sync_all()?;
}
fs::rename(&tmp_path, path)?;
Ok(())
}
/// Read `path` in full, returning `None` if the file does not exist.
pub fn read_file(path: &Path) -> std::io::Result<Option<Vec<u8>>> {
match fs::read(path) {
Ok(data) => Ok(Some(data)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn test_atomic_write_and_read() {
let dir = std::env::temp_dir().join("reticulum_test_persistence");
let _ = fs::create_dir_all(&dir);
let path = dir.join("test_atomic");
atomic_write(&path, b"hello world").unwrap();
let data = read_file(&path).unwrap().unwrap();
assert_eq!(data, b"hello world");
let _ = fs::remove_file(&path);
let _ = fs::remove_dir(&dir);
}
#[test]
fn test_read_nonexistent() {
let path = PathBuf::from("/tmp/reticulum_nonexistent_file_xyz");
let result = read_file(&path).unwrap();
assert!(result.is_none());
}
}
+658
View File
@@ -0,0 +1,658 @@
use rns_crypto::sha::full_hash;
use rns_crypto::x25519::X25519PrivateKey;
use rns_wire::constants::{NAME_HASH_LENGTH, RATCHET_COUNT, RATCHET_EXPIRY, RATCHET_INTERVAL};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use zeroize::Zeroize;
use crate::persistence;
/// A bounded history of X25519 private ratchet keys for forward secrecy.
///
/// Index 0 is the most recent key; older keys are retained so decryption can
/// still succeed for in-flight ciphertexts. All key material is zeroised on
/// drop and on truncation.
pub struct RatchetRing {
keys: Vec<[u8; 32]>,
last_rotation: f64,
retained_count: usize,
rotation_interval: u64,
}
impl RatchetRing {
pub fn new() -> Self {
Self {
keys: Vec::new(),
last_rotation: 0.0,
retained_count: RATCHET_COUNT,
rotation_interval: RATCHET_INTERVAL,
}
}
/// Generate a fresh ratchet key, push it to the front, and return its public key.
///
/// Any keys evicted past `retained_count` are zeroised before drop.
pub fn rotate(&mut self) -> [u8; 32] {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64();
let prv = X25519PrivateKey::generate();
let pub_key = prv.public_key().to_bytes();
self.keys.insert(0, prv.to_bytes());
if self.keys.len() > self.retained_count {
for key in &mut self.keys[self.retained_count..] {
key.zeroize();
}
self.keys.truncate(self.retained_count);
}
self.last_rotation = now;
pub_key
}
/// True when at least `rotation_interval` seconds have elapsed since the last rotate.
pub fn needs_rotation(&self) -> bool {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64();
now - self.last_rotation >= self.rotation_interval as f64
}
/// Public key of the most recent ratchet, if the ring has been rotated at least once.
pub fn current_public_key(&self) -> Option<[u8; 32]> {
self.keys.first().map(|prv_bytes| {
let prv = X25519PrivateKey::from_bytes(prv_bytes);
prv.public_key().to_bytes()
})
}
/// All retained private keys, newest first, for decryption attempts.
pub fn private_keys(&self) -> &[[u8; 32]] {
&self.keys
}
pub fn len(&self) -> usize {
self.keys.len()
}
pub fn is_empty(&self) -> bool {
self.keys.is_empty()
}
/// Set `retained_count`; returns `false` if `count == 0`.
pub fn set_retained_ratchets(&mut self, count: usize) -> bool {
if count > 0 {
self.retained_count = count;
self.clean();
true
} else {
false
}
}
pub fn retained_ratchets(&self) -> usize {
self.retained_count
}
/// Set `rotation_interval` (seconds); returns `false` if `interval == 0`.
pub fn set_ratchet_interval(&mut self, interval: u64) -> bool {
if interval > 0 {
self.rotation_interval = interval;
true
} else {
false
}
}
pub fn ratchet_interval(&self) -> u64 {
self.rotation_interval
}
fn clean(&mut self) {
if self.keys.len() > self.retained_count {
self.keys.truncate(self.retained_count);
}
}
/// Persist to `path` as a Python-compatible msgpack envelope.
///
/// Python writes `{signature, ratchets}`. Rust also includes
/// `last_rotation`, which Python ignores and Rust defaults when loading a
/// Python-written file. `ratchets` is itself the msgpack-encoded key list
/// signed by the owning identity.
pub fn save(&self, path: &Path, signature: &[u8; 64]) -> std::io::Result<()> {
let ratchets_packed =
rmp_serde::to_vec(&self.keys).map_err(|e| std::io::Error::other(e.to_string()))?;
let persisted = RatchetRingPersisted {
signature: signature.to_vec(),
ratchets: ratchets_packed,
last_rotation: self.last_rotation,
};
let buf =
rmp_serde::to_vec(&persisted).map_err(|e| std::io::Error::other(e.to_string()))?;
persistence::atomic_write(path, &buf)
}
/// Load the ring, retrying with 1s/2s/4s backoff to ride out transient
/// read errors while another process is rewriting the file.
pub fn load(path: &Path) -> std::io::Result<(Self, [u8; 64])> {
let mut last_err = None;
let delays_ms = [0, 1000, 2000, 4000];
for (attempt, delay) in delays_ms.iter().enumerate() {
if *delay > 0 {
std::thread::sleep(std::time::Duration::from_millis(*delay));
}
match Self::try_load(path) {
Ok(result) => return Ok(result),
Err(e) => {
if attempt < delays_ms.len() - 1 {
tracing::warn!(
attempt = attempt + 1,
path = %path.display(),
error = %e,
"ratchet load attempt failed, retrying"
);
}
last_err = Some(e);
}
}
}
Err(last_err.unwrap())
}
fn try_load(path: &Path) -> std::io::Result<(Self, [u8; 64])> {
let data = std::fs::read(path)?;
let persisted: RatchetRingPersisted =
rmp_serde::from_slice(&data).map_err(|e| std::io::Error::other(e.to_string()))?;
if persisted.signature.len() != 64 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"invalid signature length in ratchet file",
));
}
let mut signature = [0u8; 64];
signature.copy_from_slice(&persisted.signature);
let keys: Vec<[u8; 32]> = rmp_serde::from_slice(&persisted.ratchets)
.map_err(|e| std::io::Error::other(e.to_string()))?;
Ok((
Self {
keys,
last_rotation: persisted.last_rotation,
retained_count: RATCHET_COUNT,
rotation_interval: RATCHET_INTERVAL,
},
signature,
))
}
}
#[derive(Serialize, Deserialize)]
struct RatchetRingPersisted {
signature: Vec<u8>,
ratchets: Vec<u8>,
#[serde(default)]
last_rotation: f64,
}
impl Zeroize for RatchetRing {
fn zeroize(&mut self) {
for key in &mut self.keys {
key.zeroize();
}
self.keys.clear();
self.last_rotation = 0.0;
}
}
impl Drop for RatchetRing {
fn drop(&mut self) {
self.zeroize();
}
}
impl Default for RatchetRing {
fn default() -> Self {
Self::new()
}
}
/// Ratchet public key learned from a remote destination's announce, with
/// the local receive time used for expiry.
pub struct ReceivedRatchet {
pub ratchet_pub: [u8; 32],
pub received_at: f64,
}
// On-disk shape shared with the Python reference: `{"ratchet": bytes, "received": float}`.
#[derive(Serialize, Deserialize)]
struct ReceivedRatchetPersisted {
ratchet: Vec<u8>,
received: f64,
}
impl ReceivedRatchet {
pub fn new(ratchet_pub: [u8; 32]) -> Self {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64();
Self {
ratchet_pub,
received_at: now,
}
}
pub fn is_expired(&self) -> bool {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64();
now - self.received_at > RATCHET_EXPIRY as f64
}
pub fn ratchet_id(&self) -> Vec<u8> {
get_ratchet_id(&self.ratchet_pub)
}
/// Persist to `{ratchetdir}/{hex(dest_hash)}` in the shared msgpack format.
pub fn save(&self, path: &Path) -> std::io::Result<()> {
let persisted = ReceivedRatchetPersisted {
ratchet: self.ratchet_pub.to_vec(),
received: self.received_at,
};
let buf =
rmp_serde::to_vec(&persisted).map_err(|e| std::io::Error::other(e.to_string()))?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
persistence::atomic_write(path, &buf)
}
pub fn load(path: &Path) -> std::io::Result<Self> {
let data = std::fs::read(path)?;
let persisted: ReceivedRatchetPersisted =
rmp_serde::from_slice(&data).map_err(|e| std::io::Error::other(e.to_string()))?;
if persisted.ratchet.len() != 32 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"invalid ratchet public key length",
));
}
let mut ratchet_pub = [0u8; 32];
ratchet_pub.copy_from_slice(&persisted.ratchet);
Ok(Self {
ratchet_pub,
received_at: persisted.received,
})
}
}
/// Compute the ratchet identifier: `full_hash(ratchet_pub)[..NAME_HASH_LENGTH]`.
pub fn get_ratchet_id(ratchet_pub: &[u8; 32]) -> Vec<u8> {
let hash = full_hash(ratchet_pub);
hash[..NAME_HASH_LENGTH].to_vec()
}
/// Derive the ratchet public key from its 32-byte private key.
pub fn ratchet_public_bytes(ratchet_prv: &[u8; 32]) -> [u8; 32] {
let prv = X25519PrivateKey::from_bytes(ratchet_prv);
prv.public_key().to_bytes()
}
/// Sweep `dir`, deleting expired and unparseable ratchet files. Returns the
/// number of files removed.
///
/// Only touches disk; pair with [`purge_expired_ratchets_in_memory`] when an
/// in-memory cache is also kept.
pub fn clean_received_ratchets_dir(dir: &Path) -> usize {
let mut removed = 0usize;
let Ok(entries) = std::fs::read_dir(dir) else {
return 0;
};
for entry in entries.flatten() {
let path = entry.path();
if !path.is_file() {
continue;
}
let drop_it = match ReceivedRatchet::load(&path) {
Ok(r) => r.is_expired(),
Err(_) => true,
};
if drop_it {
match std::fs::remove_file(&path) {
Ok(()) => removed += 1,
Err(e) => tracing::error!(
path = %path.display(),
error = %e,
"failed to remove expired/corrupt ratchet file"
),
}
}
}
removed
}
/// Drop expired entries from an in-memory received-ratchet map; returns the count removed.
pub fn purge_expired_ratchets_in_memory<K: Eq + std::hash::Hash>(
map: &mut HashMap<K, ReceivedRatchet>,
) -> usize {
let before = map.len();
map.retain(|_, r| !r.is_expired());
before - map.len()
}
/// Per-destination cache of remote ratchet public keys, with optional disk backing.
pub struct ReceivedRatchetStore {
entries: HashMap<[u8; 16], ReceivedRatchet>,
storage_dir: Option<PathBuf>,
}
impl ReceivedRatchetStore {
/// In-memory only; no persistence.
pub fn new() -> Self {
Self {
entries: HashMap::new(),
storage_dir: None,
}
}
/// Store backed by `dir` (one file per destination hash).
pub fn with_storage(dir: PathBuf) -> Self {
Self {
entries: HashMap::new(),
storage_dir: Some(dir),
}
}
/// Record `ratchet_pub` for `dest_hash`. Re-inserting the identical key is a no-op;
/// any other value replaces the entry and is written to disk when backed.
pub fn remember(&mut self, dest_hash: [u8; 16], ratchet_pub: [u8; 32]) {
if let Some(existing) = self.entries.get(&dest_hash)
&& existing.ratchet_pub == ratchet_pub
{
return;
}
let received = ReceivedRatchet::new(ratchet_pub);
if let Some(ref dir) = self.storage_dir {
let hexhash = hex::encode(dest_hash);
let path = dir.join(&hexhash);
if let Err(e) = received.save(&path) {
tracing::error!(
dest = hexhash,
error = %e,
"failed to persist received ratchet"
);
}
}
self.entries.insert(dest_hash, received);
}
/// Return the current ratchet public key for `dest_hash`, loading from
/// disk on miss. Yields `None` if the entry is expired or absent.
pub fn get(&mut self, dest_hash: &[u8; 16]) -> Option<[u8; 32]> {
if !self.entries.contains_key(dest_hash)
&& let Some(ref dir) = self.storage_dir
{
let hexhash = hex::encode(dest_hash);
let path = dir.join(&hexhash);
if path.exists() {
match ReceivedRatchet::load(&path) {
Ok(ratchet) => {
if !ratchet.is_expired() && ratchet.ratchet_pub.len() == 32 {
self.entries.insert(*dest_hash, ratchet);
} else {
return None;
}
}
Err(e) => {
tracing::error!(
dest = hexhash,
error = %e,
"failed to load ratchet from disk"
);
return None;
}
}
}
}
self.entries
.get(dest_hash)
.filter(|r| !r.is_expired())
.map(|r| r.ratchet_pub)
}
/// Return the current ratchet ID for `dest_hash`, loading from disk on miss.
pub fn current_ratchet_id(&mut self, dest_hash: &[u8; 16]) -> Option<Vec<u8>> {
self.get(dest_hash)
.map(|pub_bytes| get_ratchet_id(&pub_bytes))
}
pub fn clean_expired(&mut self) {
self.entries.retain(|_, ratchet| !ratchet.is_expired());
if let Some(ref dir) = self.storage_dir {
clean_received_ratchets_dir(dir);
}
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
impl Default for ReceivedRatchetStore {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_ratchet_ring_rotate() {
let mut ring = RatchetRing::new();
assert!(ring.is_empty());
let pub1 = ring.rotate();
assert_eq!(ring.len(), 1);
assert!(ring.current_public_key().is_some());
let pub2 = ring.rotate();
assert_eq!(ring.len(), 2);
assert_ne!(pub1, pub2);
}
#[test]
fn test_ratchet_ring_max_keys() {
let mut ring = RatchetRing::new();
for _ in 0..RATCHET_COUNT + 10 {
ring.rotate();
}
assert_eq!(ring.len(), RATCHET_COUNT);
}
#[test]
fn test_ratchet_ring_file_roundtrip() {
let dir = std::env::temp_dir().join("reticulum_ratchet_test_msgpack");
let _ = std::fs::create_dir_all(&dir);
let path = dir.join("ratchets");
let mut ring = RatchetRing::new();
ring.rotate();
ring.rotate();
ring.rotate();
let sig = [0xAA; 64];
ring.save(&path, &sig).unwrap();
let (ring2, sig2) = RatchetRing::load(&path).unwrap();
assert_eq!(ring2.len(), 3);
assert_eq!(sig2, sig);
assert_eq!(ring.private_keys(), ring2.private_keys());
let _ = std::fs::remove_file(&path);
let _ = std::fs::remove_dir(&dir);
}
#[test]
fn test_ratchet_ring_loads_python_shape_without_last_rotation() {
#[derive(Serialize)]
struct PythonRatchets {
signature: Vec<u8>,
ratchets: Vec<u8>,
}
let dir = std::env::temp_dir().join("reticulum_python_ratchet_test_msgpack");
let _ = std::fs::create_dir_all(&dir);
let path = dir.join("ratchets");
let keys = vec![[0x11; 32], [0x22; 32]];
let signature = vec![0xAA; 64];
let ratchets = rmp_serde::to_vec(&keys).unwrap();
let persisted = PythonRatchets {
signature: signature.clone(),
ratchets,
};
let buf = rmp_serde::to_vec(&persisted).unwrap();
std::fs::write(&path, buf).unwrap();
let (ring, loaded_signature) = RatchetRing::load(&path).unwrap();
assert_eq!(ring.len(), 2);
assert_eq!(ring.private_keys(), keys.as_slice());
assert_eq!(loaded_signature.as_slice(), signature.as_slice());
let _ = std::fs::remove_file(&path);
let _ = std::fs::remove_dir(&dir);
}
#[test]
fn test_set_retained_ratchets() {
let mut ring = RatchetRing::new();
for _ in 0..20 {
ring.rotate();
}
assert_eq!(ring.len(), 20);
assert!(ring.set_retained_ratchets(5));
assert_eq!(ring.len(), 5);
assert_eq!(ring.retained_ratchets(), 5);
assert!(!ring.set_retained_ratchets(0));
assert_eq!(ring.retained_ratchets(), 5);
}
#[test]
fn test_set_ratchet_interval() {
let mut ring = RatchetRing::new();
assert_eq!(ring.ratchet_interval(), RATCHET_INTERVAL);
assert!(ring.set_ratchet_interval(60));
assert_eq!(ring.ratchet_interval(), 60);
assert!(!ring.set_ratchet_interval(0));
assert_eq!(ring.ratchet_interval(), 60);
}
#[test]
fn test_received_ratchet_msgpack_roundtrip() {
let dir = std::env::temp_dir().join("reticulum_recv_ratchet_test");
let _ = std::fs::create_dir_all(&dir);
let path = dir.join("test_ratchet");
let ratchet_pub = rns_crypto::random::random_32();
let received = ReceivedRatchet::new(ratchet_pub);
received.save(&path).unwrap();
let loaded = ReceivedRatchet::load(&path).unwrap();
assert_eq!(loaded.ratchet_pub, ratchet_pub);
assert!((loaded.received_at - received.received_at).abs() < 0.001);
assert!(!loaded.is_expired());
let _ = std::fs::remove_file(&path);
let _ = std::fs::remove_dir(&dir);
}
#[test]
fn test_received_ratchet_store() {
let dir = std::env::temp_dir().join("reticulum_ratchet_store_test");
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::create_dir_all(&dir);
let mut store = ReceivedRatchetStore::with_storage(dir.clone());
let dest_hash = [0xAA; 16];
let ratchet_pub = rns_crypto::random::random_32();
store.remember(dest_hash, ratchet_pub);
assert_eq!(store.len(), 1);
assert_eq!(store.get(&dest_hash), Some(ratchet_pub));
let rid = store.current_ratchet_id(&dest_hash);
assert!(rid.is_some());
// Fresh store re-reads the entry from disk.
let mut store2 = ReceivedRatchetStore::with_storage(dir.clone());
assert_eq!(store2.get(&dest_hash), Some(ratchet_pub));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn test_received_ratchet_store_dedup() {
let mut store = ReceivedRatchetStore::new();
let dest_hash = [0xBB; 16];
let ratchet_pub = rns_crypto::random::random_32();
store.remember(dest_hash, ratchet_pub);
store.remember(dest_hash, ratchet_pub);
assert_eq!(store.len(), 1);
let ratchet_pub2 = rns_crypto::random::random_32();
store.remember(dest_hash, ratchet_pub2);
assert_eq!(store.len(), 1);
assert_eq!(store.get(&dest_hash), Some(ratchet_pub2));
}
#[test]
fn test_get_ratchet_id() {
let pub_bytes = rns_crypto::random::random_32();
let rid = get_ratchet_id(&pub_bytes);
assert_eq!(rid.len(), NAME_HASH_LENGTH);
}
#[test]
fn test_ratchet_public_bytes() {
let prv = X25519PrivateKey::generate();
let prv_bytes = prv.to_bytes();
let pub_bytes = ratchet_public_bytes(&prv_bytes);
assert_eq!(pub_bytes, prv.public_key().to_bytes());
}
}
+77
View File
@@ -0,0 +1,77 @@
[package]
name = "rns-interface"
description = "Network interface trait and implementations for Reticulum"
version.workspace = true
edition.workspace = true
license.workspace = true
[features]
default = []
serial = ["dep:serialport"]
ble = ["dep:btleplug", "dep:futures", "dep:uuid"]
ble_peer = ["ble"]
# See rns-transport's mobile-throttle. When enabled, auto-interface beacons
# and reverse-peering probes slow down in the background; BLE peer scan
# cadence adjusts to `is_foreground`. Disabled on desktop builds.
mobile-throttle = ["rns-transport/mobile-throttle"]
[dependencies]
rns-crypto = { workspace = true, features = ["std"] }
rns-wire = { workspace = true, features = ["std"] }
rns-transport = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }
bytes = { workspace = true }
tracing = { workspace = true }
socket2 = { workspace = true }
if-addrs = { workspace = true }
serialport = { workspace = true, optional = true }
btleplug = { workspace = true, optional = true }
futures = { version = "0.3", optional = true }
uuid = { version = "1", optional = true }
rand = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
hex = { workspace = true }
# Apple BLE Peripheral (CoreBluetooth GATT server, iOS + macOS).
# Version pinned to match btleplug's internal objc2 version so the shared
# runtime types stay binary-compatible. objc2-core-bluetooth gives us
# linked-symbol access to NSString constants (CBCentralManagerScanOption*,
# CB*RestoreIdentifierKey, etc.) instead of re-declaring their literal
# values, which Apple is free to change.
[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies]
objc2 = "0.5"
objc2-foundation = "0.2"
objc2-core-bluetooth = "0.2"
[target.'cfg(target_os = "macos")'.dependencies]
libc = "0.2"
# Android JNI (BLE Peripheral, USB Serial)
[target.'cfg(target_os = "android")'.dependencies]
jni = "0.19"
# Linux BLE Peripheral via BlueZ D-Bus (real GATT server, B7).
# Linux-only target dep so non-Linux builds don't pull in BlueZ. The
# linux_peripheral module is gated by both `ble` feature and target_os.
[target.'cfg(target_os = "linux")'.dependencies]
bluer = { version = "0.17", features = ["bluetoothd"] }
# Windows BLE Peripheral via WinRT GattServiceProvider (MSIX-packaged apps).
# Windows-only target dep so cross-platform builds don't pull in WinRT
# shims. The windows_peripheral module is gated by `ble` feature and
# target_os. GattServiceProvider.CreateAsync returns AccessDenied for
# unpackaged Win32 binaries; we surface that as a clear peripheral-
# unavailable event so embedding UIs can direct users to an MSIX build for
# discoverability.
[target.'cfg(target_os = "windows")'.dependencies]
windows = { version = "0.58", features = [
"Devices_Bluetooth",
"Devices_Bluetooth_Advertisement",
"Devices_Bluetooth_GenericAttributeProfile",
"Devices_Radios",
"Foundation",
"Foundation_Collections",
"Storage_Streams",
] }
+658
View File
@@ -0,0 +1,658 @@
//! USB serial RNode over Android USB-C OTG via JNI to `UsbManager`. 115200 8N1.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use bytes::Bytes;
use tokio::sync::mpsc;
use crate::kiss;
use crate::rnode;
use crate::traits::{
InterfaceDirection, InterfaceError, InterfaceHandle, InterfaceId, InterfaceMode,
};
use rns_transport::messages::TransportMessage;
pub const BAUD_RATE: u32 = 115_200;
/// USB VIDs of serial chipsets commonly used by RNode hardware.
pub const KNOWN_VIDS: &[(u16, &str)] = &[
(0x0403, "FTDI"),
(0x10C4, "Silicon Labs CP210x"),
(0x1A86, "WCH CH340/CH341"),
(0x0525, "CDC-ACM (Netchip)"),
(0x2E8A, "Raspberry Pi Pico / RP2040"),
(0x303A, "Espressif ESP32-S3"),
(0x239A, "Adafruit"),
(0x1915, "Nordic Semiconductor NRF52840"),
];
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UsbSerialDevice {
pub device_name: String,
pub vid: u16,
pub pid: u16,
pub chipset: String,
pub manufacturer: String,
pub product: String,
}
#[derive(Debug, Clone)]
pub struct AndroidUsbConfig {
pub name: String,
pub device_name: String,
pub baud_rate: u32,
pub frequency: u32,
pub bandwidth: u32,
pub spreading_factor: u8,
pub coding_rate: u8,
pub tx_power: u8,
pub mode: InterfaceMode,
}
impl AndroidUsbConfig {
pub fn new(name: &str, device_name: &str) -> Self {
Self {
name: name.to_string(),
device_name: device_name.to_string(),
baud_rate: BAUD_RATE,
frequency: 915_000_000,
bandwidth: 125_000,
spreading_factor: 8,
coding_rate: 6,
tx_power: 17,
mode: InterfaceMode::Full,
}
}
}
use jni::JavaVM;
use jni::objects::{GlobalRef, JObject, JValue};
use std::sync::OnceLock;
static JAVA_VM: OnceLock<JavaVM> = OnceLock::new();
static APP_CONTEXT: OnceLock<GlobalRef> = OnceLock::new();
/// Stash JavaVM (wired from `JNI_OnLoad`); Application context fetched lazily
/// via `ActivityThread.currentApplication()` so callers don't thread it through.
pub fn init_vm(vm: JavaVM) {
let _ = JAVA_VM.set(vm);
}
/// Shared JavaVM accessor (e.g. `auto.rs::get_link_local_addrs_android`).
/// `None` until `init_vm` has run.
pub fn java_vm() -> Option<&'static JavaVM> {
JAVA_VM.get()
}
fn with_env<F, R>(f: F) -> Result<R, String>
where
F: FnOnce(&jni::JNIEnv) -> Result<R, String>,
{
let vm = JAVA_VM.get().ok_or("JavaVM not initialized for USB")?;
let env = vm
.attach_current_thread()
.map_err(|e| format!("JNI: {e}"))?;
f(&env)
}
/// Lazily resolve the Application context; cached after first resolution.
fn ensure_app_context(env: &jni::JNIEnv) -> Result<&'static GlobalRef, String> {
if let Some(ctx) = APP_CONTEXT.get() {
return Ok(ctx);
}
let activity_thread = env
.find_class("android/app/ActivityThread")
.map_err(|e| format!("ActivityThread class: {e}"))?;
let app = env
.call_static_method(
activity_thread,
"currentApplication",
"()Landroid/app/Application;",
&[],
)
.map_err(|e| format!("currentApplication: {e}"))?
.l()
.map_err(|e| format!("currentApplication object: {e}"))?;
if app.is_null() {
return Err("ActivityThread.currentApplication() returned null".into());
}
let global = env
.new_global_ref(app)
.map_err(|e| format!("new_global_ref(application): {e}"))?;
let _ = APP_CONTEXT.set(global);
APP_CONTEXT
.get()
.ok_or_else(|| "APP_CONTEXT race".to_string())
}
pub async fn enumerate_usb_devices() -> Result<Vec<UsbSerialDevice>, String> {
tokio::task::spawn_blocking(|| {
with_env(|env| {
let ctx = ensure_app_context(env)?;
let usb_str = env.new_string("usb").map_err(|e| format!("{e}"))?;
let usb_mgr = env
.call_method(
ctx.as_obj(),
"getSystemService",
"(Ljava/lang/String;)Ljava/lang/Object;",
&[JValue::Object(usb_str.into())],
)
.map_err(|e| format!("{e}"))?
.l()
.map_err(|e| format!("{e}"))?;
let device_map = env
.call_method(usb_mgr, "getDeviceList", "()Ljava/util/HashMap;", &[])
.map_err(|e| format!("{e}"))?
.l()
.map_err(|e| format!("{e}"))?;
let values = env
.call_method(device_map, "values", "()Ljava/util/Collection;", &[])
.map_err(|e| format!("{e}"))?
.l()
.map_err(|e| format!("{e}"))?;
let iter = env
.call_method(values, "iterator", "()Ljava/util/Iterator;", &[])
.map_err(|e| format!("{e}"))?
.l()
.map_err(|e| format!("{e}"))?;
let mut devices = Vec::new();
loop {
let has_next = env
.call_method(iter, "hasNext", "()Z", &[])
.map_err(|e| format!("{e}"))?
.z()
.map_err(|e| format!("{e}"))?;
if !has_next {
break;
}
let device = env
.call_method(iter, "next", "()Ljava/lang/Object;", &[])
.map_err(|e| format!("{e}"))?
.l()
.map_err(|e| format!("{e}"))?;
let vid = env
.call_method(device, "getVendorId", "()I", &[])
.map_err(|e| format!("{e}"))?
.i()
.map_err(|e| format!("{e}"))? as u16;
let pid = env
.call_method(device, "getProductId", "()I", &[])
.map_err(|e| format!("{e}"))?
.i()
.map_err(|e| format!("{e}"))? as u16;
let name_js = env
.call_method(device, "getDeviceName", "()Ljava/lang/String;", &[])
.map_err(|e| format!("{e}"))?
.l()
.map_err(|e| format!("{e}"))?;
let name: String = env
.get_string(name_js.into())
.map(|s| s.into())
.unwrap_or_default();
let chipset = KNOWN_VIDS
.iter()
.find(|(v, _)| *v == vid)
.map(|(_, n)| n.to_string())
.unwrap_or_default();
if !chipset.is_empty() {
devices.push(UsbSerialDevice {
device_name: name,
vid,
pid,
chipset,
manufacturer: String::new(),
product: String::new(),
});
}
}
Ok(devices)
})
})
.await
.map_err(|e| format!("{e}"))?
}
pub async fn request_usb_permission(device_name: &str) -> Result<bool, String> {
let dev_name = device_name.to_string();
tokio::task::spawn_blocking(move || {
with_env(|env| {
let ctx = ensure_app_context(env)?;
let usb_str = env.new_string("usb").map_err(|e| format!("{e}"))?;
let usb_mgr = env
.call_method(
ctx.as_obj(),
"getSystemService",
"(Ljava/lang/String;)Ljava/lang/Object;",
&[JValue::Object(usb_str.into())],
)
.map_err(|e| format!("{e}"))?
.l()
.map_err(|e| format!("{e}"))?;
let device_map = env
.call_method(usb_mgr, "getDeviceList", "()Ljava/util/HashMap;", &[])
.map_err(|e| format!("{e}"))?
.l()
.map_err(|e| format!("{e}"))?;
let key = env.new_string(&dev_name).map_err(|e| format!("{e}"))?;
let device = env
.call_method(
device_map,
"get",
"(Ljava/lang/Object;)Ljava/lang/Object;",
&[JValue::Object(key.into())],
)
.map_err(|e| format!("{e}"))?
.l()
.map_err(|e| format!("{e}"))?;
if device.is_null() {
return Err(format!("USB device not found: {dev_name}"));
}
env.call_method(
usb_mgr,
"hasPermission",
"(Landroid/hardware/usb/UsbDevice;)Z",
&[JValue::Object(device)],
)
.map_err(|e| format!("{e}"))?
.z()
.map_err(|e| format!("{e}"))
})
})
.await
.map_err(|e| format!("{e}"))?
}
/// Open device, claim CDC data interface, set line coding.
/// Returns `(tx, rx, connected_flag)` — drop flag to false to stop loops.
async fn open_usb_serial(
device_name: &str,
baud_rate: u32,
) -> Result<
(
mpsc::Sender<Vec<u8>>,
mpsc::Receiver<Vec<u8>>,
Arc<AtomicBool>,
),
InterfaceError,
> {
let dev_name = device_name.to_string();
tokio::task::spawn_blocking(move || -> Result<_, String> {
with_env(|env| {
let ctx = ensure_app_context(env)?;
let usb_str = env.new_string("usb").map_err(|e| format!("{e}"))?;
let usb_mgr = env
.call_method(
ctx.as_obj(),
"getSystemService",
"(Ljava/lang/String;)Ljava/lang/Object;",
&[JValue::Object(usb_str.into())],
)
.map_err(|e| format!("{e}"))?
.l()
.map_err(|e| format!("{e}"))?;
let device_map = env
.call_method(usb_mgr, "getDeviceList", "()Ljava/util/HashMap;", &[])
.map_err(|e| format!("{e}"))?
.l()
.map_err(|e| format!("{e}"))?;
let key = env.new_string(&dev_name).map_err(|e| format!("{e}"))?;
let device = env
.call_method(
device_map,
"get",
"(Ljava/lang/Object;)Ljava/lang/Object;",
&[JValue::Object(key.into())],
)
.map_err(|e| format!("{e}"))?
.l()
.map_err(|e| format!("{e}"))?;
let connection = env
.call_method(
usb_mgr,
"openDevice",
"(Landroid/hardware/usb/UsbDevice;)Landroid/hardware/usb/UsbDeviceConnection;",
&[JValue::Object(device)],
)
.map_err(|e| format!("{e}"))?
.l()
.map_err(|e| format!("{e}"))?;
if connection.is_null() {
return Err("Failed to open USB device (permission denied?)".into());
}
// CDC-Data (0x0A) or vendor-specific (0xFF) with bulk IN+OUT.
let iface_count = env
.call_method(device, "getInterfaceCount", "()I", &[])
.map_err(|e| format!("{e}"))?
.i()
.map_err(|e| format!("{e}"))?;
let mut data_iface = JObject::null();
let mut ep_in = JObject::null();
let mut ep_out = JObject::null();
for i in 0..iface_count {
let iface = env
.call_method(
device,
"getInterface",
"(I)Landroid/hardware/usb/UsbInterface;",
&[JValue::Int(i)],
)
.map_err(|e| format!("{e}"))?
.l()
.map_err(|e| format!("{e}"))?;
let cls = env
.call_method(iface, "getInterfaceClass", "()I", &[])
.map_err(|e| format!("{e}"))?
.i()
.map_err(|e| format!("{e}"))?;
if cls == 0x0A || cls == 0xFF {
let epc = env
.call_method(iface, "getEndpointCount", "()I", &[])
.map_err(|e| format!("{e}"))?
.i()
.map_err(|e| format!("{e}"))?;
for j in 0..epc {
let ep = env
.call_method(
iface,
"getEndpoint",
"(I)Landroid/hardware/usb/UsbEndpoint;",
&[JValue::Int(j)],
)
.map_err(|e| format!("{e}"))?
.l()
.map_err(|e| format!("{e}"))?;
let dir = env
.call_method(ep, "getDirection", "()I", &[])
.map_err(|e| format!("{e}"))?
.i()
.map_err(|e| format!("{e}"))?;
if dir == 0x80 {
ep_in = ep;
} else {
ep_out = ep;
}
}
if !ep_in.is_null() && !ep_out.is_null() {
data_iface = iface;
break;
}
}
}
if data_iface.is_null() {
return Err("No CDC-ACM interface found".into());
}
env.call_method(
connection,
"claimInterface",
"(Landroid/hardware/usb/UsbInterface;Z)Z",
&[JValue::Object(data_iface), JValue::Bool(1)],
)
.map_err(|e| format!("{e}"))?;
// CDC SET_LINE_CODING (bmRequestType=0x21, bRequest=0x20):
// [baud_rate u32 LE][stop_bits u8][parity u8][data_bits u8].
//
// The Android signature is `controlTransfer(int, int, int, int,
// byte[], int, int)` — seven parameters including the trailing
// timeout. Calling with the six-parameter signature throws
// NoSuchMethodError into a pending JNI exception, which the next
// JNI op (new_global_ref) detects as a CheckJNI violation and
// aborts the process. CP2102 / CH340 / FTDI ignore CDC class
// requests anyway (they use vendor-specific control transfers),
// so we send this best-effort and explicitly clear any pending
// exception before continuing.
let mut lc = [0u8; 7];
lc[0..4].copy_from_slice(&baud_rate.to_le_bytes());
lc[6] = 8;
let lc_arr = env.byte_array_from_slice(&lc).map_err(|e| format!("{e}"))?;
let _ = env.call_method(
connection,
"controlTransfer",
"(IIII[BII)I",
&[
JValue::Int(0x21),
JValue::Int(0x20),
JValue::Int(0),
JValue::Int(0),
JValue::Object(lc_arr.into()),
JValue::Int(7),
JValue::Int(1000),
],
);
// Defensive: ensure any Java exception from the optional CDC call
// is cleared so the subsequent global-ref allocations don't trip
// CheckJNI's "pending exception" abort.
if env.exception_check().unwrap_or(false) {
let _ = env.exception_clear();
}
let conn_ref = env.new_global_ref(connection).map_err(|e| format!("{e}"))?;
let ep_in_ref = env.new_global_ref(ep_in).map_err(|e| format!("{e}"))?;
let ep_out_ref = env.new_global_ref(ep_out).map_err(|e| format!("{e}"))?;
let connected = Arc::new(AtomicBool::new(true));
let (write_tx, mut write_rx) = mpsc::channel::<Vec<u8>>(64);
let (read_tx, read_rx) = mpsc::channel::<Vec<u8>>(64);
let cw = connected.clone();
let vm = match JAVA_VM.get() {
Some(v) => v.clone(),
None => return Err("JavaVM not initialized for USB write loop".into()),
};
let cr_w = conn_ref.clone();
let ep_w = ep_out_ref.clone();
tokio::task::spawn_blocking(move || {
let rt = tokio::runtime::Handle::current();
while cw.load(Ordering::Relaxed) {
match rt.block_on(write_rx.recv()) {
Some(data) => {
if let Ok(env2) = vm.attach_current_thread() {
let buf = env2
.byte_array_from_slice(&data)
.expect("JNI byte_array_from_slice failed (OOM in JVM heap)");
let _ = env2.call_method(
cr_w.as_obj(),
"bulkTransfer",
"(Landroid/hardware/usb/UsbEndpoint;[BII)I",
&[
JValue::Object(ep_w.as_obj()),
JValue::Object(buf.into()),
JValue::Int(data.len() as i32),
JValue::Int(1000),
],
);
}
}
None => break,
}
}
});
let cr = connected.clone();
let vm2 = match JAVA_VM.get() {
Some(v) => v.clone(),
None => return Err("JavaVM not initialized for USB read loop".into()),
};
tokio::task::spawn_blocking(move || {
loop {
if !cr.load(Ordering::Relaxed) {
break;
}
if let Ok(env2) = vm2.attach_current_thread() {
let buf = env2
.new_byte_array(1024)
.expect("JNI new_byte_array failed (OOM in JVM heap)");
match env2.call_method(
conn_ref.as_obj(),
"bulkTransfer",
"(Landroid/hardware/usb/UsbEndpoint;[BII)I",
&[
JValue::Object(ep_in_ref.as_obj()),
JValue::Object(buf.into()),
JValue::Int(1024),
JValue::Int(100),
],
) {
Ok(val) => {
let n = val.i().unwrap_or(-1);
if n > 0 {
if let Ok(bytes) = env2.convert_byte_array(buf) {
if read_tx
.blocking_send(bytes[..n as usize].to_vec())
.is_err()
{
break;
}
}
}
}
Err(_) => {
cr.store(false, Ordering::Relaxed);
break;
}
}
}
}
});
Ok((write_tx, read_rx, connected))
})
})
.await
.map_err(|e| InterfaceError::SendFailed(format!("{e}")))?
.map_err(|e| InterfaceError::SendFailed(e))
}
/// Same shape as the serial/BLE RNode interfaces, but over Android USB.
pub async fn spawn_android_usb_rnode_interface(
config: AndroidUsbConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, InterfaceError> {
let (raw_write_tx, mut raw_read_rx, connected) =
open_usb_serial(&config.device_name, config.baud_rate).await?;
let name = config.name.clone();
// Radio stays disabled until we push an init sequence, so do it before
// handing the write channel to the transport-facing task.
let mut rnode_cfg = rnode::RNodeConfig::new(&config.name, &config.device_name);
rnode_cfg.baud_rate = config.baud_rate;
rnode_cfg.frequency = config.frequency;
rnode_cfg.bandwidth = config.bandwidth;
rnode_cfg.spreading_factor = config.spreading_factor;
rnode_cfg.coding_rate = config.coding_rate;
rnode_cfg.tx_power = config.tx_power;
rnode_cfg.mode = config.mode;
let init_bytes = rnode::build_init_sequence(&rnode_cfg);
if raw_write_tx.send(init_bytes).await.is_err() {
return Err(InterfaceError::SendFailed(
"Android USB writer closed before RNode init could be sent".into(),
));
}
let shared_txb = Arc::new(AtomicU64::new(0));
let shared_rxb = Arc::new(AtomicU64::new(0));
let (tx, mut app_rx) = mpsc::channel::<Bytes>(64);
let txb = shared_txb.clone();
let wtx = raw_write_tx.clone();
let write_name = name.clone();
tokio::spawn(async move {
while let Some(payload) = app_rx.recv().await {
let frame = kiss::frame(&payload);
txb.fetch_add(frame.len() as u64, Ordering::Relaxed);
if wtx.send(frame).await.is_err() {
tracing::warn!(name = %write_name, "USB write channel closed");
break;
}
}
});
// Any RSSI/SNR from a preceding CMD_STAT_* frame attaches to the next
// inbound data packet; both reset after use.
let read_name = name.clone();
let rxb = shared_rxb.clone();
let online = connected.clone();
let read_task = tokio::spawn(async move {
let mut deframer = kiss::KissDeframer::new();
let mut last_rssi: Option<f32> = None;
let mut last_snr: Option<f32> = None;
while let Some(bytes) = raw_read_rx.recv().await {
if bytes.is_empty() {
continue;
}
// Count only real LoRa data payloads, not KISS framing or
// control responses (DETECT_RESP, CMD_STAT_*, CMD_FW_VERSION,
// etc.). Mirrors ble_rnode.rs so UI RX counters don't tick up
// while the radio is idle.
for (cmd, frame) in deframer.feed(&bytes) {
match rnode::process_rnode_response(cmd, &frame, id, &mut last_rssi, &mut last_snr)
{
rnode::RNodeResponse::Packet(msg) => {
rxb.fetch_add(frame.len() as u64, Ordering::Relaxed);
if transport_tx.send(msg).await.is_err() {
tracing::warn!(name = %read_name, "transport channel closed");
online.store(false, Ordering::SeqCst);
return;
}
}
rnode::RNodeResponse::Ready(_) | rnode::RNodeResponse::None => {}
}
}
}
tracing::info!(name = %read_name, "Android USB read task exiting (channel closed)");
online.store(false, Ordering::SeqCst);
});
Ok(InterfaceHandle {
id,
name,
mode: config.mode,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: true,
repeat: false,
},
bitrate: BAUD_RATE as u64,
mtu: 500,
online: connected,
txb: Some(shared_txb),
rxb: Some(shared_rxb),
tx,
read_task,
})
}
/// Push an already-KISS-framed control frame through the raw USB writer,
/// bypassing the transport CMD_DATA wrapper. The canonical caller is the
/// BLE→serial handoff, which sends `[FEND, CMD_BT_CTRL, 0x00, FEND]` to turn
/// off the RNode's BT radio before the USB link takes over.
pub async fn send_raw_frame(
writer: &mpsc::Sender<Vec<u8>>,
frame: Vec<u8>,
) -> Result<(), InterfaceError> {
writer
.send(frame)
.await
.map_err(|_| InterfaceError::SendFailed("USB raw writer closed".into()))
}
File diff suppressed because it is too large. Load diff
+680
View File
@@ -0,0 +1,680 @@
//! AX.25-over-KISS — prepends a UI header (src/dst call+SSID) and strips on RX.
#[cfg(feature = "serial")]
use std::sync::Arc;
#[cfg(feature = "serial")]
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
#[cfg(feature = "serial")]
use std::time::Duration;
#[cfg(feature = "serial")]
use bytes::Bytes;
#[cfg(feature = "serial")]
use tokio::sync::mpsc;
use crate::kiss;
use crate::traits::InterfaceMode;
#[cfg(feature = "serial")]
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId};
#[cfg(feature = "serial")]
use rns_transport::messages::{InboundPacket, TransportMessage};
/// "No layer 3 protocol".
pub const AX25_PID_NOLAYER3: u8 = 0xF0;
/// Unnumbered Information control field.
pub const AX25_CTRL_UI: u8 = 0x03;
/// 2×7 (addresses) + 1 (control) + 1 (PID).
pub const AX25_HEADER_SIZE: usize = 16;
pub const HW_MTU: u16 = 564;
pub const BITRATE_GUESS: u64 = 1200;
pub const DEFAULT_DST_CALL: &[u8] = b"APZRNS";
pub const DEFAULT_DST_SSID: u8 = 0;
#[derive(Debug, Clone)]
pub struct AX25KISSConfig {
pub name: String,
pub port: String,
pub baud_rate: u32,
/// 3-6 uppercase ASCII.
pub src_call: String,
/// 0-15.
pub src_ssid: u8,
pub dst_call: String,
pub dst_ssid: u8,
/// ms (default 350).
pub preamble: u16,
/// ms (default 20).
pub txtail: u16,
/// CSMA persistence 0-255 (default 64).
pub persistence: u8,
/// CSMA slot time ms (default 20).
pub slottime: u16,
/// Honour CMD_READY from TNC.
pub flow_control: bool,
pub mode: InterfaceMode,
}
impl AX25KISSConfig {
pub fn new(name: &str, port: &str, callsign: &str, ssid: u8) -> Self {
Self {
name: name.to_string(),
port: port.to_string(),
baud_rate: 9600,
src_call: callsign.to_uppercase(),
src_ssid: ssid,
dst_call: String::from_utf8_lossy(DEFAULT_DST_CALL).to_string(),
dst_ssid: DEFAULT_DST_SSID,
preamble: 350,
txtail: 20,
persistence: 64,
slottime: 20,
flow_control: false,
mode: InterfaceMode::Full,
}
}
pub fn validate(&self) -> Result<(), String> {
if self.src_call.len() < 3 || self.src_call.len() > 6 {
return Err(format!(
"Invalid callsign '{}': must be 3-6 characters",
self.src_call
));
}
if self.src_ssid > 15 {
return Err(format!("Invalid SSID {}: must be 0-15", self.src_ssid));
}
Ok(())
}
}
/// 16-byte AX.25 UI header (AX.25 v2.2 §3.12):
/// `dst_call(6) | dst_ssid(1) | src_call(6) | src_ssid(1) | CTRL | PID`.
/// Callsign bytes left-shifted 1, space-padded to 6. SSID = `0x60 | (ssid<<1)`;
/// src SSID also sets end-of-address bit.
pub fn build_ax25_header(
dst_call: &[u8],
dst_ssid: u8,
src_call: &[u8],
src_ssid: u8,
) -> [u8; AX25_HEADER_SIZE] {
let mut header = [0u8; AX25_HEADER_SIZE];
for i in 0..6 {
header[i] = if i < dst_call.len() {
dst_call[i] << 1
} else {
0x20
};
}
header[6] = 0x60 | (dst_ssid << 1);
for i in 0..6 {
header[7 + i] = if i < src_call.len() {
src_call[i] << 1
} else {
0x20
};
}
// End-of-address bit terminates the address field.
header[13] = 0x60 | (src_ssid << 1) | 0x01;
header[14] = AX25_CTRL_UI;
header[15] = AX25_PID_NOLAYER3;
header
}
pub fn frame_ax25_kiss(
data: &[u8],
dst_call: &[u8],
dst_ssid: u8,
src_call: &[u8],
src_ssid: u8,
) -> Vec<u8> {
let header = build_ax25_header(dst_call, dst_ssid, src_call, src_ssid);
let mut payload = Vec::with_capacity(header.len() + data.len());
payload.extend_from_slice(&header);
payload.extend_from_slice(data);
kiss::frame(&payload)
}
/// Payload after the 16-byte header, or `None` if too short.
pub fn strip_ax25_header(data: &[u8]) -> Option<&[u8]> {
if data.len() > AX25_HEADER_SIZE {
Some(&data[AX25_HEADER_SIZE..])
} else {
None
}
}
/// preamble/txtail/slottime are ms→10ms units per KISS spec.
pub fn build_ax25_kiss_init(config: &AX25KISSConfig) -> Vec<u8> {
let mut out = Vec::new();
let preamble_val = (config.preamble / 10).min(255) as u8;
out.extend_from_slice(&kiss::frame_with_command(
kiss::CMD_TXDELAY,
&[preamble_val],
));
let txtail_val = (config.txtail / 10).min(255) as u8;
out.extend_from_slice(&kiss::frame_with_command(kiss::CMD_TXTAIL, &[txtail_val]));
out.extend_from_slice(&kiss::frame_with_command(
kiss::CMD_P,
&[config.persistence],
));
let slottime_val = (config.slottime / 10).min(255) as u8;
out.extend_from_slice(&kiss::frame_with_command(
kiss::CMD_SLOTTIME,
&[slottime_val],
));
out.extend_from_slice(&kiss::frame_with_command(kiss::CMD_READY, &[0x01]));
out
}
#[cfg(feature = "serial")]
const AX25_READ_TIMEOUT_MS: u64 = 100;
#[cfg(feature = "serial")]
const FLOW_CONTROL_TIMEOUT_SECS: u64 = 5;
/// Parse `"CALL-SSID"` or `"CALL"`; uppercased call, SSID defaults to 0.
pub fn parse_callsign_ssid(input: &str) -> Result<(String, u8), String> {
let (call_part, ssid) = if let Some(idx) = input.rfind('-') {
let call = &input[..idx];
let ssid_str = &input[idx + 1..];
let ssid: u8 = ssid_str
.parse()
.map_err(|_| format!("Invalid SSID '{}': must be a number 0-15", ssid_str))?;
(call, ssid)
} else {
(input, 0u8)
};
let call = call_part.to_uppercase();
if call.len() < 3 || call.len() > 6 {
return Err(format!(
"Invalid callsign '{}': must be 3-6 characters",
call
));
}
if !call.bytes().all(|b| b.is_ascii_alphanumeric()) {
return Err(format!(
"Invalid callsign '{}': must be ASCII alphanumeric",
call
));
}
if ssid > 15 {
return Err(format!("Invalid SSID {}: must be 0-15", ssid));
}
Ok((call, ssid))
}
#[cfg(feature = "serial")]
pub async fn spawn_ax25kiss_interface(
config: AX25KISSConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
config.validate().map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("ax25kiss config: {}", e))
})?;
let port = serialport::new(&config.port, config.baud_rate)
.data_bits(serialport::DataBits::Eight)
.parity(serialport::Parity::None)
.stop_bits(serialport::StopBits::One)
.timeout(Duration::from_millis(AX25_READ_TIMEOUT_MS))
.open()
.map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("ax25kiss serial open: {}", e))
})?;
tracing::info!(
name = %config.name,
port = %config.port,
baud = config.baud_rate,
src_call = %config.src_call,
src_ssid = config.src_ssid,
"AX.25 KISS interface opened"
);
let online = Arc::new(AtomicBool::new(true));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let (tx, mut rx) = mpsc::channel::<Bytes>(256);
let name = config.name.clone();
let mode = config.mode;
let flow_control = config.flow_control;
let src_call_bytes: Vec<u8> = config.src_call.as_bytes().to_vec();
let dst_call_bytes: Vec<u8> = config.dst_call.as_bytes().to_vec();
let src_ssid = config.src_ssid;
let dst_ssid = config.dst_ssid;
let port_write = port
.try_clone()
.map_err(|e| crate::traits::InterfaceError::SendFailed(format!("ax25kiss clone: {}", e)))?;
{
let mut init_port = port_write.try_clone().map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("ax25kiss init clone: {}", e))
})?;
let init_seq = build_ax25_kiss_init(&config);
use std::io::Write;
let _ = init_port.write_all(&init_seq);
let _ = init_port.flush();
tracing::debug!(name = %config.name, "AX.25 KISS init commands sent");
}
let ready = Arc::new(AtomicBool::new(true));
let online_w = online.clone();
let ready_w = ready.clone();
let txb_w = shared_txb.clone();
tokio::spawn(async move {
let mut port_w = port_write;
while let Some(data) = rx.recv().await {
txb_w.fetch_add(data.len() as u64, Ordering::Relaxed);
if flow_control {
let start = std::time::Instant::now();
while !ready_w.load(Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(10)).await;
if !online_w.load(Ordering::SeqCst) {
return;
}
if start.elapsed() > Duration::from_secs(FLOW_CONTROL_TIMEOUT_SECS) {
tracing::warn!("AX.25 KISS flow control timeout, unlocking");
ready_w.store(true, Ordering::SeqCst);
break;
}
}
}
let framed =
frame_ax25_kiss(&data, &dst_call_bytes, dst_ssid, &src_call_bytes, src_ssid);
if flow_control {
ready_w.store(false, Ordering::SeqCst);
}
let online_ref = online_w.clone();
let result = tokio::task::spawn_blocking(move || {
use std::io::Write;
port_w.write_all(&framed)?;
port_w.flush()?;
Ok::<_, std::io::Error>(port_w)
})
.await;
match result {
Ok(Ok(p)) => {
port_w = p;
}
Ok(Err(e)) => {
tracing::warn!(error = %e, "AX.25 KISS write error");
online_ref.store(false, Ordering::SeqCst);
break;
}
Err(e) => {
tracing::warn!(error = %e, "AX.25 KISS write task panicked");
break;
}
}
}
});
let online_r = online.clone();
let ready_r = ready;
let rxb_r = shared_rxb.clone();
let read_task = tokio::spawn(async move {
let mut port_r = port;
let mut deframer = kiss::KissDeframer::new();
let mut buf = [0u8; 1024];
loop {
if !online_r.load(Ordering::SeqCst) {
break;
}
let result = tokio::task::spawn_blocking(move || {
use std::io::Read;
match port_r.read(&mut buf) {
Ok(n) => Ok((port_r, buf, n)),
Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok((port_r, buf, 0)),
Err(e) => Err((port_r, e)),
}
})
.await;
match result {
Ok(Ok((p, b, n))) => {
port_r = p;
buf = b;
if n > 0 {
rxb_r.fetch_add(n as u64, Ordering::Relaxed);
for (cmd, frame) in deframer.feed(&buf[..n]) {
match cmd {
kiss::CMD_DATA => {
let payload = match strip_ax25_header(&frame) {
Some(p) if !p.is_empty() => p.to_vec(),
_ => continue,
};
let msg = TransportMessage::Inbound(InboundPacket {
raw: Bytes::from(payload),
interface_id: id,
rssi: None,
snr: None,
q: None,
});
if transport_tx.send(msg).await.is_err() {
tracing::warn!(id, "transport channel closed");
online_r.store(false, Ordering::SeqCst);
return;
}
}
kiss::CMD_READY => {
ready_r.store(true, Ordering::SeqCst);
tracing::debug!(id, "AX.25 KISS flow control: ready");
}
_ => {
tracing::debug!(id, cmd, "ignoring KISS command");
}
}
}
}
}
Ok(Err((_p, e))) => {
tracing::warn!(error = %e, "AX.25 KISS read error");
online_r.store(false, Ordering::SeqCst);
return;
}
Err(e) => {
tracing::warn!(error = %e, "AX.25 KISS read task panicked");
online_r.store(false, Ordering::SeqCst);
return;
}
}
}
});
Ok(InterfaceHandle {
id,
name,
mode,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: BITRATE_GUESS,
mtu: HW_MTU as u32,
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
tx,
read_task,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_ax25_config() {
let cfg = AX25KISSConfig::new("ax25-0", "/dev/ttyUSB0", "N0CALL", 7);
assert_eq!(cfg.src_call, "N0CALL");
assert_eq!(cfg.src_ssid, 7);
assert_eq!(cfg.dst_call, "APZRNS");
assert_eq!(cfg.preamble, 350);
assert!(cfg.validate().is_ok());
}
#[test]
fn test_ax25_config_validation() {
let cfg = AX25KISSConfig::new("ax25", "/dev/ttyUSB0", "AB", 0);
assert!(cfg.validate().is_err());
let cfg = AX25KISSConfig::new("ax25", "/dev/ttyUSB0", "ABCDEFG", 0);
assert!(cfg.validate().is_err());
let mut cfg = AX25KISSConfig::new("ax25", "/dev/ttyUSB0", "N0CALL", 0);
cfg.src_ssid = 16;
assert!(cfg.validate().is_err());
}
#[test]
fn test_build_ax25_header() {
let header = build_ax25_header(b"APZRNS", 0, b"N0CALL", 7);
assert_eq!(header.len(), AX25_HEADER_SIZE);
assert_eq!(header[0], b'A' << 1);
assert_eq!(header[6], 0x60);
assert_eq!(header[7], b'N' << 1);
assert_eq!(header[13], 0x60 | (7 << 1) | 0x01);
assert_eq!(header[14], AX25_CTRL_UI);
assert_eq!(header[15], AX25_PID_NOLAYER3);
}
#[test]
fn test_frame_ax25_kiss_roundtrip() {
let data = b"hello ax25";
let framed = frame_ax25_kiss(data, b"APZRNS", 0, b"N0CALL", 7);
let mut deframer = kiss::KissDeframer::new();
let frames = deframer.feed(&framed);
assert_eq!(frames.len(), 1);
let (cmd, payload) = &frames[0];
assert_eq!(*cmd, kiss::CMD_DATA);
let stripped = strip_ax25_header(payload).unwrap();
assert_eq!(stripped, data);
}
#[test]
fn test_strip_ax25_header_too_short() {
let short_data = [0u8; AX25_HEADER_SIZE];
assert!(strip_ax25_header(&short_data).is_none());
assert!(strip_ax25_header(&[]).is_none());
}
#[test]
fn test_ax25_kiss_init_parseable() {
let cfg = AX25KISSConfig::new("ax25", "/dev/ttyUSB0", "N0CALL", 7);
let init_seq = build_ax25_kiss_init(&cfg);
let mut deframer = kiss::KissDeframer::new();
let frames = deframer.feed(&init_seq);
assert_eq!(frames.len(), 5);
}
#[test]
fn test_parse_callsign_ssid_with_ssid() {
let (call, ssid) = parse_callsign_ssid("N0CALL-7").unwrap();
assert_eq!(call, "N0CALL");
assert_eq!(ssid, 7);
}
#[test]
fn test_parse_callsign_ssid_without_ssid() {
let (call, ssid) = parse_callsign_ssid("N0CALL").unwrap();
assert_eq!(call, "N0CALL");
assert_eq!(ssid, 0);
}
#[test]
fn test_parse_callsign_ssid_zero() {
let (call, ssid) = parse_callsign_ssid("ABC-0").unwrap();
assert_eq!(call, "ABC");
assert_eq!(ssid, 0);
}
#[test]
fn test_parse_callsign_ssid_max() {
let (call, ssid) = parse_callsign_ssid("W1AW-15").unwrap();
assert_eq!(call, "W1AW");
assert_eq!(ssid, 15);
}
#[test]
fn test_parse_callsign_ssid_lowercase() {
let (call, ssid) = parse_callsign_ssid("n0call-3").unwrap();
assert_eq!(call, "N0CALL");
assert_eq!(ssid, 3);
}
#[test]
fn test_parse_callsign_ssid_too_short() {
assert!(parse_callsign_ssid("AB-1").is_err());
assert!(parse_callsign_ssid("AB").is_err());
}
#[test]
fn test_parse_callsign_ssid_too_long() {
assert!(parse_callsign_ssid("ABCDEFG-1").is_err());
}
#[test]
fn test_parse_callsign_ssid_invalid_ssid() {
assert!(parse_callsign_ssid("N0CALL-16").is_err());
assert!(parse_callsign_ssid("N0CALL-99").is_err());
assert!(parse_callsign_ssid("N0CALL-abc").is_err());
}
#[test]
fn test_parse_callsign_ssid_non_ascii() {
assert!(parse_callsign_ssid("N0C@LL-1").is_err());
}
#[test]
fn test_callsign_shift_and_padding() {
let header = build_ax25_header(b"CQ", 0, b"ABC", 0);
assert_eq!(header[0], b'C' << 1);
assert_eq!(header[1], b'Q' << 1);
assert_eq!(header[2], 0x20);
assert_eq!(header[3], 0x20);
assert_eq!(header[4], 0x20);
assert_eq!(header[5], 0x20);
assert_eq!(header[7], b'A' << 1);
assert_eq!(header[8], b'B' << 1);
assert_eq!(header[9], b'C' << 1);
assert_eq!(header[10], 0x20);
assert_eq!(header[11], 0x20);
assert_eq!(header[12], 0x20);
}
#[test]
fn test_header_ssid_encoding() {
let header = build_ax25_header(b"DST", 0, b"SRC", 0);
assert_eq!(header[6], 0x60);
assert_eq!(header[13], 0x60 | 0x01);
let header = build_ax25_header(b"DST", 15, b"SRC", 15);
assert_eq!(header[6], 0x7E);
assert_eq!(header[13], 0x7E | 0x01);
}
#[test]
fn test_header_full_callsign() {
let header = build_ax25_header(b"ABCDEF", 0, b"GHIJKL", 0);
assert_eq!(header[0], b'A' << 1);
assert_eq!(header[1], b'B' << 1);
assert_eq!(header[2], b'C' << 1);
assert_eq!(header[3], b'D' << 1);
assert_eq!(header[4], b'E' << 1);
assert_eq!(header[5], b'F' << 1);
assert_eq!(header[7], b'G' << 1);
assert_eq!(header[8], b'H' << 1);
assert_eq!(header[9], b'I' << 1);
assert_eq!(header[10], b'J' << 1);
assert_eq!(header[11], b'K' << 1);
assert_eq!(header[12], b'L' << 1);
}
#[test]
fn test_ax25_kiss_init_values() {
let cfg = AX25KISSConfig::new("ax25", "/dev/ttyUSB0", "N0CALL", 0);
let init_seq = build_ax25_kiss_init(&cfg);
let mut deframer = kiss::KissDeframer::new();
let frames = deframer.feed(&init_seq);
assert_eq!(frames[0].0, kiss::CMD_TXDELAY);
assert_eq!(frames[0].1, &[35]);
assert_eq!(frames[1].0, kiss::CMD_TXTAIL);
assert_eq!(frames[1].1, &[2]);
assert_eq!(frames[2].0, kiss::CMD_P);
assert_eq!(frames[2].1, &[64]);
assert_eq!(frames[3].0, kiss::CMD_SLOTTIME);
assert_eq!(frames[3].1, &[2]);
assert_eq!(frames[4].0, kiss::CMD_READY);
assert_eq!(frames[4].1, &[0x01]);
}
#[test]
fn test_strip_ax25_header_exact_payload() {
let mut data = [0u8; AX25_HEADER_SIZE + 1];
data[AX25_HEADER_SIZE] = 0x42;
let payload = strip_ax25_header(&data).unwrap();
assert_eq!(payload, &[0x42]);
}
#[test]
fn test_frame_ax25_kiss_wire_vector() {
// Byte-exact wire vector for APZRNS-0 <- N0CALL-7.
let data = b"\x01\x02\x03";
let framed = frame_ax25_kiss(data, b"APZRNS", 0, b"N0CALL", 7);
let mut deframer = kiss::KissDeframer::new();
let frames = deframer.feed(&framed);
assert_eq!(frames.len(), 1);
let inner = &frames[0].1;
assert_eq!(inner[0], 0x82);
assert_eq!(inner[1], 0xA0);
assert_eq!(inner[2], 0xB4);
assert_eq!(inner[3], 0xA4);
assert_eq!(inner[4], 0x9C);
assert_eq!(inner[5], 0xA6);
assert_eq!(inner[6], 0x60);
assert_eq!(inner[7], 0x9C);
assert_eq!(inner[8], 0x60);
assert_eq!(inner[9], 0x86);
assert_eq!(inner[10], 0x82);
assert_eq!(inner[11], 0x98);
assert_eq!(inner[12], 0x98);
assert_eq!(inner[13], 0x6F);
assert_eq!(inner[14], AX25_CTRL_UI);
assert_eq!(inner[15], AX25_PID_NOLAYER3);
assert_eq!(&inner[16..], data);
}
#[test]
fn test_config_from_parsed_callsign() {
let (call, ssid) = parse_callsign_ssid("W1AW-12").unwrap();
let cfg = AX25KISSConfig::new("ax25-0", "/dev/ttyUSB0", &call, ssid);
assert_eq!(cfg.src_call, "W1AW");
assert_eq!(cfg.src_ssid, 12);
assert!(cfg.validate().is_ok());
}
}
+609
View File
@@ -0,0 +1,609 @@
//! High-throughput HDLC-over-TCP backbone. Server accepts many peers
//! (each its own [`InterfaceHandle`]); client auto-reconnects.
//! Per-peer tuning: TCP keepalive + TCP_USER_TIMEOUT + NODELAY + large
//! buffers. Inbound deframer is capped (vs Python's unbounded) to avoid
//! malformed-peer memory blow-up.
use std::net::IpAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;
use bytes::Bytes;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::mpsc;
use crate::hdlc;
use crate::socket_tuning::{iface_addr_for, set_keepalive_tuned, set_socket_buffers};
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
use rns_transport::messages::{InboundPacket, TransportMessage};
/// 1 MiB MTU — also the SO_RCVBUF/SNDBUF target (kernel clamps).
pub const HW_MTU: u32 = 1_048_576;
/// Listener-side bitrate guess advertised on the parent handle.
pub const BITRATE_GUESS: u64 = 1_000_000_000;
/// Per-peer guess (100 Mbps) — drives [`crate::traits::optimise_mtu`] → 64 KiB MTU.
pub const CHILD_BITRATE_GUESS: u64 = 100_000_000;
pub const RECONNECT_WAIT: u64 = 5;
pub const INITIAL_CONNECT_TIMEOUT: u64 = 5;
pub const TCP_PROBE_AFTER: u32 = 5;
pub const TCP_PROBE_INTERVAL: u32 = 2;
pub const TCP_PROBES: u32 = 12;
/// Linux TCP_USER_TIMEOUT — drops stuck conns when peer goes silent without RST.
pub const TCP_USER_TIMEOUT: u32 = 24;
const TX_CHANNEL_DEPTH: usize = 1024;
#[derive(Debug, Clone)]
pub struct BackboneServerConfig {
pub name: String,
pub listen_ip: String,
pub listen_port: u16,
pub prefer_ipv6: bool,
pub mode: InterfaceMode,
/// Optional kernel ifname; binds to its current IP (falls back to `listen_ip`).
pub device: Option<String>,
}
impl BackboneServerConfig {
pub fn new(name: &str, ip: &str, port: u16) -> Self {
Self {
name: name.to_string(),
listen_ip: ip.to_string(),
listen_port: port,
prefer_ipv6: false,
mode: InterfaceMode::Full,
device: None,
}
}
}
#[derive(Debug, Clone)]
pub struct BackboneClientConfig {
pub name: String,
pub target_host: String,
pub target_port: u16,
pub prefer_ipv6: bool,
pub connect_timeout_secs: u64,
pub max_reconnect_tries: Option<usize>,
pub mode: InterfaceMode,
}
impl BackboneClientConfig {
pub fn new(name: &str, host: &str, port: u16) -> Self {
Self {
name: name.to_string(),
target_host: host.to_string(),
target_port: port,
prefer_ipv6: false,
connect_timeout_secs: INITIAL_CONNECT_TIMEOUT,
max_reconnect_tries: None,
mode: InterfaceMode::Full,
}
}
}
fn keepalive_durations() -> (Duration, Duration, u32, Duration) {
(
Duration::from_secs(TCP_PROBE_AFTER as u64),
Duration::from_secs(TCP_PROBE_INTERVAL as u64),
TCP_PROBES,
Duration::from_secs(TCP_USER_TIMEOUT as u64),
)
}
fn tune_stream(stream: &TcpStream) {
let _ = stream.set_nodelay(true);
let (idle, intvl, retries, user_timeout) = keepalive_durations();
set_keepalive_tuned(stream, idle, intvl, retries, user_timeout);
set_socket_buffers(stream, HW_MTU as usize);
}
fn child_mtu() -> u32 {
crate::traits::optimise_mtu(CHILD_BITRATE_GUESS)
.map(|m| m.min(HW_MTU))
.unwrap_or(rns_wire::constants::MTU as u32)
}
async fn backbone_read_loop(
mut reader: tokio::net::tcp::OwnedReadHalf,
interface_id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
online: Arc<AtomicBool>,
rxb: Arc<AtomicU64>,
) {
let mut deframer = hdlc::HdlcDeframer::new();
// Large buffer to amortise syscalls; inbound capped by HdlcDeframer::MAX_FRAME_SIZE.
let mut buf = vec![0u8; 65536];
loop {
match reader.read(&mut buf).await {
Ok(0) => {
tracing::info!(interface_id, "backbone read: EOF");
break;
}
Ok(n) => {
rxb.fetch_add(n as u64, Ordering::Relaxed);
for frame in deframer.feed(&buf[..n]) {
if frame.is_empty() {
continue;
}
let msg = TransportMessage::Inbound(InboundPacket {
raw: Bytes::from(frame),
interface_id,
rssi: None,
snr: None,
q: None,
});
if transport_tx.send(msg).await.is_err() {
tracing::warn!(interface_id, "transport channel closed");
online.store(false, Ordering::SeqCst);
return;
}
}
}
Err(e) => {
tracing::warn!(interface_id, error = %e, "backbone read error");
break;
}
}
}
online.store(false, Ordering::SeqCst);
}
async fn backbone_write_loop(
mut writer: tokio::net::tcp::OwnedWriteHalf,
mut rx: mpsc::Receiver<Bytes>,
online: Arc<AtomicBool>,
txb: Arc<AtomicU64>,
) {
while let Some(data) = rx.recv().await {
let framed = hdlc::frame(&data);
txb.fetch_add(framed.len() as u64, Ordering::Relaxed);
if let Err(e) = writer.write_all(&framed).await {
tracing::warn!(error = %e, "backbone write error");
break;
}
}
online.store(false, Ordering::SeqCst);
}
/// `device` takes precedence over `listen_ip` when its lookup succeeds.
fn resolve_listen_addr(config: &BackboneServerConfig) -> String {
if let Some(name) = config.device.as_deref() {
match iface_addr_for(name, config.prefer_ipv6) {
Some(IpAddr::V4(v4)) => return v4.to_string(),
Some(IpAddr::V6(v6)) => return format!("[{}]", v6),
None => {
tracing::warn!(
device = %name,
listen_ip = %config.listen_ip,
"backbone: device lookup failed, falling back to listen_ip",
);
}
}
}
config.listen_ip.clone()
}
/// Resolve `host:port` preferring the configured address family.
async fn resolve_target(
host: &str,
port: u16,
prefer_ipv6: bool,
) -> std::io::Result<std::net::SocketAddr> {
let mut addrs: Vec<std::net::SocketAddr> =
tokio::net::lookup_host((host, port)).await?.collect();
if addrs.is_empty() {
return Err(std::io::Error::new(
std::io::ErrorKind::AddrNotAvailable,
format!("no addresses resolved for {host}:{port}"),
));
}
// Prefer the requested family; else first resolved.
let preferred = if prefer_ipv6 {
addrs.iter().find(|a| a.is_ipv6()).copied()
} else {
addrs.iter().find(|a| a.is_ipv4()).copied()
};
Ok(preferred.unwrap_or_else(|| addrs.remove(0)))
}
/// Spawn a backbone server; each accepted connection becomes an `InterfaceHandle`.
pub async fn spawn_backbone_server(
config: BackboneServerConfig,
id: InterfaceId,
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let listen_ip = resolve_listen_addr(&config);
let bind_addr = if listen_ip.starts_with('[') {
format!("{}:{}", listen_ip, config.listen_port)
} else if listen_ip.contains(':') && !listen_ip.contains('.') {
format!("[{}]:{}", listen_ip, config.listen_port)
} else {
format!("{}:{}", listen_ip, config.listen_port)
};
let listener = TcpListener::bind(&bind_addr).await?;
let local_addr = listener.local_addr()?;
tracing::info!(name = %config.name, addr = %local_addr, "backbone server listening");
let online = Arc::new(AtomicBool::new(true));
let online2 = online.clone();
let name = config.name.clone();
let mode = config.mode;
// Parent listener is inbound-only; drain task warns on stray writes.
let (tx, mut listener_rx) = mpsc::channel::<Bytes>(1);
let drain_name = name.clone();
tokio::spawn(async move {
while listener_rx.recv().await.is_some() {
tracing::warn!(
name = %drain_name,
"backbone listener tx received unexpected outbound data; dropping",
);
}
});
let read_task = tokio::spawn(async move {
loop {
match listener.accept().await {
Ok((stream, peer)) => {
let client_id = id_gen.fetch_add(1, Ordering::SeqCst);
let client_name = format!("{}/client_{}", config.name, client_id);
tracing::info!(
name = %client_name,
peer = %peer,
"backbone: accepted connection",
);
tune_stream(&stream);
let c_online = Arc::new(AtomicBool::new(true));
let c_rxb = Arc::new(AtomicU64::new(0));
let c_txb = Arc::new(AtomicU64::new(0));
let (c_tx, c_rx) = mpsc::channel::<Bytes>(TX_CHANNEL_DEPTH);
let (reader, writer) = stream.into_split();
let c_online_w = c_online.clone();
let c_txb_w = c_txb.clone();
tokio::spawn(backbone_write_loop(writer, c_rx, c_online_w, c_txb_w));
let c_online_r = c_online.clone();
let c_rxb_r = c_rxb.clone();
let transport_tx2 = transport_tx.clone();
let dereg_tx = transport_tx.clone();
let cname = client_name.clone();
let read_handle = tokio::spawn(async move {
backbone_read_loop(reader, client_id, transport_tx2, c_online_r, c_rxb_r)
.await;
tracing::info!(name = %cname, "backbone client disconnected");
// Proactive notify so broadcasts don't target dead tx.
let _ = dereg_tx
.send(TransportMessage::DeregisterInterface { id: client_id })
.await;
});
let handle = InterfaceHandle {
id: client_id,
name: client_name,
mode,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: CHILD_BITRATE_GUESS,
mtu: child_mtu(),
online: c_online,
rxb: Some(c_rxb),
txb: Some(c_txb),
tx: c_tx,
read_task: read_handle,
};
if handle_tx.send(handle).await.is_err() {
tracing::warn!("backbone handle registry closed");
break;
}
}
Err(e) => {
tracing::warn!(error = %e, "backbone accept error");
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
}
online2.store(false, Ordering::SeqCst);
});
Ok(InterfaceHandle {
id,
name,
mode,
direction: InterfaceDirection {
inbound: true,
outbound: false,
forward: false,
repeat: false,
},
bitrate: BITRATE_GUESS,
mtu: rns_wire::constants::MTU as u32,
online,
rxb: Some(Arc::new(AtomicU64::new(0))),
txb: Some(Arc::new(AtomicU64::new(0))),
tx,
read_task,
})
}
pub async fn spawn_backbone_client(
config: BackboneClientConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let online = Arc::new(AtomicBool::new(false));
let online2 = online.clone();
let (tx, rx) = mpsc::channel::<Bytes>(TX_CHANNEL_DEPTH);
let name = config.name.clone();
let mode = config.mode;
let rx = Arc::new(tokio::sync::Mutex::new(rx));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let task_rxb = shared_rxb.clone();
let task_txb = shared_txb.clone();
let read_task = tokio::spawn(async move {
let max_tries = config.max_reconnect_tries;
let mut tries: usize = 0;
loop {
let target = match tokio::time::timeout(
Duration::from_secs(config.connect_timeout_secs),
resolve_target(&config.target_host, config.target_port, config.prefer_ipv6),
)
.await
{
Ok(Ok(addr)) => addr,
Ok(Err(e)) => {
tracing::warn!(name = %config.name, error = %e, "backbone resolve failed");
if let Some(max) = max_tries {
tries += 1;
if tries >= max {
let _ = transport_tx
.send(TransportMessage::DeregisterInterface { id })
.await;
return;
}
}
tokio::time::sleep(Duration::from_secs(RECONNECT_WAIT)).await;
continue;
}
Err(_) => {
tracing::warn!(name = %config.name, "backbone resolve timed out");
if let Some(max) = max_tries {
tries += 1;
if tries >= max {
let _ = transport_tx
.send(TransportMessage::DeregisterInterface { id })
.await;
return;
}
}
tokio::time::sleep(Duration::from_secs(RECONNECT_WAIT)).await;
continue;
}
};
let stream = match tokio::time::timeout(
Duration::from_secs(config.connect_timeout_secs),
TcpStream::connect(target),
)
.await
{
Ok(Ok(s)) => s,
Ok(Err(e)) => {
tracing::warn!(name = %config.name, error = %e, "backbone connect failed");
if let Some(max) = max_tries {
tries += 1;
if tries >= max {
let _ = transport_tx
.send(TransportMessage::DeregisterInterface { id })
.await;
return;
}
}
tokio::time::sleep(Duration::from_secs(RECONNECT_WAIT)).await;
continue;
}
Err(_) => {
tracing::warn!(name = %config.name, "backbone connect timed out");
if let Some(max) = max_tries {
tries += 1;
if tries >= max {
let _ = transport_tx
.send(TransportMessage::DeregisterInterface { id })
.await;
return;
}
}
tokio::time::sleep(Duration::from_secs(RECONNECT_WAIT)).await;
continue;
}
};
tune_stream(&stream);
online2.store(true, Ordering::SeqCst);
tries = 0;
let c_online = Arc::new(AtomicBool::new(true));
let (reader, writer) = stream.into_split();
let (conn_tx, conn_rx) = mpsc::channel::<Bytes>(TX_CHANNEL_DEPTH);
let c_online_w = c_online.clone();
let c_txb = task_txb.clone();
let write_handle =
tokio::spawn(backbone_write_loop(writer, conn_rx, c_online_w, c_txb));
let rx_ref = rx.clone();
let fwd_handle = tokio::spawn(async move {
let mut guard = rx_ref.lock().await;
while let Some(data) = guard.recv().await {
if conn_tx.send(data).await.is_err() {
break;
}
}
});
let c_online_r = c_online.clone();
let c_rxb = task_rxb.clone();
backbone_read_loop(reader, id, transport_tx.clone(), c_online_r, c_rxb).await;
online2.store(false, Ordering::SeqCst);
fwd_handle.abort();
let _ = fwd_handle.await;
write_handle.abort();
let _ = write_handle.await;
if let Some(max) = max_tries {
tries += 1;
if tries >= max {
let _ = transport_tx
.send(TransportMessage::DeregisterInterface { id })
.await;
return;
}
}
tracing::info!(
name = %config.name,
"backbone: reconnecting in {}s",
RECONNECT_WAIT,
);
tokio::time::sleep(Duration::from_secs(RECONNECT_WAIT)).await;
}
});
Ok(InterfaceHandle {
id,
name,
mode,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: CHILD_BITRATE_GUESS,
mtu: child_mtu(),
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
tx,
read_task,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_backbone_server_config() {
let cfg = BackboneServerConfig::new("backbone0", "0.0.0.0", 4243);
assert_eq!(cfg.listen_port, 4243);
assert!(!cfg.prefer_ipv6);
assert!(cfg.device.is_none());
}
#[test]
fn test_backbone_client_config() {
let cfg = BackboneClientConfig::new("bb-client", "10.0.0.1", 4243);
assert_eq!(cfg.target_host, "10.0.0.1");
assert_eq!(cfg.connect_timeout_secs, INITIAL_CONNECT_TIMEOUT);
}
#[test]
fn test_constants() {
assert_eq!(HW_MTU, 1_048_576);
assert_eq!(BITRATE_GUESS, 1_000_000_000);
assert_eq!(CHILD_BITRATE_GUESS, 100_000_000);
assert_eq!(RECONNECT_WAIT, 5);
}
#[test]
fn test_backbone_server_config_mode() {
let cfg = BackboneServerConfig::new("bb-srv", "0.0.0.0", 4243);
assert_eq!(cfg.mode, InterfaceMode::Full);
assert_eq!(cfg.listen_ip, "0.0.0.0");
assert_eq!(cfg.name, "bb-srv");
}
#[test]
fn test_backbone_client_config_defaults() {
let cfg = BackboneClientConfig::new("bb-cli", "192.168.1.1", 4243);
assert_eq!(cfg.target_host, "192.168.1.1");
assert_eq!(cfg.target_port, 4243);
assert_eq!(cfg.mode, InterfaceMode::Full);
assert!(cfg.max_reconnect_tries.is_none());
}
#[test]
fn test_backbone_config_ipv6() {
let cfg = BackboneServerConfig::new("bb-v6", "::", 4243);
assert!(!cfg.prefer_ipv6);
let mut cfg = cfg;
cfg.prefer_ipv6 = true;
assert!(cfg.prefer_ipv6);
}
#[test]
fn test_child_mtu_uses_100mbps_curve() {
// optimise_mtu(100 Mbps) is one of the step values; verify the
// result lands inside the HW_MTU ceiling.
let mtu = child_mtu();
assert!(mtu <= HW_MTU);
assert!(mtu >= rns_wire::constants::MTU as u32 / 2);
}
#[tokio::test]
async fn test_backbone_max_reconnect_dereg() {
// Connect attempts to a port nobody is listening on; with
// max_reconnect_tries = Some(1) we get one connect attempt, one
// failure, then DeregisterInterface and exit.
let mut cfg = BackboneClientConfig::new("bb-dereg", "127.0.0.1", 1);
cfg.connect_timeout_secs = 1;
cfg.max_reconnect_tries = Some(1);
let (tx, mut rx) = mpsc::channel::<TransportMessage>(8);
let handle = spawn_backbone_client(cfg, 99, tx).await.unwrap();
// Wait for the read_task to finish — guarded by a generous timeout
// to absorb the one RECONNECT_WAIT sleep + connect attempt.
let dereg = tokio::time::timeout(Duration::from_secs(15), async {
loop {
match rx.recv().await {
Some(TransportMessage::DeregisterInterface { id }) => return Some(id),
Some(_) => continue,
None => return None,
}
}
})
.await
.ok()
.flatten();
assert_eq!(dereg, Some(99));
// Drop the handle (aborts read_task if still alive).
drop(handle);
}
#[tokio::test]
async fn test_resolve_target_loopback_v4() {
let addr = resolve_target("127.0.0.1", 1234, false).await.unwrap();
assert!(addr.is_ipv4());
assert_eq!(addr.port(), 1234);
}
}
@@ -0,0 +1,932 @@
//! Apple CBCentralManager scan driver.
//!
//! Exists to pass `CBCentralManagerScanOptionAllowDuplicatesKey = YES` to
//! `scanForPeripheralsWithServices:options:` — btleplug does not expose
//! that key, and without it CoreBluetooth reports each peripheral at most
//! once per scan session.
#![cfg(any(target_os = "ios", target_os = "macos"))]
use crate::ble_central_lifecycle::{
CentralEvent, CentralLifecycle, CentralState, DiscoveryEvent, classify_protocol,
};
use crate::ble_peer::{COLUMBA_SERVICE_UUID, RATSPEAK_SERVICE_UUID};
use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel};
use objc2::{msg_send, sel};
use objc2_core_bluetooth::{
CBAdvertisementDataServiceUUIDsKey, CBCentralManagerOptionRestoreIdentifierKey,
CBCentralManagerRestoredStatePeripheralsKey, CBCentralManagerRestoredStateScanOptionsKey,
CBCentralManagerRestoredStateScanServicesKey, CBCentralManagerScanOptionAllowDuplicatesKey,
};
use objc2_foundation::NSString;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
use tokio::sync::mpsc;
use uuid::Uuid;
/// Must stay stable across updates; changing forfeits previously-backgrounded connections.
const CENTRAL_RESTORE_ID: &str = "org.ratspeak.ios.central";
struct SendPtr(*mut AnyObject);
unsafe impl Send for SendPtr {}
unsafe impl Sync for SendPtr {}
/// Live CBCentralManager. Null when no scan is in flight.
static MANAGER_PTR: OnceLock<Mutex<SendPtr>> = OnceLock::new();
static DELEGATE_CLASS: OnceLock<&'static AnyClass> = OnceLock::new();
static LIFECYCLE: OnceLock<CentralLifecycle> = OnceLock::new();
/// Replaced every `start_scan` so each cycle has a fresh receiver.
static DISCOVERY_TX: OnceLock<Mutex<Option<mpsc::UnboundedSender<DiscoveryEvent>>>> =
OnceLock::new();
/// Worker thread waits on this until `did_update_state` reports `PoweredOn`.
static POWERED_ON_TX: OnceLock<Mutex<Option<std::sync::mpsc::Sender<()>>>> = OnceLock::new();
static SCAN_SERVICES: OnceLock<Mutex<Vec<Uuid>>> = OnceLock::new();
fn lifecycle() -> &'static CentralLifecycle {
LIFECYCLE.get_or_init(CentralLifecycle::new)
}
/// Trace invalid transitions instead of panicking — BLE stacks occasionally
/// deliver redundant callbacks.
fn apply_event(event: CentralEvent) -> Option<CentralState> {
match lifecycle().apply(event.clone()) {
Ok(state) => {
tracing::trace!(?event, ?state, "Apple BLE central lifecycle");
Some(state)
}
Err(err) => {
tracing::warn!(?err, "Apple BLE central lifecycle: rejected transition");
None
}
}
}
fn discovery_tx() -> &'static Mutex<Option<mpsc::UnboundedSender<DiscoveryEvent>>> {
DISCOVERY_TX.get_or_init(|| Mutex::new(None))
}
fn powered_on_tx() -> &'static Mutex<Option<std::sync::mpsc::Sender<()>>> {
POWERED_ON_TX.get_or_init(|| Mutex::new(None))
}
fn scan_services() -> &'static Mutex<Vec<Uuid>> {
SCAN_SERVICES.get_or_init(|| Mutex::new(Vec::new()))
}
fn manager_slot() -> &'static Mutex<SendPtr> {
MANAGER_PTR.get_or_init(|| Mutex::new(SendPtr(std::ptr::null_mut())))
}
/// Start a CBCentralManager scan with `AllowDuplicatesKey = YES`. Empty
/// `services` scans for all advertisements.
pub async fn start_scan(
services: Vec<Uuid>,
) -> Result<mpsc::UnboundedReceiver<DiscoveryEvent>, String> {
let cur = lifecycle().current();
if matches!(
cur,
CentralState::Scanning | CentralState::StartingWaitingPlatform | CentralState::StoppingScan
) {
return Err(format!("BLE scan already in progress (state={cur:?})"));
}
apply_event(CentralEvent::StartRequested);
let (tx, rx) = mpsc::unbounded_channel::<DiscoveryEvent>();
{
let mut g = discovery_tx()
.lock()
.map_err(|e| format!("discovery_tx lock poisoned: {e}"))?;
*g = Some(tx);
}
{
let mut g = scan_services()
.lock()
.map_err(|e| format!("scan_services lock poisoned: {e}"))?;
*g = services;
}
// CoreBluetooth on macOS returns state=Unsupported on rapid alloc/release
// cycles, so the first manager stays retained and later cycles just rotate
// the discovery channel and reissue `scanForPeripheralsWithServices`.
let existing_mgr: Option<*mut AnyObject> = {
match manager_slot().lock() {
Ok(g) if !g.0.is_null() => Some(g.0),
_ => None,
}
};
if let Some(mgr_raw) = existing_mgr {
unsafe {
scan_with_manager(mgr_raw)
.map_err(|e| format!("rescan on persistent manager failed: {e}"))?;
}
apply_event(CentralEvent::PlatformReady);
tracing::info!(
target: "ble_trace",
step = "central.scan_reused_manager",
"Apple BLE Central: rescan invoked on persistent manager"
);
return Ok(rx);
}
let (signal_tx, signal_rx) = std::sync::mpsc::channel::<()>();
{
let mut g = powered_on_tx()
.lock()
.map_err(|e| format!("powered_on_tx lock poisoned: {e}"))?;
*g = Some(signal_tx);
}
// OS thread: raw `*mut AnyObject` isn't Send, and
// `initWithDelegate:queue:nil` wires the delegate to CoreBluetooth's
// main dispatch queue.
std::thread::spawn(move || unsafe {
let delegate_cls = get_delegate_class();
let delegate_raw: *mut AnyObject = msg_send![delegate_cls, alloc];
let delegate_raw: *mut AnyObject = msg_send![delegate_raw, init];
let Some(mgr_cls) = AnyClass::get("CBCentralManager") else {
tracing::error!("Apple BLE Central: CBCentralManager class not found");
return;
};
let mgr_raw: *mut AnyObject = msg_send![mgr_cls, alloc];
// RestoreIdentifierKey lets iOS resurrect us for a background BLE
// event after the process is killed.
let opts = match build_init_options() {
Ok(d) => d,
Err(e) => {
tracing::error!("Apple BLE Central: init-options build failed: {e}");
std::ptr::null_mut::<AnyObject>()
}
};
let mgr_raw: *mut AnyObject = msg_send![mgr_raw,
initWithDelegate: delegate_raw,
queue: std::ptr::null::<AnyObject>(),
options: opts,
];
// `retain` returns `id`; binding as `*mut AnyObject` avoids objc2's
// debug class-verify tripping on KVO-swizzled subclasses.
let _: *mut AnyObject = msg_send![mgr_raw, retain];
if let Ok(mut g) = manager_slot().lock() {
*g = SendPtr(mgr_raw);
}
tracing::info!("Apple BLE Central: manager created, waiting for PoweredOn");
// 10s safety net; real Bluetooth-off/permission errors surface
// through did_update_state, not here.
if let Err(e) = signal_rx.recv_timeout(Duration::from_secs(10)) {
tracing::error!("Apple BLE Central: timed out waiting for PoweredOn: {e}");
return;
}
match scan_with_manager(mgr_raw) {
Ok(()) => tracing::info!(
"Apple BLE Central: scanForPeripherals invoked (AllowDuplicates=YES)"
),
Err(e) => tracing::error!("Apple BLE Central: scan invocation failed: {e}"),
}
});
Ok(rx)
}
/// Idempotent.
pub async fn stop_scan() -> Result<(), String> {
let cur = lifecycle().current();
if matches!(
cur,
CentralState::Idle | CentralState::Stopped | CentralState::Failed
) {
tracing::debug!(state = ?cur, "Apple BLE Central: stop_scan is a no-op");
return Ok(());
}
apply_event(CentralEvent::StopRequested);
// Issue the ObjC calls outside the manager lock so concurrent
// did_discover callbacks (which take the same lock) can't deadlock.
let mgr_ptr: *mut AnyObject = {
match manager_slot().lock() {
Ok(g) if !g.0.is_null() => g.0,
_ => {
// No manager ever constructed, or already torn down.
finalize_stop();
return Ok(());
}
}
};
unsafe {
// We do NOT release the manager — the next start_scan reuses it.
// Per-cycle release on macOS triggers CBManagerStateUnsupported.
// `teardown_central` does the full release on interface shutdown.
let _: () = msg_send![&*mgr_ptr, stopScan];
}
finalize_stop();
Ok(())
}
/// Full teardown — interface shutdown only. Per-cycle stops use
/// [`stop_scan`] to keep the manager alive (macOS alloc-cycle bug).
pub async fn teardown_central() -> Result<(), String> {
let _ = stop_scan().await;
let mgr_ptr: *mut AnyObject = match manager_slot().lock() {
Ok(g) if !g.0.is_null() => g.0,
_ => return Ok(()),
};
unsafe {
// Detach delegate before release so a late main-queue callback
// can't fire into a freed object.
let _: () = msg_send![&*mgr_ptr, setDelegate: std::ptr::null::<AnyObject>()];
// Balance the explicit retain from start_scan; the original alloc
// ref is intentionally left intact — CoreBluetooth keeps one for
// main-queue drain and a double-release UAFs on contended teardown.
let _: () = msg_send![&*mgr_ptr, release];
}
if let Ok(mut g) = manager_slot().lock() {
*g = SendPtr(std::ptr::null_mut());
}
Ok(())
}
fn finalize_stop() {
if let Some(lock) = POWERED_ON_TX.get()
&& let Ok(mut g) = lock.lock()
{
*g = None;
}
// Drop the discovery sender so receivers don't hang on recv.
if let Some(lock) = DISCOVERY_TX.get()
&& let Ok(mut g) = lock.lock()
{
*g = None;
}
apply_event(CentralEvent::ScanStopped);
apply_event(CentralEvent::Reset);
}
pub fn current_state() -> CentralState {
lifecycle().current()
}
/// Persistent `CBCentralManager` pointer. Apple central peripheral caches
/// are per-manager, not per-process — `ble_central_apple_connect` must
/// drive `connectPeripheral:` against the same manager that scanned.
pub fn central_manager_ptr() -> Option<*mut AnyObject> {
let lock = MANAGER_PTR.get()?;
let g = lock.lock().ok()?;
if g.0.is_null() { None } else { Some(g.0) }
}
fn get_delegate_class() -> &'static AnyClass {
DELEGATE_CLASS.get_or_init(|| {
let superclass = AnyClass::get("NSObject").expect("NSObject must exist");
let mut builder = ClassBuilder::new("RatspeakBleCentralDelegate", superclass)
.expect("ClassBuilder for central delegate must succeed");
extern "C" fn did_update_state(
_this: *mut AnyObject,
_sel: Sel,
central: *mut AnyObject,
) {
if central.is_null() {
return;
}
let state: i64 = unsafe { msg_send![&*central, state] };
tracing::info!(
state,
name = cb_state_name(state),
"Apple BLE Central: state update"
);
match state {
// CBManagerState: 0=Unknown 1=Resetting 2=Unsupported
// 3=Unauthorized 4=PoweredOff 5=PoweredOn.
0 => {}
1 => {
apply_event(CentralEvent::PlatformUnavailable {
reason: "resetting".into(),
});
}
2 => {
apply_event(CentralEvent::FatalError {
reason: "bluetooth unsupported".into(),
});
}
3 => {
apply_event(CentralEvent::FatalError {
reason: "bluetooth permission denied".into(),
});
}
4 => {
apply_event(CentralEvent::PlatformUnavailable {
reason: "bluetooth off".into(),
});
}
// PoweredOn: signal the start_scan worker, or reissue
// scanForPeripherals if the worker already exited (recovery).
5 => {
let tx = match powered_on_tx().lock() {
Ok(mut g) => g.take(),
Err(e) => {
tracing::error!("Apple BLE Central: powered_on_tx lock err: {e}");
return;
}
};
if let Some(tx) = tx {
if let Err(e) = tx.send(()) {
tracing::error!(
"Apple BLE Central: powered_on signal send err: {e}"
);
return;
}
apply_event(CentralEvent::PlatformReady);
tracing::info!(
"Apple BLE Central: powered on (initial), releasing worker"
);
return;
}
let s = lifecycle().current();
if !matches!(s, CentralState::StartingWaitingPlatform) {
tracing::info!(state = ?s, "Apple BLE Central: PoweredOn with no recovery needed");
return;
}
let Some(mgr_lock) = MANAGER_PTR.get() else {
tracing::warn!(
"Apple BLE Central: recovery PoweredOn but manager slot unset"
);
return;
};
let mgr_ptr = match mgr_lock.lock() {
Ok(g) if !g.0.is_null() => g.0,
_ => {
tracing::warn!(
"Apple BLE Central: recovery PoweredOn but manager is null"
);
return;
}
};
unsafe {
match scan_with_manager(mgr_ptr) {
Ok(()) => {
apply_event(CentralEvent::PlatformReady);
tracing::info!(
"Apple BLE Central: powered on (recovery), scan resumed"
);
}
Err(e) => {
tracing::error!(
"Apple BLE Central: recovery scan invocation failed: {e}"
);
}
}
}
}
_ => {
tracing::warn!(state, "Apple BLE Central: unknown CBManagerState");
}
}
}
// iOS calls this BEFORE `centralManagerDidUpdateState:` when
// resurrecting our process for a background BLE event. Restored TX
// subscriptions survive; we just need a live per-peripheral delegate
// before any further callbacks fire.
extern "C" fn will_restore_state(
_this: *mut AnyObject,
_sel: Sel,
_central: *mut AnyObject,
dict: *mut AnyObject,
) {
if dict.is_null() {
tracing::info!("Apple BLE Central: willRestoreState (empty dict)");
return;
}
unsafe {
let peripherals: *mut AnyObject =
msg_send![&*dict, objectForKey: CBCentralManagerRestoredStatePeripheralsKey];
let scan_services: *mut AnyObject =
msg_send![&*dict, objectForKey: CBCentralManagerRestoredStateScanServicesKey];
let scan_options: *mut AnyObject =
msg_send![&*dict, objectForKey: CBCentralManagerRestoredStateScanOptionsKey];
let peripheral_count: usize = if peripherals.is_null() {
0
} else {
msg_send![&*peripherals, count]
};
let service_count: usize = if scan_services.is_null() {
0
} else {
msg_send![&*scan_services, count]
};
let has_options = !scan_options.is_null();
tracing::info!(
target: "ble_trace",
step = "central.will_restore_state",
peripheral_count,
service_count,
has_options,
"Apple BLE Central: willRestoreState"
);
// Adopt only Connected peripherals; other states fall through
// to the next scan cycle. On error `adopt_restored_peer`
// releases the retain.
if !peripherals.is_null() {
for i in 0..peripheral_count {
let p: *mut AnyObject = msg_send![&*peripherals, objectAtIndex: i];
if p.is_null() {
continue;
}
let state: i64 = msg_send![&*p, state];
let identifier = peripheral_identifier(p);
if identifier.is_empty() {
tracing::warn!(
target: "ble_trace",
step = "central.restore_skip_no_id",
cb_state = state,
"Apple BLE Central: skipping restored peripheral with no identifier"
);
continue;
}
const CB_PERIPHERAL_STATE_CONNECTED: i64 = 2;
if state != CB_PERIPHERAL_STATE_CONNECTED {
tracing::info!(
target: "ble_trace",
step = "central.restore_skip_state",
address = %identifier,
cb_state = state,
"Apple BLE Central: restored peripheral not in Connected state \u{2014} deferring to scan rediscovery"
);
continue;
}
// ConnectedPeer::drop balances this retain on success;
// adopt_restored_peer releases on failure.
let _: *mut AnyObject = msg_send![p, retain];
match crate::ble_central_apple_connect::adopt_restored_peer(
identifier.clone(),
p,
) {
Ok(()) => {
tracing::info!(
target: "ble_trace",
step = "central.restore_adopted",
address = %identifier,
"Apple BLE Central: restored Connected peripheral adopted"
);
}
Err(e) => {
tracing::warn!(
target: "ble_trace",
step = "central.restore_adopt_failed",
address = %identifier,
error = %e,
"Apple BLE Central: adopt_restored_peer failed; the helper already released the retain"
);
}
}
}
}
}
}
extern "C" fn did_discover(
_this: *mut AnyObject,
_sel: Sel,
_central: *mut AnyObject,
peripheral: *mut AnyObject,
ad_data: *mut AnyObject,
rssi: *mut AnyObject,
) {
if peripheral.is_null() {
return;
}
let identifier = unsafe { peripheral_identifier(peripheral) };
let rssi_i16: i16 = unsafe { nsnumber_to_i16(rssi) };
if identifier.is_empty() {
tracing::debug!(
target: "ble_trace",
step = "central.discover_drop_no_id",
rssi = rssi_i16,
"Apple BLE Central: didDiscoverPeripheral with empty identifier"
);
return;
}
let services = unsafe { extract_advertised_services(ad_data) };
let classified =
classify_protocol(&services, RATSPEAK_SERVICE_UUID, COLUMBA_SERVICE_UUID);
tracing::debug!(
target: "ble_trace",
step = "central.discover",
peripheral = %identifier,
rssi = rssi_i16,
advertised_services = ?services,
classified = ?classified,
"Apple BLE Central: didDiscoverPeripheral"
);
let protocol = match classified {
Some(p) => p,
// Duplicates mode occasionally reports ads that don't fully
// match the filter.
None => return,
};
// The connect path needs the same CBPeripheral pointer the scan
// saw — Apple central peripheral caches don't cross managers.
// CoreBluetooth delivers a valid `CBPeripheral *` for this delegate call.
unsafe {
crate::ble_central_apple_connect::record_discovered(
identifier.clone(),
peripheral,
);
}
let event = DiscoveryEvent {
identifier,
rssi: rssi_i16,
services,
protocol,
seen_at: Instant::now(),
};
// No sender means stop_scan raced us between the radio event
// and this callback — drop silently.
if let Some(lock) = DISCOVERY_TX.get()
&& let Ok(g) = lock.lock()
&& let Some(tx) = g.as_ref()
{
let _ = tx.send(event);
}
}
// Connection-state callbacks share this delegate (one delegate per
// CBCentralManager) and forward to ble_central_apple_connect.
extern "C" fn did_connect(
_this: *mut AnyObject,
_sel: Sel,
_central: *mut AnyObject,
peripheral: *mut AnyObject,
) {
let address = unsafe { peripheral_identifier(peripheral) };
if address.is_empty() {
return;
}
tracing::info!(
target: "ble_trace",
step = "central.did_connect",
address = %address,
"Apple BLE Central: didConnectPeripheral"
);
crate::ble_central_apple_connect::on_did_connect(&address);
}
extern "C" fn did_fail_to_connect(
_this: *mut AnyObject,
_sel: Sel,
_central: *mut AnyObject,
peripheral: *mut AnyObject,
error: *mut AnyObject,
) {
let address = unsafe { peripheral_identifier(peripheral) };
if address.is_empty() {
return;
}
let err = if error.is_null() {
"didFailToConnect (no error description)".to_string()
} else {
unsafe { nserror_message(error) }
};
tracing::warn!(
target: "ble_trace",
step = "central.did_fail_connect",
address = %address,
error = %err,
"Apple BLE Central: didFailToConnectPeripheral"
);
crate::ble_central_apple_connect::on_did_fail_connect(&address, err);
}
extern "C" fn did_disconnect(
_this: *mut AnyObject,
_sel: Sel,
_central: *mut AnyObject,
peripheral: *mut AnyObject,
error: *mut AnyObject,
) {
let address = unsafe { peripheral_identifier(peripheral) };
if address.is_empty() {
return;
}
let err = if error.is_null() {
None
} else {
Some(unsafe { nserror_message(error) })
};
tracing::info!(
target: "ble_trace",
step = "central.did_disconnect",
address = %address,
error = ?err,
"Apple BLE Central: didDisconnectPeripheral"
);
crate::ble_central_apple_connect::on_did_disconnect(&address, err);
}
unsafe {
builder.add_method(
sel!(centralManagerDidUpdateState:),
did_update_state as extern "C" fn(*mut AnyObject, Sel, *mut AnyObject),
);
builder.add_method(
sel!(centralManager:willRestoreState:),
will_restore_state
as extern "C" fn(*mut AnyObject, Sel, *mut AnyObject, *mut AnyObject),
);
builder.add_method(
sel!(centralManager:didDiscoverPeripheral:advertisementData:RSSI:),
did_discover
as extern "C" fn(
*mut AnyObject,
Sel,
*mut AnyObject,
*mut AnyObject,
*mut AnyObject,
*mut AnyObject,
),
);
builder.add_method(
sel!(centralManager:didConnectPeripheral:),
did_connect
as extern "C" fn(*mut AnyObject, Sel, *mut AnyObject, *mut AnyObject),
);
builder.add_method(
sel!(centralManager:didFailToConnectPeripheral:error:),
did_fail_to_connect
as extern "C" fn(
*mut AnyObject,
Sel,
*mut AnyObject,
*mut AnyObject,
*mut AnyObject,
),
);
builder.add_method(
sel!(centralManager:didDisconnectPeripheral:error:),
did_disconnect
as extern "C" fn(
*mut AnyObject,
Sel,
*mut AnyObject,
*mut AnyObject,
*mut AnyObject,
),
);
}
builder.register()
})
}
unsafe fn nserror_message(err: *mut AnyObject) -> String {
if err.is_null() {
return String::new();
}
unsafe {
let desc: *mut AnyObject = msg_send![&*err, localizedDescription];
nsstring_to_string(desc)
}
}
/// # Safety
/// `mgr_raw` must be a retained, non-null `CBCentralManager` whose delegate
/// has been installed and whose `state` is PoweredOn.
unsafe fn scan_with_manager(mgr_raw: *mut AnyObject) -> Result<(), String> {
let services = scan_services()
.lock()
.map_err(|e| format!("scan_services lock poisoned: {e}"))?
.clone();
unsafe {
// nil filter = scan all.
let svc_arr: *mut AnyObject = if services.is_empty() {
std::ptr::null_mut()
} else {
let arr_cls = AnyClass::get("NSArray").ok_or("NSArray not found")?;
let mut raw_ptrs: Vec<*const AnyObject> = Vec::with_capacity(services.len());
for u in &services {
raw_ptrs.push(cbuuid(u) as *const AnyObject);
}
msg_send![arr_cls,
arrayWithObjects: raw_ptrs.as_ptr(),
count: raw_ptrs.len()]
};
let number_cls = AnyClass::get("NSNumber").ok_or("NSNumber not found")?;
let dict_cls = AnyClass::get("NSDictionary").ok_or("NSDictionary not found")?;
let yes: *mut AnyObject = msg_send![number_cls, numberWithBool: true];
let opts: *mut AnyObject = msg_send![dict_cls,
dictionaryWithObject: yes,
forKey: CBCentralManagerScanOptionAllowDuplicatesKey];
tracing::info!(
target: "ble_trace",
step = "central.scan_invoked",
filter_count = services.len(),
filter_uuids = ?services,
"Apple BLE Central: scanForPeripheralsWithServices"
);
let _: () = msg_send![&*mgr_raw,
scanForPeripheralsWithServices: svc_arr,
options: opts];
}
Ok(())
}
/// `{ RestoreIdentifierKey: CENTRAL_RESTORE_ID }`. Ignored on macOS.
unsafe fn build_init_options() -> Result<*mut AnyObject, String> {
unsafe {
let dict_cls = AnyClass::get("NSDictionary").ok_or("NSDictionary not found")?;
let restore_id = NSString::from_str(CENTRAL_RESTORE_ID);
let opts: *mut AnyObject = msg_send![dict_cls,
dictionaryWithObject: &*restore_id,
forKey: CBCentralManagerOptionRestoreIdentifierKey];
Ok(opts)
}
}
fn cb_state_name(state: i64) -> &'static str {
match state {
0 => "unknown",
1 => "resetting",
2 => "unsupported",
3 => "unauthorized",
4 => "poweredOff",
5 => "poweredOn",
_ => "?",
}
}
unsafe fn peripheral_identifier(peripheral: *mut AnyObject) -> String {
unsafe {
let id_obj: *mut AnyObject = msg_send![&*peripheral, identifier];
if id_obj.is_null() {
return String::new();
}
let uuid_str: *mut AnyObject = msg_send![&*id_obj, UUIDString];
nsstring_to_string(uuid_str)
}
}
/// Short SIG forms like "180D" are expanded to the Bluetooth base UUID.
unsafe fn extract_advertised_services(ad_data: *mut AnyObject) -> Vec<Uuid> {
if ad_data.is_null() {
return Vec::new();
}
unsafe {
let arr: *mut AnyObject =
msg_send![&*ad_data, objectForKey: CBAdvertisementDataServiceUUIDsKey];
if arr.is_null() {
return Vec::new();
}
let count: usize = msg_send![&*arr, count];
let mut out = Vec::with_capacity(count);
for i in 0..count {
let cb: *mut AnyObject = msg_send![&*arr, objectAtIndex: i];
if cb.is_null() {
continue;
}
let s_obj: *mut AnyObject = msg_send![&*cb, UUIDString];
if s_obj.is_null() {
continue;
}
let s = nsstring_to_string(s_obj);
match Uuid::parse_str(&s) {
Ok(u) => out.push(u),
Err(_) => {
if let Ok(u) = parse_short_uuid(&s) {
out.push(u);
}
}
}
}
out
}
}
/// Null → `-100` (treated as far-away, not drop-worthy).
unsafe fn nsnumber_to_i16(n: *mut AnyObject) -> i16 {
if n.is_null() {
return -100;
}
let v: i32 = unsafe { msg_send![&*n, intValue] };
v.clamp(i16::MIN as i32, i16::MAX as i32) as i16
}
unsafe fn nsstring_to_string(s: *mut AnyObject) -> String {
if s.is_null() {
return String::new();
}
unsafe {
let utf8: *const std::ffi::c_char = msg_send![&*s, UTF8String];
// 4 = NSUTF8StringEncoding
let len: usize = msg_send![&*s, lengthOfBytesUsingEncoding: 4usize];
if utf8.is_null() || len == 0 {
return String::new();
}
let bytes = std::slice::from_raw_parts(utf8 as *const u8, len);
String::from_utf8_lossy(bytes).into_owned()
}
}
fn cbuuid(uuid: &Uuid) -> *mut AnyObject {
let s = NSString::from_str(&uuid.to_string());
unsafe {
let cls = AnyClass::get("CBUUID").expect("CBUUID must exist at runtime");
let obj: *mut AnyObject = msg_send![cls, UUIDWithString: &*s];
// UUIDWithString: returns autoreleased; retain so the pointer
// survives the autorelease pool drain.
let _: *mut AnyObject = msg_send![obj, retain];
obj
}
}
/// Expand a SIG short UUID ("180D" / "0000180D") to its 128-bit form using
/// the Bluetooth base UUID.
fn parse_short_uuid(s: &str) -> Result<Uuid, ()> {
let hex = s.trim();
match hex.len() {
4 => {
let v = u16::from_str_radix(hex, 16).map_err(|_| ())?;
Uuid::parse_str(&format!("0000{v:04x}-0000-1000-8000-00805f9b34fb")).map_err(|_| ())
}
8 => {
let v = u32::from_str_radix(hex, 16).map_err(|_| ())?;
Uuid::parse_str(&format!("{v:08x}-0000-1000-8000-00805f9b34fb")).map_err(|_| ())
}
_ => Err(()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_short_uuid_expands_16bit_to_base_uuid() {
let u = parse_short_uuid("180D").expect("must parse");
assert_eq!(
u,
Uuid::parse_str("0000180d-0000-1000-8000-00805f9b34fb").unwrap()
);
}
#[test]
fn parse_short_uuid_expands_32bit_to_base_uuid() {
let u = parse_short_uuid("0000180D").expect("must parse");
assert_eq!(
u,
Uuid::parse_str("0000180d-0000-1000-8000-00805f9b34fb").unwrap()
);
}
#[test]
fn parse_short_uuid_is_case_insensitive() {
let u1 = parse_short_uuid("180d").unwrap();
let u2 = parse_short_uuid("180D").unwrap();
assert_eq!(u1, u2);
}
#[test]
fn parse_short_uuid_rejects_non_hex() {
assert!(parse_short_uuid("zzzz").is_err());
assert!(parse_short_uuid("").is_err());
assert!(parse_short_uuid("180").is_err());
assert!(parse_short_uuid("1800000D").is_ok());
}
#[test]
fn cb_state_name_covers_documented_states() {
assert_eq!(cb_state_name(0), "unknown");
assert_eq!(cb_state_name(1), "resetting");
assert_eq!(cb_state_name(2), "unsupported");
assert_eq!(cb_state_name(3), "unauthorized");
assert_eq!(cb_state_name(4), "poweredOff");
assert_eq!(cb_state_name(5), "poweredOn");
assert_eq!(cb_state_name(99), "?");
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,487 @@
//! BLE central (scan) lifecycle. `PlatformUnavailable` rewinds active states
//! to `StartingWaitingPlatform` so scanning resumes after a Bluetooth toggle.
use std::sync::{Mutex, MutexGuard, PoisonError};
use std::time::Instant;
use uuid::Uuid;
/// Which GATT service a peer advertises (adapter reports the primary it saw).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AdvertisedProtocol {
Ratspeak,
Columba,
}
/// `identifier` is platform-stable (Apple UUIDString, bluer D-Bus path, Android MAC).
#[derive(Debug, Clone)]
pub struct DiscoveryEvent {
pub identifier: String,
pub rssi: i16,
pub services: Vec<Uuid>,
pub protocol: AdvertisedProtocol,
pub seen_at: Instant,
}
/// Classify ad services. Ratspeak beats Columba when both advertised.
pub fn classify_protocol(
services: &[Uuid],
ratspeak_uuid: Uuid,
columba_uuid: Uuid,
) -> Option<AdvertisedProtocol> {
if services.contains(&ratspeak_uuid) {
Some(AdvertisedProtocol::Ratspeak)
} else if services.contains(&columba_uuid) {
Some(AdvertisedProtocol::Columba)
} else {
None
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CentralState {
Idle,
/// `start_scan` issued; awaiting `CBManagerState == PoweredOn` etc.
StartingWaitingPlatform,
Scanning,
/// `stop_scan` issued; awaiting platform ack (synthetic on Apple where
/// stopScan is synchronous, real on bluer).
StoppingScan,
/// Cleanly torn down. Distinct from `Idle` for telemetry.
Stopped,
/// Bluetooth unsupported / permission denied; requires explicit `Reset`.
Failed,
}
impl CentralState {
pub fn is_active(self) -> bool {
!matches!(self, Self::Idle | Self::Stopped | Self::Failed)
}
pub fn is_starting(self) -> bool {
matches!(self, Self::StartingWaitingPlatform)
}
pub fn is_scanning(self) -> bool {
matches!(self, Self::Scanning)
}
pub fn is_stopping(self) -> bool {
matches!(self, Self::StoppingScan)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CentralEvent {
StartRequested,
/// Platform ready: adapter calls `scanForPeripheralsWithServices` here.
PlatformReady,
/// Active states rewind to `StartingWaitingPlatform` so recovery
/// resumes scanning.
PlatformUnavailable {
reason: String,
},
StopRequested,
/// `stopScan` completed (synthetic on Apple where it's synchronous).
ScanStopped,
FatalError {
reason: String,
},
Reset,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CentralTransitionError {
pub from: CentralState,
pub event: CentralEvent,
}
impl std::fmt::Display for CentralTransitionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"invalid BLE central lifecycle transition: event {:?} is not valid from state {:?}",
self.event, self.from
)
}
}
impl std::error::Error for CentralTransitionError {}
/// Idempotent re-requests return `Ok` with state unchanged.
pub fn transition(
state: CentralState,
event: &CentralEvent,
) -> Result<CentralState, CentralTransitionError> {
use CentralEvent::*;
use CentralState::*;
if let FatalError { .. } = event {
return Ok(Failed);
}
let next = match (state, event) {
(Idle, StartRequested) => StartingWaitingPlatform,
(Stopped, StartRequested) => StartingWaitingPlatform,
(StartingWaitingPlatform, PlatformReady) => Scanning,
(Scanning, StopRequested) => StoppingScan,
(StartingWaitingPlatform, StopRequested) => Stopped,
(StoppingScan, ScanStopped) => Stopped,
(Stopped, Reset) => Idle,
(Scanning, PlatformUnavailable { .. }) => StartingWaitingPlatform,
(StartingWaitingPlatform, PlatformUnavailable { .. }) => StartingWaitingPlatform,
(Failed, Reset) => Idle,
(StartingWaitingPlatform | Scanning, StartRequested) => state,
(Idle | Stopped | StoppingScan, StopRequested) => state,
(Idle, Reset) => Idle,
_ => {
return Err(CentralTransitionError {
from: state,
event: event.clone(),
});
}
};
Ok(next)
}
pub struct CentralLifecycle {
state: Mutex<CentralState>,
}
impl CentralLifecycle {
pub fn new() -> Self {
Self {
state: Mutex::new(CentralState::Idle),
}
}
pub fn current(&self) -> CentralState {
*self.lock().expect("poisoned")
}
pub fn apply(&self, event: CentralEvent) -> Result<CentralState, CentralTransitionError> {
let mut guard = self.lock().expect("poisoned");
let next = transition(*guard, &event)?;
*guard = next;
Ok(next)
}
pub fn is_scanning(&self) -> bool {
matches!(self.current(), CentralState::Scanning)
}
fn lock(
&self,
) -> Result<MutexGuard<'_, CentralState>, PoisonError<MutexGuard<'_, CentralState>>> {
self.state.lock()
}
}
impl Default for CentralLifecycle {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for CentralLifecycle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CentralLifecycle")
.field("state", &self.current())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn unavail(reason: &str) -> CentralEvent {
CentralEvent::PlatformUnavailable {
reason: reason.into(),
}
}
fn fatal(reason: &str) -> CentralEvent {
CentralEvent::FatalError {
reason: reason.into(),
}
}
fn drive(start: CentralState, events: &[CentralEvent]) -> CentralState {
let lc = CentralLifecycle {
state: Mutex::new(start),
};
for e in events {
lc.apply(e.clone())
.unwrap_or_else(|err| panic!("transition failed: {err}"));
}
lc.current()
}
// ---- Happy-path transitions ----
#[test]
fn full_start_cycle_reaches_scanning() {
let final_state = drive(
CentralState::Idle,
&[CentralEvent::StartRequested, CentralEvent::PlatformReady],
);
assert_eq!(final_state, CentralState::Scanning);
}
#[test]
fn full_stop_cycle_reaches_stopped() {
let final_state = drive(
CentralState::Scanning,
&[CentralEvent::StopRequested, CentralEvent::ScanStopped],
);
assert_eq!(final_state, CentralState::Stopped);
}
#[test]
fn stopped_can_start_again() {
let final_state = drive(
CentralState::Stopped,
&[
CentralEvent::Reset,
CentralEvent::StartRequested,
CentralEvent::PlatformReady,
],
);
assert_eq!(final_state, CentralState::Scanning);
}
// ---- Teardown sequencing ----
#[test]
fn stop_request_alone_does_not_reach_stopped_from_scanning() {
// Apple's stopScan is synchronous, but the machine still requires
// an explicit ScanStopped for symmetry with async backends.
let lc = CentralLifecycle::new();
lc.apply(CentralEvent::StartRequested).unwrap();
lc.apply(CentralEvent::PlatformReady).unwrap();
assert_eq!(lc.current(), CentralState::Scanning);
lc.apply(CentralEvent::StopRequested).unwrap();
assert_eq!(lc.current(), CentralState::StoppingScan);
let err = lc.apply(CentralEvent::Reset);
assert!(err.is_err());
assert_eq!(lc.current(), CentralState::StoppingScan);
}
#[test]
fn stop_before_platform_ready_reaches_stopped_immediately() {
let final_state = drive(
CentralState::StartingWaitingPlatform,
&[CentralEvent::StopRequested],
);
assert_eq!(final_state, CentralState::Stopped);
}
// ---- Platform availability ----
#[test]
fn bluetooth_off_mid_scan_rewinds_to_waiting_platform() {
let final_state = drive(CentralState::Scanning, &[unavail("bluetooth off")]);
assert_eq!(final_state, CentralState::StartingWaitingPlatform);
}
#[test]
fn bluetooth_recovery_cycle_returns_to_scanning() {
let final_state = drive(
CentralState::Scanning,
&[unavail("bluetooth off"), CentralEvent::PlatformReady],
);
assert_eq!(final_state, CentralState::Scanning);
}
#[test]
fn double_unavailable_while_waiting_is_idempotent() {
let final_state = drive(
CentralState::StartingWaitingPlatform,
&[unavail("resetting"), unavail("resetting")],
);
assert_eq!(final_state, CentralState::StartingWaitingPlatform);
}
// ---- Idempotency ----
#[test]
fn double_start_from_scanning_is_noop() {
let lc = CentralLifecycle::new();
lc.apply(CentralEvent::StartRequested).unwrap();
lc.apply(CentralEvent::PlatformReady).unwrap();
lc.apply(CentralEvent::StartRequested).unwrap();
assert_eq!(lc.current(), CentralState::Scanning);
}
#[test]
fn double_stop_while_stopping_is_noop() {
let lc = CentralLifecycle::new();
lc.apply(CentralEvent::StartRequested).unwrap();
lc.apply(CentralEvent::PlatformReady).unwrap();
lc.apply(CentralEvent::StopRequested).unwrap();
assert_eq!(lc.current(), CentralState::StoppingScan);
lc.apply(CentralEvent::StopRequested).unwrap();
assert_eq!(lc.current(), CentralState::StoppingScan);
}
#[test]
fn reset_from_idle_is_noop() {
let lc = CentralLifecycle::new();
lc.apply(CentralEvent::Reset).unwrap();
assert_eq!(lc.current(), CentralState::Idle);
}
// ---- Fatal ----
#[test]
fn fatal_from_any_state_reaches_failed() {
for from in [
CentralState::Idle,
CentralState::StartingWaitingPlatform,
CentralState::Scanning,
CentralState::StoppingScan,
CentralState::Stopped,
] {
let final_state = drive(from, &[fatal("oom")]);
assert_eq!(final_state, CentralState::Failed, "from {from:?}");
}
}
#[test]
fn failed_requires_reset_to_restart() {
let lc = CentralLifecycle {
state: Mutex::new(CentralState::Failed),
};
let err = lc
.apply(CentralEvent::StartRequested)
.expect_err("StartRequested from Failed must be rejected");
assert_eq!(err.from, CentralState::Failed);
}
#[test]
fn reset_from_failed_returns_to_idle() {
let final_state = drive(CentralState::Failed, &[CentralEvent::Reset]);
assert_eq!(final_state, CentralState::Idle);
}
// ---- Invalid transitions ----
#[test]
fn platform_ready_from_idle_is_rejected() {
let lc = CentralLifecycle::new();
let err = lc
.apply(CentralEvent::PlatformReady)
.expect_err("PlatformReady from Idle must be rejected");
assert_eq!(err.from, CentralState::Idle);
assert_eq!(lc.current(), CentralState::Idle);
}
#[test]
fn scan_stopped_from_idle_is_rejected() {
let lc = CentralLifecycle::new();
assert!(lc.apply(CentralEvent::ScanStopped).is_err());
}
#[test]
fn predicates_match_intuition() {
assert!(!CentralState::Idle.is_active());
assert!(CentralState::Scanning.is_active());
assert!(CentralState::Scanning.is_scanning());
assert!(CentralState::StartingWaitingPlatform.is_starting());
assert!(CentralState::StoppingScan.is_stopping());
let lc = CentralLifecycle::new();
assert!(!lc.is_scanning());
lc.apply(CentralEvent::StartRequested).unwrap();
lc.apply(CentralEvent::PlatformReady).unwrap();
assert!(lc.is_scanning());
}
// ---- End-to-end scenarios for the iOS / macOS adapter ----
#[test]
fn full_enable_disable_enable_cycle_ends_idle_ready_to_scan() {
let lc = CentralLifecycle::new();
lc.apply(CentralEvent::StartRequested).unwrap();
lc.apply(CentralEvent::PlatformReady).unwrap();
assert_eq!(lc.current(), CentralState::Scanning);
lc.apply(CentralEvent::StopRequested).unwrap();
lc.apply(CentralEvent::ScanStopped).unwrap();
lc.apply(CentralEvent::Reset).unwrap();
lc.apply(CentralEvent::StartRequested).unwrap();
lc.apply(CentralEvent::PlatformReady).unwrap();
assert_eq!(lc.current(), CentralState::Scanning);
}
// ---- Protocol classification ----
fn ratspeak_uuid() -> Uuid {
Uuid::from_u128(0xa1b2c3d4_e5f6_4a5b_8c9d_0e1f2a3b4c5d)
}
fn columba_uuid() -> Uuid {
Uuid::from_u128(0x37145b00_442d_4a94_917f_8f42c5da28e3)
}
fn unrelated_uuid() -> Uuid {
Uuid::from_u128(0xdead_dead_dead_dead_dead_dead_dead_dead)
}
#[test]
fn classify_picks_ratspeak_over_columba_when_both_advertised() {
let services = vec![ratspeak_uuid(), columba_uuid()];
let got = classify_protocol(&services, ratspeak_uuid(), columba_uuid());
assert_eq!(got, Some(AdvertisedProtocol::Ratspeak));
}
#[test]
fn classify_returns_ratspeak_when_only_ratspeak_present() {
let services = vec![ratspeak_uuid()];
let got = classify_protocol(&services, ratspeak_uuid(), columba_uuid());
assert_eq!(got, Some(AdvertisedProtocol::Ratspeak));
}
#[test]
fn classify_returns_columba_when_only_columba_present() {
let services = vec![columba_uuid()];
let got = classify_protocol(&services, ratspeak_uuid(), columba_uuid());
assert_eq!(got, Some(AdvertisedProtocol::Columba));
}
#[test]
fn classify_returns_none_when_neither_present() {
let services = vec![unrelated_uuid()];
let got = classify_protocol(&services, ratspeak_uuid(), columba_uuid());
assert_eq!(got, None);
}
#[test]
fn classify_returns_none_on_empty_ad() {
let got = classify_protocol(&[], ratspeak_uuid(), columba_uuid());
assert_eq!(got, None);
}
#[test]
fn classify_ignores_unrelated_services_mixed_in() {
let services = vec![unrelated_uuid(), columba_uuid(), unrelated_uuid()];
let got = classify_protocol(&services, ratspeak_uuid(), columba_uuid());
assert_eq!(got, Some(AdvertisedProtocol::Columba));
}
#[test]
fn platform_unavailable_during_scan_rewinds_and_recovers_automatically() {
let lc = CentralLifecycle::new();
lc.apply(CentralEvent::StartRequested).unwrap();
lc.apply(CentralEvent::PlatformReady).unwrap();
lc.apply(unavail("bluetooth off")).unwrap();
assert_eq!(lc.current(), CentralState::StartingWaitingPlatform);
lc.apply(unavail("resetting")).unwrap();
assert_eq!(lc.current(), CentralState::StartingWaitingPlatform);
lc.apply(CentralEvent::PlatformReady).unwrap();
assert_eq!(lc.current(), CentralState::Scanning);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,675 @@
//! BLE peripheral lifecycle state machine. Platform adapters (Apple
//! `CBPeripheralManager`, Linux `bluer`, Android `BluetoothGattServer`,
//! Windows `GattServiceProvider`) drive it via [`PeripheralLifecycle::apply`].
//!
//! Two invariants this encodes that are easy to violate by hand:
//!
//! 1. **Teardown waits for platform confirmation.** iOS has no
//! `peripheralManagerDidStopAdvertising:` callback; the only reliable
//! "stopped" signal is polling `CBPeripheralManager.isAdvertising` until
//! `NO`. Calling `removeAllServices` while still advertising leaves
//! CoreBluetooth in a dirty state that breaks subsequent enables.
//!
//! 2. **Mid-session platform transitions rewind.** A `Resetting` →
//! `PoweredOff` → `PoweredOn` cycle (user toggling Bluetooth, OS stack
//! crash recovery) must drop back to `StartingWaitingPlatform` so the
//! next `PlatformReady` re-registers.
//!
//! Invalid transitions return an error; adapters log and continue rather
//! than panic — BLE backends occasionally deliver out-of-order or redundant
//! callbacks.
use std::sync::{Mutex, MutexGuard, PoisonError};
/// Sub-states for `Starting` and `Stopping` are explicit so each can reject
/// events that don't belong to its phase.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PeripheralState {
Idle,
/// Awaiting `CBManagerState == PoweredOn` / `bluer` `Adapter.powered`.
StartingWaitingPlatform,
/// Registering GATT services; awaiting per-service add confirmation.
StartingRegisteringServices,
/// `startAdvertising` issued; awaiting platform confirmation.
StartingAdvertising,
Advertising,
/// `stopAdvertising` issued; awaiting confirmation. iOS lacks a delegate
/// callback for this — the adapter polls `isAdvertising`.
StoppingAdvertisement,
/// `removeAllServices` issued; awaiting confirmation.
StoppingRemovingServices,
/// Cleanly torn down. Distinct from `Idle` for telemetry.
Stopped,
/// Unrecoverable. Requires explicit [`LifecycleEvent::Reset`].
Failed,
}
impl PeripheralState {
/// True when the peripheral holds platform resources needing release on teardown.
pub fn is_active(self) -> bool {
!matches!(self, Self::Idle | Self::Stopped | Self::Failed)
}
pub fn is_starting(self) -> bool {
matches!(
self,
Self::StartingWaitingPlatform
| Self::StartingRegisteringServices
| Self::StartingAdvertising
)
}
pub fn is_stopping(self) -> bool {
matches!(
self,
Self::StoppingAdvertisement | Self::StoppingRemovingServices
)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LifecycleEvent {
StartRequested,
/// Platform ready for service registration + advertising.
PlatformReady,
/// Platform blocked (BT off, permission denied, adapter resetting).
/// Rewinds active states to `StartingWaitingPlatform` to preserve user
/// intent across recovery.
PlatformUnavailable {
reason: String,
},
ServicesAdded,
AdvertiseStarted,
StopRequested,
/// `stopAdvertising` completed. On iOS this comes from polling
/// `isAdvertising` since no delegate callback exists. Skipping this and
/// going straight to `removeAllServices` was the root cause of the
/// "disable doesn't fully tear down" bug.
AdvertiseStopped,
ServicesRemoved,
FatalError {
reason: String,
},
Reset,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransitionError {
pub from: PeripheralState,
pub event: LifecycleEvent,
}
impl std::fmt::Display for TransitionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"invalid BLE peripheral lifecycle transition: event {:?} is not valid from state {:?}",
self.event, self.from
)
}
}
impl std::error::Error for TransitionError {}
/// Caller performs the side-effect (calling `stopAdvertising` etc.) on the
/// returned next state. Idempotent re-requests return `Ok` with state
/// unchanged; genuine violations return [`TransitionError`].
pub fn transition(
state: PeripheralState,
event: &LifecycleEvent,
) -> Result<PeripheralState, TransitionError> {
use LifecycleEvent::*;
use PeripheralState::*;
if let FatalError { .. } = event {
return Ok(Failed);
}
let next = match (state, event) {
// ---- Start path ----
(Idle, StartRequested) => StartingWaitingPlatform,
(Stopped, StartRequested) => StartingWaitingPlatform,
(StartingWaitingPlatform, PlatformReady) => StartingRegisteringServices,
(StartingRegisteringServices, ServicesAdded) => StartingAdvertising,
(StartingAdvertising, AdvertiseStarted) => Advertising,
// ---- Stop path ----
(Advertising, StopRequested) => StoppingAdvertisement,
// Stop while starting: skip ahead to the appropriate Stopping
// sub-state so the in-flight platform calls unwind cleanly.
(StartingAdvertising, StopRequested) => StoppingAdvertisement,
(StartingRegisteringServices, StopRequested) => StoppingRemovingServices,
(StartingWaitingPlatform, StopRequested) => Stopped, // nothing registered yet
(StoppingAdvertisement, AdvertiseStopped) => StoppingRemovingServices,
(StoppingRemovingServices, ServicesRemoved) => Stopped,
(Stopped, Reset) => Idle,
// Platform-unavailable from any active state rewinds to
// WaitingPlatform so the next PlatformReady resumes automatically.
(Advertising, PlatformUnavailable { .. }) => StartingWaitingPlatform,
(StartingAdvertising, PlatformUnavailable { .. }) => StartingWaitingPlatform,
(StartingRegisteringServices, PlatformUnavailable { .. }) => StartingWaitingPlatform,
(StartingWaitingPlatform, PlatformUnavailable { .. }) => StartingWaitingPlatform,
(Failed, Reset) => Idle,
// ---- Idempotent no-ops ----
(
StartingWaitingPlatform
| StartingRegisteringServices
| StartingAdvertising
| Advertising,
StartRequested,
) => state,
(Idle | Stopped | StoppingAdvertisement | StoppingRemovingServices, StopRequested) => state,
(Idle, Reset) => Idle,
_ => {
return Err(TransitionError {
from: state,
event: event.clone(),
});
}
};
Ok(next)
}
/// Mutex is held only across the transition itself; side-effects run after
/// `apply` returns.
pub struct PeripheralLifecycle {
state: Mutex<PeripheralState>,
}
impl PeripheralLifecycle {
pub fn new() -> Self {
Self {
state: Mutex::new(PeripheralState::Idle),
}
}
pub fn current(&self) -> PeripheralState {
*self.lock().expect("poisoned")
}
pub fn apply(&self, event: LifecycleEvent) -> Result<PeripheralState, TransitionError> {
let mut guard = self.lock().expect("poisoned");
let next = transition(*guard, &event)?;
*guard = next;
Ok(next)
}
pub fn is_advertising(&self) -> bool {
matches!(self.current(), PeripheralState::Advertising)
}
fn lock(
&self,
) -> Result<MutexGuard<'_, PeripheralState>, PoisonError<MutexGuard<'_, PeripheralState>>> {
self.state.lock()
}
}
impl Default for PeripheralLifecycle {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for PeripheralLifecycle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PeripheralLifecycle")
.field("state", &self.current())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn err(reason: &str) -> LifecycleEvent {
LifecycleEvent::PlatformUnavailable {
reason: reason.into(),
}
}
fn fatal(reason: &str) -> LifecycleEvent {
LifecycleEvent::FatalError {
reason: reason.into(),
}
}
fn drive(start: PeripheralState, events: &[LifecycleEvent]) -> PeripheralState {
let lc = PeripheralLifecycle {
state: Mutex::new(start),
};
for e in events {
lc.apply(e.clone())
.unwrap_or_else(|err| panic!("transition failed: {err}"));
}
lc.current()
}
// ---- Happy-path transitions ----
#[test]
fn full_start_cycle_reaches_advertising() {
let final_state = drive(
PeripheralState::Idle,
&[
LifecycleEvent::StartRequested,
LifecycleEvent::PlatformReady,
LifecycleEvent::ServicesAdded,
LifecycleEvent::AdvertiseStarted,
],
);
assert_eq!(final_state, PeripheralState::Advertising);
}
#[test]
fn full_stop_cycle_reaches_stopped() {
let final_state = drive(
PeripheralState::Advertising,
&[
LifecycleEvent::StopRequested,
LifecycleEvent::AdvertiseStopped,
LifecycleEvent::ServicesRemoved,
],
);
assert_eq!(final_state, PeripheralState::Stopped);
}
#[test]
fn stopped_can_start_again() {
let final_state = drive(
PeripheralState::Stopped,
&[
LifecycleEvent::Reset,
LifecycleEvent::StartRequested,
LifecycleEvent::PlatformReady,
LifecycleEvent::ServicesAdded,
LifecycleEvent::AdvertiseStarted,
],
);
assert_eq!(final_state, PeripheralState::Advertising);
}
// ---- Teardown requires confirmation (the bug we are fixing) ----
#[test]
fn stop_request_alone_does_not_reach_stopped() {
// Calling `stopAdvertising` without waiting for confirmation left
// CoreBluetooth dirty in the previous implementation. The machine
// must NOT allow StoppingAdvertisement → Stopped without
// AdvertiseStopped first.
let lc = PeripheralLifecycle::new();
lc.apply(LifecycleEvent::StartRequested).unwrap();
lc.apply(LifecycleEvent::PlatformReady).unwrap();
lc.apply(LifecycleEvent::ServicesAdded).unwrap();
lc.apply(LifecycleEvent::AdvertiseStarted).unwrap();
lc.apply(LifecycleEvent::StopRequested).unwrap();
assert_eq!(lc.current(), PeripheralState::StoppingAdvertisement);
// Jumping straight to ServicesRemoved is invalid — we have not yet
// seen AdvertiseStopped.
let err = lc
.apply(LifecycleEvent::ServicesRemoved)
.expect_err("ServicesRemoved should be rejected in StoppingAdvertisement");
assert_eq!(err.from, PeripheralState::StoppingAdvertisement);
assert_eq!(lc.current(), PeripheralState::StoppingAdvertisement);
}
#[test]
fn advertise_stopped_then_services_removed_reaches_stopped() {
let final_state = drive(
PeripheralState::StoppingAdvertisement,
&[
LifecycleEvent::AdvertiseStopped,
LifecycleEvent::ServicesRemoved,
],
);
assert_eq!(final_state, PeripheralState::Stopped);
}
// ---- Platform availability transitions ----
#[test]
fn bluetooth_off_mid_advertising_rewinds_to_waiting_platform() {
let final_state = drive(PeripheralState::Advertising, &[err("bluetooth off")]);
assert_eq!(final_state, PeripheralState::StartingWaitingPlatform);
}
#[test]
fn bluetooth_recovery_cycle_returns_to_advertising() {
let final_state = drive(
PeripheralState::Advertising,
&[
err("bluetooth off"),
LifecycleEvent::PlatformReady,
LifecycleEvent::ServicesAdded,
LifecycleEvent::AdvertiseStarted,
],
);
assert_eq!(final_state, PeripheralState::Advertising);
}
#[test]
fn platform_unavailable_while_waiting_platform_is_idempotent() {
// iOS sometimes emits Resetting twice before PoweredOn.
let final_state = drive(
PeripheralState::StartingWaitingPlatform,
&[err("resetting"), err("resetting")],
);
assert_eq!(final_state, PeripheralState::StartingWaitingPlatform);
}
// ---- Stop while starting ----
#[test]
fn stop_before_platform_ready_reaches_stopped_immediately() {
// Nothing registered yet, nothing to tear down.
let final_state = drive(
PeripheralState::StartingWaitingPlatform,
&[LifecycleEvent::StopRequested],
);
assert_eq!(final_state, PeripheralState::Stopped);
}
#[test]
fn stop_mid_service_registration_skips_to_removing_services() {
// Services need removing but there's no advertising to stop yet.
let final_state = drive(
PeripheralState::StartingRegisteringServices,
&[LifecycleEvent::StopRequested],
);
assert_eq!(final_state, PeripheralState::StoppingRemovingServices);
}
#[test]
fn stop_mid_advertise_enters_stopping_advertisement() {
let final_state = drive(
PeripheralState::StartingAdvertising,
&[LifecycleEvent::StopRequested],
);
assert_eq!(final_state, PeripheralState::StoppingAdvertisement);
}
// ---- Idempotent events ----
#[test]
fn double_start_is_noop() {
let lc = PeripheralLifecycle::new();
lc.apply(LifecycleEvent::StartRequested).unwrap();
lc.apply(LifecycleEvent::PlatformReady).unwrap();
lc.apply(LifecycleEvent::ServicesAdded).unwrap();
lc.apply(LifecycleEvent::AdvertiseStarted).unwrap();
assert_eq!(lc.current(), PeripheralState::Advertising);
lc.apply(LifecycleEvent::StartRequested).unwrap();
assert_eq!(lc.current(), PeripheralState::Advertising);
}
#[test]
fn double_stop_is_noop() {
let lc = PeripheralLifecycle::new();
lc.apply(LifecycleEvent::StopRequested).unwrap();
assert_eq!(lc.current(), PeripheralState::Idle);
lc.apply(LifecycleEvent::StopRequested).unwrap();
assert_eq!(lc.current(), PeripheralState::Idle);
}
#[test]
fn reset_from_idle_is_noop() {
let lc = PeripheralLifecycle::new();
lc.apply(LifecycleEvent::Reset).unwrap();
assert_eq!(lc.current(), PeripheralState::Idle);
}
// ---- Fatal and recovery ----
#[test]
fn fatal_error_from_any_state_reaches_failed() {
for from in [
PeripheralState::Idle,
PeripheralState::StartingWaitingPlatform,
PeripheralState::StartingRegisteringServices,
PeripheralState::StartingAdvertising,
PeripheralState::Advertising,
PeripheralState::StoppingAdvertisement,
PeripheralState::StoppingRemovingServices,
PeripheralState::Stopped,
] {
let final_state = drive(from, &[fatal("oom")]);
assert_eq!(final_state, PeripheralState::Failed, "from {from:?}");
}
}
#[test]
fn reset_from_failed_returns_to_idle() {
let final_state = drive(PeripheralState::Failed, &[LifecycleEvent::Reset]);
assert_eq!(final_state, PeripheralState::Idle);
}
#[test]
fn failed_requires_reset_to_restart() {
let lc = PeripheralLifecycle {
state: Mutex::new(PeripheralState::Failed),
};
let err = lc
.apply(LifecycleEvent::StartRequested)
.expect_err("StartRequested from Failed should be rejected");
assert_eq!(err.from, PeripheralState::Failed);
}
// ---- Invalid transitions ----
#[test]
fn advertise_started_from_idle_is_rejected() {
let lc = PeripheralLifecycle::new();
let err = lc
.apply(LifecycleEvent::AdvertiseStarted)
.expect_err("AdvertiseStarted from Idle should be rejected");
assert_eq!(err.from, PeripheralState::Idle);
assert_eq!(lc.current(), PeripheralState::Idle);
}
#[test]
fn services_added_from_advertising_is_rejected() {
let lc = PeripheralLifecycle {
state: Mutex::new(PeripheralState::Advertising),
};
let err = lc
.apply(LifecycleEvent::ServicesAdded)
.expect_err("ServicesAdded from Advertising should be rejected");
assert_eq!(err.from, PeripheralState::Advertising);
assert_eq!(lc.current(), PeripheralState::Advertising);
}
#[test]
fn advertise_stopped_from_idle_is_rejected() {
let lc = PeripheralLifecycle::new();
assert!(lc.apply(LifecycleEvent::AdvertiseStopped).is_err());
}
#[test]
fn is_active_matches_intuition() {
assert!(!PeripheralState::Idle.is_active());
assert!(!PeripheralState::Stopped.is_active());
assert!(!PeripheralState::Failed.is_active());
assert!(PeripheralState::StartingWaitingPlatform.is_active());
assert!(PeripheralState::StartingRegisteringServices.is_active());
assert!(PeripheralState::StartingAdvertising.is_active());
assert!(PeripheralState::Advertising.is_active());
assert!(PeripheralState::StoppingAdvertisement.is_active());
assert!(PeripheralState::StoppingRemovingServices.is_active());
}
#[test]
fn is_starting_covers_all_starting_substates() {
assert!(PeripheralState::StartingWaitingPlatform.is_starting());
assert!(PeripheralState::StartingRegisteringServices.is_starting());
assert!(PeripheralState::StartingAdvertising.is_starting());
assert!(!PeripheralState::Advertising.is_starting());
assert!(!PeripheralState::StoppingAdvertisement.is_starting());
}
#[test]
fn is_stopping_covers_all_stopping_substates() {
assert!(PeripheralState::StoppingAdvertisement.is_stopping());
assert!(PeripheralState::StoppingRemovingServices.is_stopping());
assert!(!PeripheralState::Advertising.is_stopping());
assert!(!PeripheralState::StartingAdvertising.is_stopping());
}
#[test]
fn is_advertising_helper_matches_current() {
let lc = PeripheralLifecycle::new();
assert!(!lc.is_advertising());
lc.apply(LifecycleEvent::StartRequested).unwrap();
lc.apply(LifecycleEvent::PlatformReady).unwrap();
lc.apply(LifecycleEvent::ServicesAdded).unwrap();
assert!(!lc.is_advertising());
lc.apply(LifecycleEvent::AdvertiseStarted).unwrap();
assert!(lc.is_advertising());
}
// ---- End-to-end scenarios exercised by the iOS / macOS adapter ----
//
// Locks in the toggle paths that are hard to hit reliably on a dev
// machine (e.g. "disable fires before PoweredOn lands" races).
#[test]
fn full_enable_disable_enable_cycle_ends_idle_ready_to_advertise() {
let lc = PeripheralLifecycle::new();
lc.apply(LifecycleEvent::StartRequested).unwrap();
lc.apply(LifecycleEvent::PlatformReady).unwrap();
lc.apply(LifecycleEvent::ServicesAdded).unwrap();
lc.apply(LifecycleEvent::AdvertiseStarted).unwrap();
assert_eq!(lc.current(), PeripheralState::Advertising);
lc.apply(LifecycleEvent::StopRequested).unwrap();
lc.apply(LifecycleEvent::AdvertiseStopped).unwrap();
lc.apply(LifecycleEvent::ServicesRemoved).unwrap();
lc.apply(LifecycleEvent::Reset).unwrap();
assert_eq!(lc.current(), PeripheralState::Idle);
lc.apply(LifecycleEvent::StartRequested).unwrap();
lc.apply(LifecycleEvent::PlatformReady).unwrap();
lc.apply(LifecycleEvent::ServicesAdded).unwrap();
lc.apply(LifecycleEvent::AdvertiseStarted).unwrap();
assert_eq!(lc.current(), PeripheralState::Advertising);
}
#[test]
fn quick_toggle_disable_before_platform_ready_ends_idle() {
// User mashed Enable/Disable while CBManagerState was still Unknown.
let lc = PeripheralLifecycle::new();
lc.apply(LifecycleEvent::StartRequested).unwrap();
lc.apply(LifecycleEvent::StopRequested).unwrap();
assert_eq!(lc.current(), PeripheralState::Stopped);
lc.apply(LifecycleEvent::Reset).unwrap();
assert_eq!(lc.current(), PeripheralState::Idle);
}
#[test]
fn stop_mid_service_registration_requires_services_removed_not_advertise_stopped() {
// No advertising has started yet — the adapter must skip
// `stopAdvertising` and go straight to `removeAllServices`.
let lc = PeripheralLifecycle::new();
lc.apply(LifecycleEvent::StartRequested).unwrap();
lc.apply(LifecycleEvent::PlatformReady).unwrap();
// Stop in the middle of registering, before either
// `peripheralManagerDidAddService:error:` callback lands.
lc.apply(LifecycleEvent::StopRequested).unwrap();
assert_eq!(lc.current(), PeripheralState::StoppingRemovingServices);
// `AdvertiseStopped` is nonsense here — reject it.
let err = lc
.apply(LifecycleEvent::AdvertiseStopped)
.expect_err("AdvertiseStopped from StoppingRemovingServices should be rejected");
assert_eq!(err.from, PeripheralState::StoppingRemovingServices);
// `ServicesRemoved` is the correct continuation.
lc.apply(LifecycleEvent::ServicesRemoved).unwrap();
lc.apply(LifecycleEvent::Reset).unwrap();
assert_eq!(lc.current(), PeripheralState::Idle);
}
#[test]
fn redundant_services_added_after_advertise_start_is_ignored_not_fatal() {
// Late `ServicesAdded` after AdvertiseStarted (radio bounce) must
// be rejected without poisoning the machine — state unchanged.
let lc = PeripheralLifecycle::new();
lc.apply(LifecycleEvent::StartRequested).unwrap();
lc.apply(LifecycleEvent::PlatformReady).unwrap();
lc.apply(LifecycleEvent::ServicesAdded).unwrap();
lc.apply(LifecycleEvent::AdvertiseStarted).unwrap();
let err = lc.apply(LifecycleEvent::ServicesAdded);
assert!(err.is_err());
assert_eq!(lc.current(), PeripheralState::Advertising);
}
#[test]
fn platform_unavailable_during_advertising_rewinds_and_recovers_automatically() {
let lc = PeripheralLifecycle::new();
lc.apply(LifecycleEvent::StartRequested).unwrap();
lc.apply(LifecycleEvent::PlatformReady).unwrap();
lc.apply(LifecycleEvent::ServicesAdded).unwrap();
lc.apply(LifecycleEvent::AdvertiseStarted).unwrap();
assert_eq!(lc.current(), PeripheralState::Advertising);
lc.apply(LifecycleEvent::PlatformUnavailable {
reason: "bluetooth off".into(),
})
.unwrap();
assert_eq!(lc.current(), PeripheralState::StartingWaitingPlatform);
// iOS sometimes emits Resetting twice — idempotent.
lc.apply(LifecycleEvent::PlatformUnavailable {
reason: "resetting".into(),
})
.unwrap();
assert_eq!(lc.current(), PeripheralState::StartingWaitingPlatform);
lc.apply(LifecycleEvent::PlatformReady).unwrap();
lc.apply(LifecycleEvent::ServicesAdded).unwrap();
lc.apply(LifecycleEvent::AdvertiseStarted).unwrap();
assert_eq!(lc.current(), PeripheralState::Advertising);
}
#[test]
fn stop_after_advertise_error_starts_from_waiting_platform_returns_to_idle() {
// `peripheralManagerDidStartAdvertising:error:` with a non-nil error
// surfaces as `PlatformUnavailable`; a stop from that rewound state
// must still tear down cleanly.
let lc = PeripheralLifecycle::new();
lc.apply(LifecycleEvent::StartRequested).unwrap();
lc.apply(LifecycleEvent::PlatformReady).unwrap();
lc.apply(LifecycleEvent::ServicesAdded).unwrap();
lc.apply(LifecycleEvent::PlatformUnavailable {
reason: "advertising failed".into(),
})
.unwrap();
assert_eq!(lc.current(), PeripheralState::StartingWaitingPlatform);
lc.apply(LifecycleEvent::StopRequested).unwrap();
assert_eq!(lc.current(), PeripheralState::Stopped);
lc.apply(LifecycleEvent::Reset).unwrap();
assert_eq!(lc.current(), PeripheralState::Idle);
}
#[test]
fn concurrent_stop_requests_are_idempotent() {
// BLE Mesh disable and app shutdown can race; a second
// StopRequested from any Stopping* state must be a no-op.
let lc = PeripheralLifecycle::new();
lc.apply(LifecycleEvent::StartRequested).unwrap();
lc.apply(LifecycleEvent::PlatformReady).unwrap();
lc.apply(LifecycleEvent::ServicesAdded).unwrap();
lc.apply(LifecycleEvent::AdvertiseStarted).unwrap();
lc.apply(LifecycleEvent::StopRequested).unwrap();
assert_eq!(lc.current(), PeripheralState::StoppingAdvertisement);
lc.apply(LifecycleEvent::StopRequested).unwrap();
assert_eq!(lc.current(), PeripheralState::StoppingAdvertisement);
lc.apply(LifecycleEvent::AdvertiseStopped).unwrap();
lc.apply(LifecycleEvent::ServicesRemoved).unwrap();
assert_eq!(lc.current(), PeripheralState::Stopped);
}
}
File diff suppressed because it is too large. Load diff
+298
View File
@@ -0,0 +1,298 @@
//! HDLC-like framing shared by TCP, Serial, I2P, Local, Pipe, Backbone.
//! Wire: `[FLAG][escaped_payload][FLAG]`. Encode ESC before FLAG; decode FLAG before ESC.
/// HDLC frame delimiter.
pub const FLAG: u8 = 0x7E;
/// HDLC escape byte.
pub const ESC: u8 = 0x7D;
/// XOR mask applied to escaped bytes.
pub const ESC_MASK: u8 = 0x20;
/// Upper bound on a single HDLC frame (sized for full resource transfers on TCP/Local MTUs).
const MAX_FRAME_SIZE: usize = 524288;
/// Pre-allocated capacity for the deframer accumulator. Covers typical HW_MTUs
/// with headroom; larger frames grow the Vec normally.
const DEFRAME_BUF_CAPACITY: usize = 2048;
/// Append the escape-encoded form of `data` to `out`. No allocation if `out` has capacity.
pub fn escape_into(data: &[u8], out: &mut Vec<u8>) {
let mut i = 0;
while i < data.len() {
match data[i..].iter().position(|&b| b == ESC || b == FLAG) {
Some(rel) => {
let hit = i + rel;
out.extend_from_slice(&data[i..hit]);
out.push(ESC);
out.push(data[hit] ^ ESC_MASK);
i = hit + 1;
}
None => {
out.extend_from_slice(&data[i..]);
return;
}
}
}
}
/// Append the unescaped form of `data` to `out`. Unknown escape sequences and a
/// trailing lone ESC byte are passed through unchanged — matching the previous
/// implementation so any consumer relying on length/CRC rejection still sees
/// the same bytes.
pub fn unescape_into(data: &[u8], out: &mut Vec<u8>) {
let mut i = 0;
while i < data.len() {
match data[i..].iter().position(|&b| b == ESC) {
Some(rel) => {
let hit = i + rel;
out.extend_from_slice(&data[i..hit]);
if hit + 1 < data.len() {
let next = data[hit + 1];
if next == (FLAG ^ ESC_MASK) {
out.push(FLAG);
} else if next == (ESC ^ ESC_MASK) {
out.push(ESC);
} else {
out.push(ESC);
out.push(next);
}
i = hit + 2;
} else {
out.push(ESC);
return;
}
}
None => {
out.extend_from_slice(&data[i..]);
return;
}
}
}
}
/// Append a complete HDLC frame for `data` to `out`.
pub fn frame_into(data: &[u8], out: &mut Vec<u8>) {
out.push(FLAG);
escape_into(data, out);
out.push(FLAG);
}
pub fn escape(data: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(data.len() + data.len() / 8);
escape_into(data, &mut out);
out
}
pub fn unescape(data: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(data.len());
unescape_into(data, &mut out);
out
}
pub fn frame(data: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(data.len() + data.len() / 8 + 2);
frame_into(data, &mut out);
out
}
pub struct HdlcDeframer {
buffer: Vec<u8>,
in_frame: bool,
/// Reusable scratch for unescape output to avoid per-frame allocation.
unescape_scratch: Vec<u8>,
}
impl HdlcDeframer {
pub fn new() -> Self {
Self {
buffer: Vec::with_capacity(DEFRAME_BUF_CAPACITY),
in_frame: false,
unescape_scratch: Vec::with_capacity(DEFRAME_BUF_CAPACITY),
}
}
pub fn feed(&mut self, data: &[u8]) -> Vec<Vec<u8>> {
let mut frames = Vec::new();
let mut i = 0;
while i < data.len() {
match data[i..].iter().position(|&b| b == FLAG) {
Some(rel) => {
let hit = i + rel;
if self.in_frame {
self.append_in_frame(&data[i..hit]);
if !self.buffer.is_empty() {
self.unescape_scratch.clear();
unescape_into(&self.buffer, &mut self.unescape_scratch);
if !self.unescape_scratch.is_empty() {
frames.push(std::mem::take(&mut self.unescape_scratch));
// Restore capacity for the next frame.
self.unescape_scratch = Vec::with_capacity(DEFRAME_BUF_CAPACITY);
}
}
self.buffer.clear();
}
self.in_frame = true;
i = hit + 1;
}
None => {
if self.in_frame {
self.append_in_frame(&data[i..]);
}
return frames;
}
}
}
frames
}
/// Append `chunk` to `self.buffer` while enforcing `MAX_FRAME_SIZE`. On
/// overflow the in-progress frame is dropped and we wait for the next FLAG
/// to resync — matching the previous byte-loop behavior.
fn append_in_frame(&mut self, chunk: &[u8]) {
if self.buffer.len() + chunk.len() > MAX_FRAME_SIZE {
self.buffer.clear();
self.in_frame = false;
return;
}
self.buffer.extend_from_slice(chunk);
}
pub fn reset(&mut self) {
self.buffer.clear();
self.in_frame = false;
}
}
impl Default for HdlcDeframer {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_escape_unescape_roundtrip() {
let data = vec![0x00, FLAG, ESC, 0xFF, FLAG, ESC, 0x42];
let escaped = escape(&data);
let unescaped = unescape(&escaped);
assert_eq!(unescaped, data);
}
#[test]
fn test_escape_no_special_bytes() {
let data = b"hello world";
let escaped = escape(data);
assert_eq!(escaped, data);
}
#[test]
fn test_escape_flag_byte() {
let data = vec![FLAG];
let escaped = escape(&data);
assert_eq!(escaped, vec![ESC, FLAG ^ ESC_MASK]);
}
#[test]
fn test_escape_esc_byte() {
let data = vec![ESC];
let escaped = escape(&data);
assert_eq!(escaped, vec![ESC, ESC ^ ESC_MASK]);
}
#[test]
fn test_frame_and_deframe() {
let data = b"test packet data";
let framed = frame(data);
let mut deframer = HdlcDeframer::new();
let frames = deframer.feed(&framed);
assert_eq!(frames.len(), 1);
assert_eq!(frames[0], data);
}
#[test]
fn test_deframer_multiple_frames() {
let f1 = frame(b"first");
let f2 = frame(b"second");
let mut combined = f1;
combined.extend_from_slice(&f2);
let mut deframer = HdlcDeframer::new();
let frames = deframer.feed(&combined);
assert_eq!(frames.len(), 2);
assert_eq!(frames[0], b"first");
assert_eq!(frames[1], b"second");
}
#[test]
fn test_deframer_streaming() {
let framed = frame(b"streamed");
let mut deframer = HdlcDeframer::new();
let mid = framed.len() / 2;
let frames1 = deframer.feed(&framed[..mid]);
assert!(frames1.is_empty());
let frames2 = deframer.feed(&framed[mid..]);
assert_eq!(frames2.len(), 1);
assert_eq!(frames2[0], b"streamed");
}
#[test]
fn test_tricky_sequence() {
// ESC, FLAG^MASK must decode to a single FLAG byte.
let data = vec![ESC, 0x5E];
let unescaped = unescape(&data);
assert_eq!(unescaped, vec![FLAG]);
}
#[test]
fn test_into_variants_match_allocating() {
// The allocating wrappers must produce byte-identical output.
let inputs: &[&[u8]] = &[
b"",
b"plain",
&[FLAG, ESC, 0x00, 0xFF, FLAG],
&[ESC, ESC, ESC],
&[0x00; 1024],
];
for data in inputs {
let mut buf = Vec::new();
escape_into(data, &mut buf);
assert_eq!(buf, escape(data));
let escaped = escape(data);
let mut buf2 = Vec::new();
unescape_into(&escaped, &mut buf2);
assert_eq!(buf2, unescape(&escaped));
let mut buf3 = Vec::new();
frame_into(data, &mut buf3);
assert_eq!(buf3, frame(data));
}
}
#[test]
fn test_deframer_oversized_drops_then_resyncs() {
// A frame body larger than MAX_FRAME_SIZE must drop and resync on the
// next FLAG, exactly like the per-byte implementation.
let mut deframer = HdlcDeframer::new();
let mut oversized = vec![FLAG];
oversized.extend(std::iter::repeat_n(0x55, MAX_FRAME_SIZE + 100));
oversized.push(FLAG);
let frames = deframer.feed(&oversized);
assert!(frames.is_empty());
let small = frame(b"after-overflow");
let frames = deframer.feed(&small);
assert_eq!(frames.len(), 1);
assert_eq!(frames[0], b"after-overflow");
}
}
File diff suppressed because it is too large. Load diff
+483
View File
@@ -0,0 +1,483 @@
//! KISS TNC framing — used by KISS, AX.25-KISS, RNode, RNodeMulti, TCP/I2P.
//! Wire: `[FEND][CMD][escaped_payload][FEND]`.
pub const FEND: u8 = 0xC0;
pub const FESC: u8 = 0xDB;
pub const TFEND: u8 = 0xDC;
pub const TFESC: u8 = 0xDD;
pub const CMD_DATA: u8 = 0x00;
pub const CMD_TXDELAY: u8 = 0x01;
pub const CMD_P: u8 = 0x02;
pub const CMD_SLOTTIME: u8 = 0x03;
pub const CMD_TXTAIL: u8 = 0x04;
pub const CMD_FULLDUPLEX: u8 = 0x05;
pub const CMD_SETHARDWARE: u8 = 0x06;
pub const CMD_READY: u8 = 0x0F;
pub const CMD_RETURN: u8 = 0xFF;
pub const CMD_UNKNOWN: u8 = 0xFE;
/// High nibble of command byte = TNC port.
pub const PORT_MASK: u8 = 0xF0;
/// Low nibble of command byte = command.
pub const CMD_MASK: u8 = 0x0F;
/// Sized for full resource transfers on TCP/Local MTUs.
const MAX_FRAME_SIZE: usize = 524288;
/// Pre-allocated capacity for the deframer accumulator.
const DEFRAME_BUF_CAPACITY: usize = 2048;
/// Append the KISS-escape-encoded form of `data` to `out`.
pub fn escape_into(data: &[u8], out: &mut Vec<u8>) {
let mut i = 0;
while i < data.len() {
match data[i..].iter().position(|&b| b == FESC || b == FEND) {
Some(rel) => {
let hit = i + rel;
out.extend_from_slice(&data[i..hit]);
out.push(FESC);
out.push(if data[hit] == FEND { TFEND } else { TFESC });
i = hit + 1;
}
None => {
out.extend_from_slice(&data[i..]);
return;
}
}
}
}
/// Append the unescaped form of `data` to `out`. Unknown escape sequences and
/// a trailing lone FESC byte are passed through unchanged — matching the
/// previous implementation byte-for-byte.
pub fn unescape_into(data: &[u8], out: &mut Vec<u8>) {
let mut i = 0;
while i < data.len() {
match data[i..].iter().position(|&b| b == FESC) {
Some(rel) => {
let hit = i + rel;
out.extend_from_slice(&data[i..hit]);
if hit + 1 < data.len() {
match data[hit + 1] {
TFEND => out.push(FEND),
TFESC => out.push(FESC),
other => {
out.push(FESC);
out.push(other);
}
}
i = hit + 2;
} else {
out.push(FESC);
return;
}
}
None => {
out.extend_from_slice(&data[i..]);
return;
}
}
}
}
/// Append a complete KISS data-frame for `data` to `out`.
pub fn frame_into(data: &[u8], out: &mut Vec<u8>) {
out.push(FEND);
out.push(CMD_DATA);
escape_into(data, out);
out.push(FEND);
}
/// Append a KISS frame with an explicit command byte to `out`.
pub fn frame_with_command_into(cmd: u8, data: &[u8], out: &mut Vec<u8>) {
out.push(FEND);
out.push(cmd);
escape_into(data, out);
out.push(FEND);
}
pub fn escape(data: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(data.len() + data.len() / 8);
escape_into(data, &mut out);
out
}
pub fn unescape(data: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(data.len());
unescape_into(data, &mut out);
out
}
pub fn frame(data: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(data.len() + data.len() / 8 + 3);
frame_into(data, &mut out);
out
}
pub fn frame_with_command(cmd: u8, data: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(data.len() + data.len() / 8 + 3);
frame_with_command_into(cmd, data, &mut out);
out
}
pub struct KissDeframer {
buffer: Vec<u8>,
in_frame: bool,
command: u8,
/// Reusable scratch for unescape output.
unescape_scratch: Vec<u8>,
}
impl KissDeframer {
pub fn new() -> Self {
Self {
buffer: Vec::with_capacity(DEFRAME_BUF_CAPACITY),
in_frame: false,
command: CMD_UNKNOWN,
unescape_scratch: Vec::with_capacity(DEFRAME_BUF_CAPACITY),
}
}
/// Returns complete frames as (command, data) pairs.
pub fn feed(&mut self, data: &[u8]) -> Vec<(u8, Vec<u8>)> {
let mut frames = Vec::new();
let mut i = 0;
while i < data.len() {
match data[i..].iter().position(|&b| b == FEND) {
Some(rel) => {
let hit = i + rel;
if self.in_frame {
self.append_in_frame(&data[i..hit]);
if !self.buffer.is_empty() {
self.unescape_scratch.clear();
unescape_into(&self.buffer, &mut self.unescape_scratch);
let frame_data = std::mem::replace(
&mut self.unescape_scratch,
Vec::with_capacity(DEFRAME_BUF_CAPACITY),
);
frames.push((self.command & CMD_MASK, frame_data));
}
self.buffer.clear();
}
self.in_frame = true;
self.command = CMD_UNKNOWN;
i = hit + 1;
}
None => {
if self.in_frame {
self.append_in_frame(&data[i..]);
}
return frames;
}
}
}
frames
}
/// Append `chunk` to the in-frame buffer. The first byte after a FEND is
/// the command byte (consumed separately); subsequent bytes are payload
/// up to `MAX_FRAME_SIZE`. Overflow drops the in-progress frame and waits
/// for the next FEND to resync — matching the previous byte-loop.
fn append_in_frame(&mut self, chunk: &[u8]) {
let mut chunk = chunk;
if self.command == CMD_UNKNOWN {
if let Some((&first, rest)) = chunk.split_first() {
self.command = first;
chunk = rest;
} else {
return;
}
}
if self.buffer.len() + chunk.len() > MAX_FRAME_SIZE {
self.buffer.clear();
self.in_frame = false;
self.command = CMD_UNKNOWN;
return;
}
self.buffer.extend_from_slice(chunk);
}
pub fn reset(&mut self) {
self.buffer.clear();
self.in_frame = false;
self.command = CMD_UNKNOWN;
}
}
impl Default for KissDeframer {
fn default() -> Self {
Self::new()
}
}
/// Extended-KISS deframer that preserves the full command byte.
///
/// Classic KISS uses the high nibble as a TNC port and the low nibble as the
/// command, so [`KissDeframer`] returns `command & CMD_MASK`. RNode admin
/// commands use the complete byte (`0x50`, `0x62`, `0x84`, ...), so they must
/// use this deframer instead.
pub struct RawKissDeframer {
buffer: Vec<u8>,
in_frame: bool,
command: u8,
unescape_scratch: Vec<u8>,
}
impl RawKissDeframer {
pub fn new() -> Self {
Self {
buffer: Vec::with_capacity(DEFRAME_BUF_CAPACITY),
in_frame: false,
command: CMD_UNKNOWN,
unescape_scratch: Vec::with_capacity(DEFRAME_BUF_CAPACITY),
}
}
/// Returns complete frames as (full_command, data) pairs.
pub fn feed(&mut self, data: &[u8]) -> Vec<(u8, Vec<u8>)> {
let mut frames = Vec::new();
let mut i = 0;
while i < data.len() {
match data[i..].iter().position(|&b| b == FEND) {
Some(rel) => {
let hit = i + rel;
if self.in_frame {
self.append_in_frame(&data[i..hit]);
if !self.buffer.is_empty() {
self.unescape_scratch.clear();
unescape_into(&self.buffer, &mut self.unescape_scratch);
let frame_data = std::mem::replace(
&mut self.unescape_scratch,
Vec::with_capacity(DEFRAME_BUF_CAPACITY),
);
frames.push((self.command, frame_data));
}
self.buffer.clear();
}
self.in_frame = true;
self.command = CMD_UNKNOWN;
i = hit + 1;
}
None => {
if self.in_frame {
self.append_in_frame(&data[i..]);
}
return frames;
}
}
}
frames
}
fn append_in_frame(&mut self, chunk: &[u8]) {
let mut chunk = chunk;
if self.command == CMD_UNKNOWN {
if let Some((&first, rest)) = chunk.split_first() {
self.command = first;
chunk = rest;
} else {
return;
}
}
if self.buffer.len() + chunk.len() > MAX_FRAME_SIZE {
self.buffer.clear();
self.in_frame = false;
self.command = CMD_UNKNOWN;
return;
}
self.buffer.extend_from_slice(chunk);
}
pub fn reset(&mut self) {
self.buffer.clear();
self.in_frame = false;
self.command = CMD_UNKNOWN;
}
}
impl Default for RawKissDeframer {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_escape_unescape_roundtrip() {
let data = vec![0x00, FEND, FESC, 0xFF, FEND, FESC, 0x42];
let escaped = escape(&data);
let unescaped = unescape(&escaped);
assert_eq!(unescaped, data);
}
#[test]
fn test_escape_no_special_bytes() {
let data = b"hello";
let escaped = escape(data);
assert_eq!(escaped, data);
}
#[test]
fn test_escape_fend() {
let data = vec![FEND];
let escaped = escape(&data);
assert_eq!(escaped, vec![FESC, TFEND]);
}
#[test]
fn test_escape_fesc() {
let data = vec![FESC];
let escaped = escape(&data);
assert_eq!(escaped, vec![FESC, TFESC]);
}
#[test]
fn test_frame_and_deframe() {
let data = b"test kiss data";
let framed = frame(data);
let mut deframer = KissDeframer::new();
let frames = deframer.feed(&framed);
assert_eq!(frames.len(), 1);
assert_eq!(frames[0].0, CMD_DATA);
assert_eq!(frames[0].1, data);
}
#[test]
fn test_deframer_multiple_frames() {
let f1 = frame(b"first");
let f2 = frame(b"second");
let mut combined = f1;
combined.extend_from_slice(&f2);
let mut deframer = KissDeframer::new();
let frames = deframer.feed(&combined);
assert_eq!(frames.len(), 2);
assert_eq!(frames[0].1, b"first");
assert_eq!(frames[1].1, b"second");
}
#[test]
fn test_port_nibble_stripped() {
// High nibble = TNC port, must be masked.
let mut framed = Vec::new();
framed.push(FEND);
framed.push(0x10 | CMD_DATA);
framed.extend_from_slice(b"data");
framed.push(FEND);
let mut deframer = KissDeframer::new();
let frames = deframer.feed(&framed);
assert_eq!(frames.len(), 1);
assert_eq!(frames[0].0, CMD_DATA);
}
#[test]
fn test_raw_deframer_preserves_extended_commands() {
let mut deframer = RawKissDeframer::new();
let mut bytes = Vec::new();
frame_with_command_into(0x50, &[0x00], &mut bytes);
frame_with_command_into(0x62, &[0x00, 0x01, 0xE2, 0x40], &mut bytes);
frame_with_command_into(0x84, &[192, 168, 1, 10], &mut bytes);
let frames = deframer.feed(&bytes);
assert_eq!(frames.len(), 3);
assert_eq!(frames[0].0, 0x50);
assert_eq!(frames[1].0, 0x62);
assert_eq!(frames[1].1, vec![0x00, 0x01, 0xE2, 0x40]);
assert_eq!(frames[2].0, 0x84);
}
#[test]
fn test_deframer_streaming() {
let framed = frame(b"stream");
let mid = framed.len() / 2;
let mut deframer = KissDeframer::new();
let f1 = deframer.feed(&framed[..mid]);
assert!(f1.is_empty());
let f2 = deframer.feed(&framed[mid..]);
assert_eq!(f2.len(), 1);
assert_eq!(f2[0].1, b"stream");
}
#[test]
fn test_frame_with_command() {
let data = b"hardware config";
let framed = frame_with_command(CMD_SETHARDWARE, data);
let mut deframer = KissDeframer::new();
let frames = deframer.feed(&framed);
assert_eq!(frames.len(), 1);
assert_eq!(frames[0].0, CMD_SETHARDWARE);
assert_eq!(frames[0].1, data);
}
#[test]
fn test_into_variants_match_allocating() {
let inputs: &[&[u8]] = &[
b"",
b"plain",
&[FEND, FESC, 0x00, 0xFF, FEND],
&[FESC, FESC, FESC],
&[0x00; 1024],
];
for data in inputs {
let mut buf = Vec::new();
escape_into(data, &mut buf);
assert_eq!(buf, escape(data));
let escaped = escape(data);
let mut buf2 = Vec::new();
unescape_into(&escaped, &mut buf2);
assert_eq!(buf2, unescape(&escaped));
let mut buf3 = Vec::new();
frame_into(data, &mut buf3);
assert_eq!(buf3, frame(data));
let mut buf4 = Vec::new();
frame_with_command_into(CMD_SETHARDWARE, data, &mut buf4);
assert_eq!(buf4, frame_with_command(CMD_SETHARDWARE, data));
}
}
#[test]
fn test_deframer_streaming_command_byte_boundary() {
// Command byte arrives in a separate feed() chunk from the payload.
let framed = frame(b"split");
let mut deframer = KissDeframer::new();
// Feed just [FEND] first — no command byte yet.
let f1 = deframer.feed(&framed[..1]);
assert!(f1.is_empty());
// Feed just the command byte — still no full frame.
let f2 = deframer.feed(&framed[1..2]);
assert!(f2.is_empty());
// Feed the payload + closing FEND.
let f3 = deframer.feed(&framed[2..]);
assert_eq!(f3.len(), 1);
assert_eq!(f3[0].0, CMD_DATA);
assert_eq!(f3[0].1, b"split");
}
#[test]
fn test_deframer_oversized_drops_then_resyncs() {
let mut deframer = KissDeframer::new();
let mut oversized = vec![FEND, CMD_DATA];
oversized.extend(std::iter::repeat_n(0x55, MAX_FRAME_SIZE + 100));
oversized.push(FEND);
let frames = deframer.feed(&oversized);
assert!(frames.is_empty());
let small = frame(b"after-overflow");
let frames = deframer.feed(&small);
assert_eq!(frames.len(), 1);
assert_eq!(frames[0].1, b"after-overflow");
}
}
+292
View File
@@ -0,0 +1,292 @@
//! Serial port + KISS framing; CMD_DATA + CMD_READY flow control.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;
use bytes::Bytes;
use tokio::sync::mpsc;
use crate::kiss;
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
use rns_transport::messages::{InboundPacket, TransportMessage};
const KISS_READ_TIMEOUT_MS: u64 = 100;
#[derive(Debug, Clone)]
pub struct KissInterfaceConfig {
pub name: String,
pub port: String,
pub baud_rate: u32,
pub data_bits: serialport::DataBits,
pub parity: serialport::Parity,
pub stop_bits: serialport::StopBits,
pub mode: InterfaceMode,
pub slottime: Option<u8>,
pub persistence: Option<u8>,
pub txdelay: Option<u8>,
pub txtail: Option<u8>,
/// Honour CMD_READY from TNC.
pub flow_control: bool,
}
impl KissInterfaceConfig {
pub fn new(name: &str, port: &str, baud: u32) -> Self {
Self {
name: name.to_string(),
port: port.to_string(),
baud_rate: baud,
data_bits: serialport::DataBits::Eight,
parity: serialport::Parity::None,
stop_bits: serialport::StopBits::One,
mode: InterfaceMode::Full,
slottime: None,
persistence: None,
txdelay: None,
txtail: None,
flow_control: false,
}
}
}
pub async fn spawn_kiss_interface(
config: KissInterfaceConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let port = serialport::new(&config.port, config.baud_rate)
.data_bits(config.data_bits)
.parity(config.parity)
.stop_bits(config.stop_bits)
.timeout(Duration::from_millis(KISS_READ_TIMEOUT_MS))
.open()
.map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("kiss serial open: {}", e))
})?;
tracing::info!(
name = %config.name,
port = %config.port,
baud = config.baud_rate,
"KISS interface opened"
);
let online = Arc::new(AtomicBool::new(true));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let (tx, mut rx) = mpsc::channel::<Bytes>(256);
let name = config.name.clone();
let mode = config.mode;
let flow_control = config.flow_control;
let port_write = port
.try_clone()
.map_err(|e| crate::traits::InterfaceError::SendFailed(format!("kiss clone: {}", e)))?;
// Push TNC tuning before main loops so they take effect before first frame.
{
let mut init_port = port_write.try_clone().map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("kiss init clone: {}", e))
})?;
let mut init_frames = Vec::with_capacity(16);
if let Some(v) = config.txdelay {
kiss::frame_with_command_into(kiss::CMD_TXDELAY, &[v], &mut init_frames);
}
if let Some(v) = config.persistence {
kiss::frame_with_command_into(kiss::CMD_P, &[v], &mut init_frames);
}
if let Some(v) = config.slottime {
kiss::frame_with_command_into(kiss::CMD_SLOTTIME, &[v], &mut init_frames);
}
if let Some(v) = config.txtail {
kiss::frame_with_command_into(kiss::CMD_TXTAIL, &[v], &mut init_frames);
}
if !init_frames.is_empty() {
use std::io::Write;
let _ = init_port.write_all(&init_frames);
let _ = init_port.flush();
}
}
let ready = Arc::new(AtomicBool::new(true));
let online_w = online.clone();
let ready_w = ready.clone();
let txb_w = shared_txb.clone();
tokio::spawn(async move {
let mut port_w = port_write;
while let Some(data) = rx.recv().await {
txb_w.fetch_add(data.len() as u64, std::sync::atomic::Ordering::Relaxed);
// Flow control: bounded wait so a stuck TNC can't hang transmit.
if flow_control {
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
while !ready_w.load(Ordering::SeqCst) {
if tokio::time::Instant::now() >= deadline {
tracing::warn!("KISS flow control timeout, proceeding anyway");
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
if !online_w.load(Ordering::SeqCst) {
return;
}
}
}
let framed = kiss::frame(&data);
let online_ref = online_w.clone();
let result = tokio::task::spawn_blocking(move || {
use std::io::Write;
port_w.write_all(&framed)?;
port_w.flush()?;
Ok::<_, std::io::Error>(port_w)
})
.await;
match result {
Ok(Ok(p)) => {
port_w = p;
}
Ok(Err(e)) => {
tracing::warn!(error = %e, "KISS write error");
online_ref.store(false, Ordering::SeqCst);
break;
}
Err(e) => {
tracing::warn!(error = %e, "KISS write task panicked");
break;
}
}
}
});
let online_r = online.clone();
let ready_r = ready;
let rxb_r = shared_rxb.clone();
let read_task = tokio::spawn(async move {
let mut port_r = port;
let mut deframer = kiss::KissDeframer::new();
let mut buf = [0u8; 1024];
loop {
if !online_r.load(Ordering::SeqCst) {
break;
}
let result = tokio::task::spawn_blocking(move || {
use std::io::Read;
match port_r.read(&mut buf) {
Ok(n) => Ok((port_r, buf, n)),
Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok((port_r, buf, 0)),
Err(e) => Err((port_r, e)),
}
})
.await;
match result {
Ok(Ok((p, b, n))) => {
port_r = p;
buf = b;
if n > 0 {
rxb_r.fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed);
for (cmd, frame) in deframer.feed(&buf[..n]) {
match cmd {
kiss::CMD_DATA => {
if frame.is_empty() {
continue;
}
let msg = TransportMessage::Inbound(InboundPacket {
raw: Bytes::from(frame),
interface_id: id,
rssi: None,
snr: None,
q: None,
});
if transport_tx.send(msg).await.is_err() {
tracing::warn!(id, "transport channel closed");
online_r.store(false, Ordering::SeqCst);
return;
}
}
kiss::CMD_READY => {
// Nonzero = TNC ready to accept data.
let is_ready = frame.first().copied().unwrap_or(0) != 0;
ready_r.store(is_ready, Ordering::SeqCst);
tracing::debug!(id, ready = is_ready, "KISS flow control");
}
_ => {
tracing::debug!(id, cmd, "ignoring KISS command");
}
}
}
}
}
Ok(Err((_p, e))) => {
tracing::warn!(error = %e, "KISS read error");
online_r.store(false, Ordering::SeqCst);
return;
}
Err(e) => {
tracing::warn!(error = %e, "KISS read task panicked");
online_r.store(false, Ordering::SeqCst);
return;
}
}
}
});
Ok(InterfaceHandle {
id,
name,
mode,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: config.baud_rate as u64,
mtu: 564,
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
tx,
read_task,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_kiss_iface_config() {
let cfg = KissInterfaceConfig::new("kiss0", "/dev/ttyUSB0", 9600);
assert_eq!(cfg.baud_rate, 9600);
assert!(!cfg.flow_control);
assert_eq!(cfg.mode, InterfaceMode::Full);
}
#[test]
fn test_kiss_config_defaults() {
let cfg = KissInterfaceConfig::new("kiss0", "/dev/ttyUSB0", 9600);
assert_eq!(cfg.name, "kiss0");
assert_eq!(cfg.port, "/dev/ttyUSB0");
assert_eq!(cfg.data_bits, serialport::DataBits::Eight);
assert_eq!(cfg.parity, serialport::Parity::None);
assert_eq!(cfg.stop_bits, serialport::StopBits::One);
assert!(cfg.slottime.is_none());
assert!(cfg.persistence.is_none());
assert!(cfg.txdelay.is_none());
assert!(cfg.txtail.is_none());
}
#[test]
fn test_kiss_config_custom() {
let cfg = KissInterfaceConfig::new("kiss1", "/dev/ttyACM0", 57600);
assert_eq!(cfg.port, "/dev/ttyACM0");
assert_eq!(cfg.baud_rate, 57600);
}
#[test]
fn test_kiss_config_mode() {
let cfg = KissInterfaceConfig::new("kiss0", "/dev/ttyS0", 9600);
assert_eq!(cfg.mode, InterfaceMode::Full);
}
}
+39
View File
@@ -0,0 +1,39 @@
//! Network interface implementations for Reticulum.
//! Each module provides a spawn function returning a Tokio task driving a
//! concrete transport; [`traits::Interface`] is the common abstraction.
#[cfg(target_os = "android")]
pub mod android_usb;
pub mod auto;
pub mod ax25kiss;
pub mod backbone;
#[cfg(all(feature = "ble", any(target_os = "ios", target_os = "macos")))]
pub mod ble_central_apple;
#[cfg(all(feature = "ble", any(target_os = "ios", target_os = "macos")))]
pub mod ble_central_apple_connect;
#[cfg(feature = "ble")]
pub mod ble_central_lifecycle;
#[cfg(feature = "ble")]
pub mod ble_peer;
#[cfg(feature = "ble")]
pub mod ble_peer_lifecycle;
#[cfg(feature = "ble")]
pub mod ble_rnode;
pub mod hdlc;
pub mod i2p;
pub mod kiss;
#[cfg(feature = "serial")]
pub mod kiss_iface;
pub mod local;
pub mod pipe;
pub mod rnode;
pub mod rnode_admin;
#[cfg(feature = "serial")]
pub mod rnode_multi;
#[cfg(feature = "serial")]
pub mod serial;
pub mod socket_tuning;
pub mod tcp;
pub mod traits;
pub mod udp;
pub mod weave;
+749
View File
@@ -0,0 +1,749 @@
//! Shared-instance IPC. Unix domain sockets where available, TCP on
//! 127.0.0.1 as fallback. HDLC-framed.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use bytes::Bytes;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::mpsc;
use crate::hdlc;
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
use rns_transport::messages::{InboundPacket, TransportMessage};
pub const LOCAL_MTU: u32 = 262_144;
/// Default filesystem socket path for non-Linux fallback use.
pub const DEFAULT_SOCKET_PATH: &str = "/tmp/rns_reticulum.sock";
/// On Android `/tmp` isn't writable; falls back to caller's data directory.
pub fn socket_path(data_dir: Option<&std::path::Path>) -> std::path::PathBuf {
if cfg!(target_os = "android")
&& let Some(dir) = data_dir
{
return dir.join("cache").join("rns_reticulum.sock");
}
std::path::PathBuf::from(DEFAULT_SOCKET_PATH)
}
pub const FALLBACK_TCP_PORT: u16 = 37428;
pub fn socket_path_for(instance_name: &str) -> String {
format!("/tmp/rns_{}.sock", instance_name)
}
pub fn python_shared_socket_name(instance_name: &str) -> String {
if cfg!(any(target_os = "linux", target_os = "android")) {
format!("\0rns/{instance_name}")
} else {
socket_path_for(instance_name)
}
}
#[cfg(unix)]
fn is_abstract_socket_path(path: &str) -> bool {
path.as_bytes().first() == Some(&0)
}
#[cfg(unix)]
fn display_socket_path(path: &str) -> String {
if is_abstract_socket_path(path) {
format!("\\0{}", &path[1..])
} else {
path.to_string()
}
}
#[derive(Debug, Clone)]
pub struct LocalServerConfig {
/// Unix socket path (ignored on non-Unix).
pub socket_path: String,
pub name: String,
}
impl Default for LocalServerConfig {
fn default() -> Self {
Self {
socket_path: DEFAULT_SOCKET_PATH.to_string(),
name: "LocalServer".to_string(),
}
}
}
#[derive(Debug, Clone)]
pub struct LocalClientConfig {
pub socket_path: String,
pub name: String,
}
impl Default for LocalClientConfig {
fn default() -> Self {
Self {
socket_path: DEFAULT_SOCKET_PATH.to_string(),
name: "LocalClient".to_string(),
}
}
}
async fn local_read_loop<R: AsyncReadExt + Unpin>(
mut reader: R,
interface_id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
online: Arc<AtomicBool>,
rxb: Arc<AtomicU64>,
) {
let mut buf = [0u8; 8192];
let mut deframer = hdlc::HdlcDeframer::new();
loop {
match reader.read(&mut buf).await {
Ok(0) => {
tracing::info!(interface_id, "local read: EOF");
break;
}
Ok(n) => {
rxb.fetch_add(n as u64, Ordering::Relaxed);
for frame in deframer.feed(&buf[..n]) {
if frame.is_empty() {
continue;
}
let msg = TransportMessage::Inbound(InboundPacket {
raw: Bytes::from(frame),
interface_id,
rssi: None,
snr: None,
q: None,
});
if transport_tx.send(msg).await.is_err() {
tracing::warn!(interface_id, "transport channel closed");
online.store(false, Ordering::SeqCst);
return;
}
}
}
Err(e) => {
tracing::warn!(interface_id, error = %e, "local read error");
break;
}
}
}
online.store(false, Ordering::SeqCst);
}
async fn local_write_loop<W: AsyncWriteExt + Unpin>(
mut writer: W,
mut rx: mpsc::Receiver<Bytes>,
online: Arc<AtomicBool>,
txb: Arc<AtomicU64>,
) {
while let Some(data) = rx.recv().await {
let framed = hdlc::frame(&data);
if let Err(e) = writer.write_all(&framed).await {
tracing::warn!(error = %e, "local write error");
break;
}
txb.fetch_add(framed.len() as u64, Ordering::Relaxed);
}
online.store(false, Ordering::SeqCst);
}
#[cfg(unix)]
mod platform {
use super::*;
use tokio::net::{UnixListener, UnixStream};
fn bind_unix_listener(socket_path: &str) -> std::io::Result<UnixListener> {
if let Some(abstract_name) = socket_path.strip_prefix('\0') {
return bind_abstract_unix_listener(abstract_name);
}
let _ = std::fs::remove_file(socket_path);
UnixListener::bind(socket_path)
}
async fn connect_unix_stream(socket_path: &str) -> std::io::Result<UnixStream> {
if let Some(abstract_name) = socket_path.strip_prefix('\0') {
return connect_abstract_unix_stream(abstract_name);
}
UnixStream::connect(socket_path).await
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn bind_abstract_unix_listener(name: &str) -> std::io::Result<UnixListener> {
use std::os::unix::net::{SocketAddr, UnixListener as StdUnixListener};
#[cfg(target_os = "android")]
use std::os::android::net::SocketAddrExt as _;
#[cfg(target_os = "linux")]
use std::os::linux::net::SocketAddrExt as _;
let addr = SocketAddr::from_abstract_name(name.as_bytes())?;
let listener = StdUnixListener::bind_addr(&addr)?;
listener.set_nonblocking(true)?;
UnixListener::from_std(listener)
}
#[cfg(not(any(target_os = "linux", target_os = "android")))]
fn bind_abstract_unix_listener(_name: &str) -> std::io::Result<UnixListener> {
Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"abstract Unix sockets are only available on Linux/Android",
))
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn connect_abstract_unix_stream(name: &str) -> std::io::Result<UnixStream> {
use std::os::unix::net::{SocketAddr, UnixStream as StdUnixStream};
#[cfg(target_os = "android")]
use std::os::android::net::SocketAddrExt as _;
#[cfg(target_os = "linux")]
use std::os::linux::net::SocketAddrExt as _;
let addr = SocketAddr::from_abstract_name(name.as_bytes())?;
let stream = StdUnixStream::connect_addr(&addr)?;
stream.set_nonblocking(true)?;
UnixStream::from_std(stream)
}
#[cfg(not(any(target_os = "linux", target_os = "android")))]
fn connect_abstract_unix_stream(_name: &str) -> std::io::Result<UnixStream> {
Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"abstract Unix sockets are only available on Linux/Android",
))
}
pub async fn spawn_local_server_impl(
config: LocalServerConfig,
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let listener = bind_unix_listener(&config.socket_path)?;
tracing::info!(name = %config.name, path = %display_socket_path(&config.socket_path), "local server listening");
let online = Arc::new(AtomicBool::new(true));
let online2 = online.clone();
let name = config.name.clone();
let (tx, _rx) = mpsc::channel::<Bytes>(1);
let read_task = tokio::spawn(async move {
loop {
match listener.accept().await {
Ok((stream, _addr)) => {
let client_id = id_gen.fetch_add(1, Ordering::SeqCst);
let client_name = format!("{}/client_{}", config.name, client_id);
tracing::info!(name = %client_name, "local client connected");
let c_online = Arc::new(AtomicBool::new(true));
let c_rxb = Arc::new(AtomicU64::new(0));
let c_txb = Arc::new(AtomicU64::new(0));
let (c_tx, c_rx) = mpsc::channel::<Bytes>(256);
let (reader, writer) = stream.into_split();
let c_online2 = c_online.clone();
let c_txb2 = c_txb.clone();
tokio::spawn(local_write_loop(writer, c_rx, c_online2, c_txb2));
let c_online3 = c_online.clone();
let c_rxb2 = c_rxb.clone();
let transport_tx2 = transport_tx.clone();
let dereg_tx = transport_tx.clone();
let cname = client_name.clone();
let read_handle = tokio::spawn(async move {
local_read_loop(reader, client_id, transport_tx2, c_online3, c_rxb2)
.await;
tracing::info!(name = %cname, "local client disconnected");
// Proactively notify so transport drops immediately.
let _ = dereg_tx
.send(TransportMessage::DeregisterInterface { id: client_id })
.await;
});
let handle = InterfaceHandle {
id: client_id,
name: client_name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online: c_online,
rxb: Some(c_rxb),
txb: Some(c_txb),
tx: c_tx,
read_task: read_handle,
};
if handle_tx.send(handle).await.is_err() {
tracing::warn!("local handle registry closed");
break;
}
}
Err(e) => {
tracing::warn!(error = %e, "local accept error");
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
}
online2.store(false, Ordering::SeqCst);
});
let server_rxb = Arc::new(AtomicU64::new(0));
let server_txb = Arc::new(AtomicU64::new(0));
Ok(InterfaceHandle {
id: 0,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
outbound: false,
forward: false,
repeat: false,
},
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online,
rxb: Some(server_rxb),
txb: Some(server_txb),
tx,
read_task,
})
}
pub async fn spawn_local_client_impl(
config: LocalClientConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let stream = connect_unix_stream(&config.socket_path).await?;
tracing::info!(name = %config.name, path = %display_socket_path(&config.socket_path), "local client connected");
let online = Arc::new(AtomicBool::new(true));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let (tx, rx) = mpsc::channel::<Bytes>(256);
let (reader, writer) = stream.into_split();
let online_w = online.clone();
let task_txb = shared_txb.clone();
tokio::spawn(local_write_loop(writer, rx, online_w, task_txb));
let online_r = online.clone();
let task_rxb = shared_rxb.clone();
let name = config.name.clone();
let read_task = tokio::spawn(async move {
local_read_loop(reader, id, transport_tx, online_r, task_rxb).await;
});
Ok(InterfaceHandle {
id,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
tx,
read_task,
})
}
}
#[cfg(not(unix))]
mod platform {
use super::*;
use tokio::net::{TcpListener, TcpStream};
fn fallback_tcp_addr(socket_path: &str) -> String {
if let Some(addr) = socket_path
.strip_prefix("tcp://")
.filter(|addr| !addr.is_empty())
{
addr.to_string()
} else {
format!("127.0.0.1:{FALLBACK_TCP_PORT}")
}
}
pub async fn spawn_local_server_impl(
config: LocalServerConfig,
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let addr = fallback_tcp_addr(&config.socket_path);
let listener = TcpListener::bind(&addr).await?;
let local_addr = listener.local_addr()?;
tracing::info!(name = %config.name, addr = %local_addr, "local server (TCP fallback) listening");
let online = Arc::new(AtomicBool::new(true));
let online2 = online.clone();
let name = config.name.clone();
let (tx, _rx) = mpsc::channel::<Bytes>(1);
let read_task = tokio::spawn(async move {
loop {
match listener.accept().await {
Ok((stream, peer)) => {
let client_id = id_gen.fetch_add(1, Ordering::SeqCst);
let client_name = format!("{}/client_{}", config.name, client_id);
tracing::info!(name = %client_name, peer = %peer, "local client connected (TCP)");
let c_online = Arc::new(AtomicBool::new(true));
let c_rxb = Arc::new(AtomicU64::new(0));
let c_txb = Arc::new(AtomicU64::new(0));
let (c_tx, c_rx) = mpsc::channel::<Bytes>(256);
let (reader, writer) = stream.into_split();
let c_online2 = c_online.clone();
let c_txb2 = c_txb.clone();
tokio::spawn(local_write_loop(writer, c_rx, c_online2, c_txb2));
let c_online3 = c_online.clone();
let c_rxb2 = c_rxb.clone();
let transport_tx2 = transport_tx.clone();
let dereg_tx = transport_tx.clone();
let cname = client_name.clone();
let read_handle = tokio::spawn(async move {
local_read_loop(reader, client_id, transport_tx2, c_online3, c_rxb2)
.await;
tracing::info!(name = %cname, "local client disconnected");
// See unix variant — notify proactively to avoid zombies.
let _ = dereg_tx
.send(TransportMessage::DeregisterInterface { id: client_id })
.await;
});
let handle = InterfaceHandle {
id: client_id,
name: client_name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online: c_online,
rxb: Some(c_rxb),
txb: Some(c_txb),
tx: c_tx,
read_task: read_handle,
};
if handle_tx.send(handle).await.is_err() {
tracing::warn!("local handle registry closed");
break;
}
}
Err(e) => {
tracing::warn!(error = %e, "local accept error");
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
}
online2.store(false, Ordering::SeqCst);
});
let server_rxb = Arc::new(AtomicU64::new(0));
let server_txb = Arc::new(AtomicU64::new(0));
Ok(InterfaceHandle {
id: 0,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
outbound: false,
forward: false,
repeat: false,
},
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online,
rxb: Some(server_rxb),
txb: Some(server_txb),
tx,
read_task,
})
}
pub async fn spawn_local_client_impl(
config: LocalClientConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let addr = fallback_tcp_addr(&config.socket_path);
let stream = TcpStream::connect(&addr).await?;
tracing::info!(name = %config.name, addr = %addr, "local client connected (TCP fallback)");
let online = Arc::new(AtomicBool::new(true));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let (tx, rx) = mpsc::channel::<Bytes>(256);
let (reader, writer) = stream.into_split();
let online_w = online.clone();
let task_txb = shared_txb.clone();
tokio::spawn(local_write_loop(writer, rx, online_w, task_txb));
let online_r = online.clone();
let task_rxb = shared_rxb.clone();
let name = config.name.clone();
let read_task = tokio::spawn(async move {
local_read_loop(reader, id, transport_tx, online_r, task_rxb).await;
});
Ok(InterfaceHandle {
id,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
tx,
read_task,
})
}
}
#[tracing::instrument(
level = "debug",
name = "local.server.accept",
skip_all,
fields(name = %config.name, socket_path = %config.socket_path),
)]
pub async fn spawn_local_server(
config: LocalServerConfig,
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
platform::spawn_local_server_impl(config, id_gen, transport_tx, handle_tx).await
}
#[tracing::instrument(
level = "debug",
name = "local.client.connect",
skip_all,
fields(name = %config.name, client_id = id, socket_path = %config.socket_path),
)]
pub async fn spawn_local_client(
config: LocalClientConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
platform::spawn_local_client_impl(config, id, transport_tx).await
}
#[cfg(test)]
mod tests {
use super::*;
fn unique_test_socket_path(prefix: &str) -> String {
#[cfg(unix)]
{
format!(
"/tmp/{prefix}_{}_{}.sock",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
)
}
#[cfg(not(unix))]
{
let listener =
std::net::TcpListener::bind("127.0.0.1:0").expect("reserve local test port");
let port = listener.local_addr().expect("read local test port").port();
drop(listener);
format!("tcp://127.0.0.1:{port}")
}
}
#[test]
fn test_local_mtu() {
assert_eq!(LOCAL_MTU, 262_144);
}
#[test]
fn test_local_server_config() {
let cfg = LocalServerConfig {
socket_path: "/tmp/test_rns.sock".to_string(),
name: "TestServer".to_string(),
};
assert_eq!(cfg.socket_path, "/tmp/test_rns.sock");
assert_eq!(cfg.name, "TestServer");
}
#[test]
fn test_local_client_config() {
let cfg = LocalClientConfig {
socket_path: "/tmp/test_rns.sock".to_string(),
name: "TestClient".to_string(),
};
assert_eq!(cfg.socket_path, "/tmp/test_rns.sock");
assert_eq!(cfg.name, "TestClient");
}
#[tokio::test]
async fn test_local_ipc_roundtrip() {
let (transport_tx, mut transport_rx) = mpsc::channel::<TransportMessage>(64);
let (handle_tx, mut handle_rx) = mpsc::channel::<InterfaceHandle>(8);
let id_gen = Arc::new(AtomicU64::new(500));
let socket_path = unique_test_socket_path("reticulum_test");
let server_cfg = LocalServerConfig {
socket_path: socket_path.clone(),
name: "test-local-server".to_string(),
};
let server_handle = spawn_local_server(server_cfg, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
let client_cfg = LocalClientConfig {
socket_path: socket_path.clone(),
name: "test-local-client".to_string(),
};
let client_handle = spawn_local_client(client_cfg, 42, transport_tx.clone())
.await
.unwrap();
let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for accepted handle")
.expect("handle channel closed");
let payload = Bytes::from_static(b"local ipc test");
client_handle.tx.send(payload.clone()).await.unwrap();
let msg = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv())
.await
.expect("timeout")
.expect("channel closed");
match msg {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, payload);
assert_eq!(pkt.interface_id, accepted.id);
}
other => panic!("unexpected: {:?}", other),
}
let reply = Bytes::from_static(b"local ipc reply");
accepted.tx.send(reply.clone()).await.unwrap();
let msg2 = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv())
.await
.expect("timeout")
.expect("channel closed");
match msg2 {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, reply);
assert_eq!(pkt.interface_id, 42);
}
other => panic!("unexpected: {:?}", other),
}
server_handle.read_task.abort();
client_handle.read_task.abort();
let _ = std::fs::remove_file(&socket_path);
}
/// Server-side read loop must DeregisterInterface on EOF (no zombie leak).
#[tokio::test]
async fn test_local_server_deregisters_on_client_disconnect() {
let (transport_tx, mut transport_rx) = mpsc::channel::<TransportMessage>(64);
let (handle_tx, mut handle_rx) = mpsc::channel::<InterfaceHandle>(8);
let id_gen = Arc::new(AtomicU64::new(700));
let socket_path = unique_test_socket_path("reticulum_dereg_test");
let _ = std::fs::remove_file(&socket_path);
let server_cfg = LocalServerConfig {
socket_path: socket_path.clone(),
name: "dereg-server".to_string(),
};
let server_handle = spawn_local_server(server_cfg, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
let client_cfg = LocalClientConfig {
socket_path: socket_path.clone(),
name: "dereg-client".to_string(),
};
let client_handle = spawn_local_client(client_cfg, 77, transport_tx.clone())
.await
.unwrap();
let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for accepted handle")
.expect("handle channel closed");
let server_side_client_id = accepted.id;
// Abort client; server's per-client read_loop sees EOF and exits.
client_handle.read_task.abort();
drop(client_handle.tx);
let mut saw_dereg = false;
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(3);
while tokio::time::Instant::now() < deadline {
match tokio::time::timeout(std::time::Duration::from_millis(500), transport_rx.recv())
.await
{
Ok(Some(TransportMessage::DeregisterInterface { id }))
if id == server_side_client_id =>
{
saw_dereg = true;
break;
}
Ok(Some(_)) => continue, // inbound frames etc.
Ok(None) => break,
Err(_) => continue,
}
}
assert!(
saw_dereg,
"server must emit DeregisterInterface for disconnected client id {server_side_client_id}"
);
server_handle.read_task.abort();
let _ = std::fs::remove_file(&socket_path);
}
}
+251
View File
@@ -0,0 +1,251 @@
//! HDLC-framed data over a subprocess's stdin/stdout; respawns on exit.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use bytes::Bytes;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::process::Command;
use tokio::sync::mpsc;
use crate::hdlc;
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
use rns_transport::messages::{InboundPacket, TransportMessage};
pub const BITRATE_GUESS: u64 = 1_000_000;
pub const HW_MTU: u32 = 1064;
pub const DEFAULT_RESPAWN_DELAY: f64 = 5.0;
#[derive(Debug, Clone)]
pub struct PipeInterfaceConfig {
pub name: String,
pub command: String,
/// Seconds before respawning after subprocess exit.
pub respawn_delay: f64,
pub mode: InterfaceMode,
}
impl PipeInterfaceConfig {
pub fn new(name: &str, command: &str) -> Self {
Self {
name: name.to_string(),
command: command.to_string(),
respawn_delay: DEFAULT_RESPAWN_DELAY,
mode: InterfaceMode::Full,
}
}
}
pub async fn spawn_pipe_interface(
config: PipeInterfaceConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let online = Arc::new(AtomicBool::new(true));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let (tx, rx) = mpsc::channel::<Bytes>(256);
let name = config.name.clone();
let mode = config.mode;
// Outbound rx must survive respawns; share across write loops.
let rx = Arc::new(tokio::sync::Mutex::new(rx));
let online_task = online.clone();
let rxb_task = shared_rxb.clone();
let txb_task = shared_txb.clone();
let read_task = tokio::spawn(async move {
loop {
if !online_task.load(Ordering::SeqCst) {
break;
}
let parts: Vec<&str> = config.command.split_whitespace().collect();
if parts.is_empty() {
tracing::error!("PipeInterface: empty command");
break;
}
let child = Command::new(parts[0])
.args(&parts[1..])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.spawn();
let mut child = match child {
Ok(c) => c,
Err(e) => {
tracing::warn!(error = %e, "PipeInterface: failed to spawn subprocess");
tokio::time::sleep(std::time::Duration::from_secs_f64(config.respawn_delay))
.await;
continue;
}
};
tracing::info!(name = %config.name, cmd = %config.command, "PipeInterface: subprocess spawned");
let mut stdout = match child.stdout.take() {
Some(s) => s,
None => {
tracing::error!("PipeInterface: no stdout from subprocess");
break;
}
};
let mut stdin = match child.stdin.take() {
Some(s) => s,
None => {
tracing::error!("PipeInterface: no stdin for subprocess");
break;
}
};
// Per-subprocess writer channel; outer rx forwards into conn_tx.
let (conn_tx, mut conn_rx) = mpsc::channel::<Bytes>(256);
let online_w = online_task.clone();
let txb_w = txb_task.clone();
let write_handle = tokio::spawn(async move {
while let Some(data) = conn_rx.recv().await {
if !online_w.load(Ordering::SeqCst) {
break;
}
let framed = hdlc::frame(&data);
txb_w.fetch_add(framed.len() as u64, Ordering::Relaxed);
if let Err(e) = stdin.write_all(&framed).await {
tracing::warn!(error = %e, "PipeInterface: write error");
break;
}
if let Err(e) = stdin.flush().await {
tracing::warn!(error = %e, "PipeInterface: flush error");
break;
}
}
});
let rx_ref = rx.clone();
let fwd_handle = tokio::spawn(async move {
let mut guard = rx_ref.lock().await;
while let Some(data) = guard.recv().await {
if conn_tx.send(data).await.is_err() {
break;
}
}
});
let mut deframer = hdlc::HdlcDeframer::new();
let mut buf = [0u8; 2048];
loop {
match stdout.read(&mut buf).await {
Ok(0) => {
tracing::info!("PipeInterface: subprocess stdout EOF");
break;
}
Ok(n) => {
rxb_task.fetch_add(n as u64, Ordering::Relaxed);
for frame in deframer.feed(&buf[..n]) {
if frame.is_empty() {
continue;
}
let msg = TransportMessage::Inbound(InboundPacket {
raw: Bytes::from(frame),
interface_id: id,
rssi: None,
snr: None,
q: None,
});
if transport_tx.send(msg).await.is_err() {
tracing::warn!(id, "transport channel closed");
online_task.store(false, Ordering::SeqCst);
return;
}
}
}
Err(e) => {
tracing::warn!(error = %e, "PipeInterface: read error");
break;
}
}
}
fwd_handle.abort();
let _ = fwd_handle.await;
write_handle.abort();
let _ = write_handle.await;
let _ = child.kill().await;
if !online_task.load(Ordering::SeqCst) {
break;
}
tracing::info!(
name = %config.name,
delay = config.respawn_delay,
"PipeInterface: respawning subprocess"
);
tokio::time::sleep(std::time::Duration::from_secs_f64(config.respawn_delay)).await;
}
});
Ok(InterfaceHandle {
id,
name,
mode,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: BITRATE_GUESS,
mtu: HW_MTU,
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
tx,
read_task,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pipe_config() {
let cfg = PipeInterfaceConfig::new("pipe0", "cat");
assert_eq!(cfg.command, "cat");
assert_eq!(cfg.respawn_delay, DEFAULT_RESPAWN_DELAY);
assert_eq!(cfg.mode, InterfaceMode::Full);
}
#[test]
fn test_constants() {
assert_eq!(BITRATE_GUESS, 1_000_000);
assert_eq!(HW_MTU, 1064);
}
#[test]
fn test_pipe_config_custom_command() {
let cfg = PipeInterfaceConfig::new("pipe1", "socat - TCP:10.0.0.1:4242");
assert_eq!(cfg.command, "socat - TCP:10.0.0.1:4242");
assert_eq!(cfg.name, "pipe1");
}
#[test]
fn test_pipe_config_respawn_delay() {
assert_eq!(DEFAULT_RESPAWN_DELAY, 5.0);
let mut cfg = PipeInterfaceConfig::new("pipe0", "cat");
assert_eq!(cfg.respawn_delay, 5.0);
cfg.respawn_delay = 10.0;
assert_eq!(cfg.respawn_delay, 10.0);
}
#[test]
fn test_pipe_config_mode() {
let mut cfg = PipeInterfaceConfig::new("pipe0", "cat");
assert_eq!(cfg.mode, InterfaceMode::Full);
cfg.mode = InterfaceMode::PointToPoint;
assert_eq!(cfg.mode, InterfaceMode::PointToPoint);
}
}
+641
View File
@@ -0,0 +1,641 @@
//! LoRa radio control via RNode firmware's extended-KISS protocol.
//! Shared constants + transport-agnostic response handler. Serial:
//! [`spawn_rnode_interface`] (feature `serial`); BLE: [`crate::ble_rnode`].
use bytes::Bytes;
use crate::kiss;
use crate::traits::{InterfaceId, InterfaceMode};
use rns_transport::messages::{InboundPacket, TransportMessage};
#[cfg(feature = "serial")]
use crate::traits::{InterfaceDirection, InterfaceHandle};
#[cfg(feature = "serial")]
use std::sync::Arc;
#[cfg(feature = "serial")]
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
#[cfg(feature = "serial")]
use std::time::Duration;
#[cfg(feature = "serial")]
use tokio::sync::mpsc;
pub const CMD_FREQUENCY: u8 = 0x01;
pub const CMD_BANDWIDTH: u8 = 0x02;
pub const CMD_TXPOWER: u8 = 0x03;
pub const CMD_SF: u8 = 0x04;
pub const CMD_CR: u8 = 0x05;
pub const CMD_RADIO_STATE: u8 = 0x06;
pub const CMD_RADIO_LOCK: u8 = 0x07;
pub const CMD_DETECT: u8 = 0x08;
pub const CMD_IMPLICIT: u8 = 0x09;
pub const CMD_LEAVE: u8 = 0x0A;
pub const CMD_PROMISC: u8 = 0x0E;
pub const CMD_READY: u8 = 0x0F;
pub const CMD_STAT_RX: u8 = 0x21;
pub const CMD_STAT_TX: u8 = 0x22;
pub const CMD_STAT_RSSI: u8 = 0x23;
pub const CMD_STAT_SNR: u8 = 0x24;
pub const CMD_STAT_CHTM: u8 = 0x25;
pub const CMD_STAT_PHYPRM: u8 = 0x26;
pub const CMD_STAT_BAT: u8 = 0x27;
pub const CMD_STAT_EDROP: u8 = 0x28;
pub const CMD_STAT_TEMP: u8 = 0x29;
pub const CMD_ERROR: u8 = 0x90;
pub const CMD_BLINK: u8 = 0x30;
pub const CMD_RANDOM: u8 = 0x40;
pub const CMD_FB_EXT: u8 = 0x41;
pub const CMD_FB_READ: u8 = 0x42;
pub const CMD_FB_WRITE: u8 = 0x43;
pub const CMD_BT_CTRL: u8 = 0x46;
pub const CMD_BOARD: u8 = 0x47;
pub const CMD_PLATFORM: u8 = 0x48;
pub const CMD_MCU: u8 = 0x49;
pub const CMD_FW_VERSION: u8 = 0x50;
pub const CMD_ROM_READ: u8 = 0x51;
pub const CMD_ROM_WRITE: u8 = 0x52;
pub const CMD_CONF_SAVE: u8 = 0x53;
pub const CMD_CONF_DELETE: u8 = 0x54;
pub const CMD_DEV_HASH: u8 = 0x56;
pub const CMD_DEV_SIG: u8 = 0x57;
pub const CMD_FW_HASH: u8 = 0x58;
pub const CMD_ROM_WIPE: u8 = 0x59;
pub const CMD_HASHES: u8 = 0x60;
pub const CMD_FW_UPD: u8 = 0x61;
pub const CMD_BT_PIN: u8 = 0x62;
pub const CMD_ST_ALOCK: u8 = 0x0B;
pub const CMD_LT_ALOCK: u8 = 0x0C;
pub const CMD_RESET: u8 = 0x55;
pub const CMD_DISP_INT: u8 = 0x45;
pub const CMD_DISP_ADR: u8 = 0x63;
pub const CMD_DISP_BLNK: u8 = 0x64;
pub const CMD_NP_INT: u8 = 0x65;
pub const CMD_DISP_ROT: u8 = 0x67;
pub const CMD_DISP_RCND: u8 = 0x68;
pub const CMD_DIS_IA: u8 = 0x69;
pub const CMD_WIFI_MODE: u8 = 0x6A;
pub const CMD_WIFI_SSID: u8 = 0x6B;
pub const CMD_WIFI_PSK: u8 = 0x6C;
pub const CMD_CFG_READ: u8 = 0x6D;
pub const CMD_WIFI_CHN: u8 = 0x6E;
pub const CMD_WIFI_IP: u8 = 0x84;
pub const CMD_WIFI_NM: u8 = 0x85;
pub const DETECT_REQ: u8 = 0x73;
pub const DETECT_RESP: u8 = 0x46;
pub const REQUIRED_FW_VER_MAJ: u8 = 1;
pub const REQUIRED_FW_VER_MIN: u8 = 52;
pub const RSSI_OFFSET: i32 = 157;
pub const RECONNECT_WAIT: u64 = 5;
pub const MAX_RECONNECT_TRIES: usize = 3;
pub const RADIO_STATE_ON: u8 = 0x01;
pub const RADIO_STATE_OFF: u8 = 0x00;
#[cfg(feature = "serial")]
const RNODE_READ_TIMEOUT_MS: u64 = 100;
#[derive(Debug, Clone)]
pub struct RNodeConfig {
pub name: String,
pub port: String,
pub baud_rate: u32,
/// Hz.
pub frequency: u32,
/// Hz.
pub bandwidth: u32,
pub spreading_factor: u8,
pub coding_rate: u8,
/// dBm.
pub tx_power: u8,
pub mode: InterfaceMode,
pub flow_control: bool,
/// Short-term airtime cap, percent (0.0..100.0). `None` = unlimited.
pub st_alock: Option<f32>,
/// Long-term airtime cap, percent (0.0..100.0). `None` = unlimited.
pub lt_alock: Option<f32>,
}
impl RNodeConfig {
pub fn new(name: &str, port: &str) -> Self {
Self {
name: name.to_string(),
port: port.to_string(),
baud_rate: 115200,
frequency: 868_000_000,
bandwidth: 125_000,
spreading_factor: 7,
coding_rate: 5,
tx_power: 14,
mode: InterfaceMode::Full,
flow_control: true,
st_alock: None,
lt_alock: None,
}
}
}
/// LoRa on-air bps via `SF * (4/CR) / (2^SF / BW_kHz) * 1000`. 0 on invalid.
pub fn calculate_bitrate(sf: u8, cr: u8, bandwidth_hz: u32) -> u64 {
if sf == 0 || cr == 0 || bandwidth_hz == 0 {
return 0;
}
let sf_f = sf as f64;
let cr_f = cr as f64;
let bw_khz = bandwidth_hz as f64 / 1000.0;
let two_pow_sf = (2.0_f64).powf(sf_f);
if two_pow_sf == 0.0 {
return 0;
}
let bitrate = sf_f * (4.0 / cr_f) / (two_pow_sf / bw_khz) * 1000.0;
if bitrate.is_finite() && bitrate > 0.0 {
bitrate as u64
} else {
0
}
}
pub fn build_detect_sequence() -> Vec<u8> {
let mut out = Vec::with_capacity(32);
kiss::frame_with_command_into(CMD_DETECT, &[DETECT_REQ], &mut out);
kiss::frame_with_command_into(CMD_FW_VERSION, &[0x00], &mut out);
kiss::frame_with_command_into(CMD_PLATFORM, &[0x00], &mut out);
kiss::frame_with_command_into(CMD_MCU, &[0x00], &mut out);
out
}
/// Airtime-lock commands. Percent is encoded as `(percent * 100)` big-endian u16.
pub fn build_airtime_sequence(config: &RNodeConfig) -> Vec<u8> {
let mut out = Vec::with_capacity(16);
if let Some(st) = config.st_alock {
let at = (st * 100.0) as u16;
let c1 = (at >> 8) as u8;
let c2 = (at & 0xFF) as u8;
kiss::frame_with_command_into(CMD_ST_ALOCK, &[c1, c2], &mut out);
}
if let Some(lt) = config.lt_alock {
let at = (lt * 100.0) as u16;
let c1 = (at >> 8) as u8;
let c2 = (at & 0xFF) as u8;
kiss::frame_with_command_into(CMD_LT_ALOCK, &[c1, c2], &mut out);
}
out
}
fn u32_to_bytes(val: u32) -> [u8; 4] {
val.to_be_bytes()
}
/// KISS init sequence. Order matters: RADIO_STATE=ON must be last.
pub fn build_init_sequence(config: &RNodeConfig) -> Vec<u8> {
let mut out = Vec::with_capacity(48);
kiss::frame_with_command_into(CMD_FREQUENCY, &u32_to_bytes(config.frequency), &mut out);
kiss::frame_with_command_into(CMD_BANDWIDTH, &u32_to_bytes(config.bandwidth), &mut out);
kiss::frame_with_command_into(CMD_SF, &[config.spreading_factor], &mut out);
kiss::frame_with_command_into(CMD_CR, &[config.coding_rate], &mut out);
kiss::frame_with_command_into(CMD_TXPOWER, &[config.tx_power], &mut out);
kiss::frame_with_command_into(CMD_RADIO_STATE, &[RADIO_STATE_ON], &mut out);
out
}
// Hot-path interface adapters pass this enum around directly; boxing the
// packet variant would add allocation to every received frame.
#[allow(clippy::large_enum_variant)]
pub enum RNodeResponse {
Packet(TransportMessage),
Ready(bool),
None,
}
/// Dispatch decoded KISS frame; shared by serial and BLE transports.
pub fn process_rnode_response(
cmd: u8,
frame: &[u8],
id: InterfaceId,
last_rssi: &mut Option<f32>,
last_snr: &mut Option<f32>,
) -> RNodeResponse {
match cmd {
kiss::CMD_DATA => {
if frame.is_empty() {
return RNodeResponse::None;
}
let msg = TransportMessage::Inbound(InboundPacket {
raw: Bytes::copy_from_slice(frame),
interface_id: id,
rssi: *last_rssi,
snr: *last_snr,
q: None,
});
// RSSI/SNR stats attach to the next data frame; clear once consumed.
*last_rssi = None;
*last_snr = None;
RNodeResponse::Packet(msg)
}
CMD_STAT_RSSI => {
if !frame.is_empty() {
*last_rssi = Some(frame[0] as i8 as f32);
}
RNodeResponse::None
}
CMD_STAT_SNR => {
if !frame.is_empty() {
*last_snr = Some(frame[0] as i8 as f32 / 4.0);
}
RNodeResponse::None
}
CMD_READY => {
let is_ready = frame.first().copied().unwrap_or(0) != 0;
RNodeResponse::Ready(is_ready)
}
CMD_DETECT => {
if frame.first().copied() == Some(DETECT_RESP) {
tracing::info!(id, "RNode detected");
}
RNodeResponse::None
}
CMD_RADIO_STATE => {
if frame.first().copied() == Some(RADIO_STATE_ON) {
tracing::info!(id, "RNode radio online");
} else {
tracing::warn!(id, "RNode radio offline");
}
RNodeResponse::None
}
CMD_FW_VERSION => {
if frame.len() >= 2 {
let major = frame[0];
let minor = frame[1];
tracing::info!(
id,
major,
minor,
"RNode firmware version {}.{}",
major,
minor,
);
if major < REQUIRED_FW_VER_MAJ
|| (major == REQUIRED_FW_VER_MAJ && minor < REQUIRED_FW_VER_MIN)
{
tracing::warn!(
id,
"RNode firmware {}.{} below required {}.{}",
major,
minor,
REQUIRED_FW_VER_MAJ,
REQUIRED_FW_VER_MIN,
);
}
}
RNodeResponse::None
}
CMD_ST_ALOCK => {
if frame.len() >= 2 {
let at = ((frame[0] as u16) << 8) | frame[1] as u16;
let pct = at as f32 / 100.0;
tracing::debug!(id, "RNode short-term airtime limit: {:.2}%", pct);
}
RNodeResponse::None
}
CMD_LT_ALOCK => {
if frame.len() >= 2 {
let at = ((frame[0] as u16) << 8) | frame[1] as u16;
let pct = at as f32 / 100.0;
tracing::debug!(id, "RNode long-term airtime limit: {:.2}%", pct);
}
RNodeResponse::None
}
CMD_STAT_BAT => {
if frame.len() >= 2 {
let batt = ((frame[0] as u16) << 8) | frame[1] as u16;
tracing::debug!(id, battery_mv = batt, "RNode battery status");
}
RNodeResponse::None
}
CMD_STAT_TEMP => {
if !frame.is_empty() {
let temp = frame[0] as i8;
tracing::debug!(id, temp_c = temp, "RNode temperature");
}
RNodeResponse::None
}
CMD_RADIO_LOCK => {
let locked = frame.first().copied().unwrap_or(0) != 0;
tracing::debug!(id, locked, "RNode radio lock state");
RNodeResponse::None
}
CMD_ERROR => {
tracing::warn!(
id,
error_code = frame.first().copied().unwrap_or(0),
"RNode reported error"
);
RNodeResponse::None
}
_ => {
tracing::debug!(id, cmd, "RNode: ignoring KISS command");
RNodeResponse::None
}
}
}
#[cfg(feature = "serial")]
pub async fn spawn_rnode_interface(
config: RNodeConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let port = serialport::new(&config.port, config.baud_rate)
.timeout(Duration::from_millis(RNODE_READ_TIMEOUT_MS))
.open()
.map_err(|e| crate::traits::InterfaceError::SendFailed(format!("rnode open: {}", e)))?;
tracing::info!(
name = %config.name,
port = %config.port,
freq = config.frequency,
bw = config.bandwidth,
sf = config.spreading_factor,
"RNode interface opened"
);
// Detect first so firmware version is known before init.
{
let mut detect_port = port.try_clone().map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("rnode clone: {}", e))
})?;
let detect_seq = build_detect_sequence();
use std::io::Write;
detect_port.write_all(&detect_seq).map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("rnode detect write: {}", e))
})?;
detect_port.flush().map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("rnode detect flush: {}", e))
})?;
}
{
let mut init_port = port.try_clone().map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("rnode clone: {}", e))
})?;
let mut init_seq = build_init_sequence(&config);
init_seq.extend_from_slice(&build_airtime_sequence(&config));
use std::io::Write;
init_port.write_all(&init_seq).map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("rnode init write: {}", e))
})?;
init_port.flush().map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("rnode init flush: {}", e))
})?;
}
let bitrate = calculate_bitrate(
config.spreading_factor,
config.coding_rate,
config.bandwidth,
);
tracing::info!(
bitrate_bps = bitrate,
bitrate_kbps = format!("{:.2}", bitrate as f64 / 1000.0),
"RNode on-air bitrate calculated"
);
let online = Arc::new(AtomicBool::new(true));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let (tx, mut rx) = mpsc::channel::<Bytes>(256);
let name = config.name.clone();
let mode = config.mode;
let flow_control = config.flow_control;
let port_write = port
.try_clone()
.map_err(|e| crate::traits::InterfaceError::SendFailed(format!("rnode clone: {}", e)))?;
let ready = Arc::new(AtomicBool::new(true));
let online_w = online.clone();
let ready_w = ready.clone();
let txb_w = shared_txb.clone();
tokio::spawn(async move {
let mut port_w = port_write;
while let Some(data) = rx.recv().await {
txb_w.fetch_add(data.len() as u64, std::sync::atomic::Ordering::Relaxed);
if flow_control {
while !ready_w.load(Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(10)).await;
if !online_w.load(Ordering::SeqCst) {
return;
}
}
}
let framed = kiss::frame(&data);
let online_ref = online_w.clone();
let result = tokio::task::spawn_blocking(move || {
use std::io::Write;
port_w.write_all(&framed)?;
port_w.flush()?;
Ok::<_, std::io::Error>(port_w)
})
.await;
match result {
Ok(Ok(p)) => {
port_w = p;
}
Ok(Err(e)) => {
tracing::warn!(error = %e, "RNode write error");
online_ref.store(false, Ordering::SeqCst);
break;
}
Err(e) => {
tracing::warn!(error = %e, "RNode write task panicked");
break;
}
}
}
});
let online_r = online.clone();
let ready_r = ready;
let rxb_r = shared_rxb.clone();
let read_task = tokio::spawn(async move {
let mut port_r = port;
let mut deframer = kiss::RawKissDeframer::new();
let mut buf = [0u8; 1024];
let mut last_rssi: Option<f32> = None;
let mut last_snr: Option<f32> = None;
loop {
if !online_r.load(Ordering::SeqCst) {
break;
}
let result = tokio::task::spawn_blocking(move || {
use std::io::Read;
match port_r.read(&mut buf) {
Ok(n) => Ok((port_r, buf, n)),
Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok((port_r, buf, 0)),
Err(e) => Err((port_r, e)),
}
})
.await;
match result {
Ok(Ok((p, b, n))) => {
port_r = p;
buf = b;
if n > 0 {
for (cmd, frame) in deframer.feed(&buf[..n]) {
match process_rnode_response(
cmd,
&frame,
id,
&mut last_rssi,
&mut last_snr,
) {
RNodeResponse::Packet(msg) => {
rxb_r.fetch_add(
frame.len() as u64,
std::sync::atomic::Ordering::Relaxed,
);
if transport_tx.send(msg).await.is_err() {
tracing::warn!(id, "transport channel closed");
online_r.store(false, Ordering::SeqCst);
return;
}
}
RNodeResponse::Ready(is_ready) => {
ready_r.store(is_ready, Ordering::SeqCst);
}
RNodeResponse::None => {}
}
}
}
}
Ok(Err((_p, e))) => {
tracing::warn!(error = %e, "RNode read error");
online_r.store(false, Ordering::SeqCst);
return;
}
Err(e) => {
tracing::warn!(error = %e, "RNode read task panicked");
online_r.store(false, Ordering::SeqCst);
return;
}
}
}
});
Ok(InterfaceHandle {
id,
name,
mode,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate,
mtu: 508,
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
tx,
read_task,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_rnode_config() {
let cfg = RNodeConfig::new("rnode0", "/dev/ttyACM0");
assert_eq!(cfg.baud_rate, 115200);
assert_eq!(cfg.frequency, 868_000_000);
assert_eq!(cfg.spreading_factor, 7);
assert!(cfg.flow_control);
assert!(cfg.st_alock.is_none());
assert!(cfg.lt_alock.is_none());
}
#[test]
fn test_init_sequence_parseable() {
let cfg = RNodeConfig::new("rnode0", "/dev/ttyACM0");
let seq = build_init_sequence(&cfg);
assert!(!seq.is_empty());
assert_eq!(seq[0], kiss::FEND);
let mut deframer = kiss::RawKissDeframer::new();
let frames = deframer.feed(&seq);
assert_eq!(frames.len(), 6);
}
#[test]
fn test_u32_to_bytes() {
assert_eq!(u32_to_bytes(868_000_000), 868_000_000u32.to_be_bytes());
assert_eq!(u32_to_bytes(0x01020304), [0x01, 0x02, 0x03, 0x04]);
}
#[test]
fn test_calculate_bitrate() {
// 7 * (4/5) / (2^7 / 125) * 1000 = 5468.75 bps -> 5468.
let br = calculate_bitrate(7, 5, 125_000);
assert_eq!(br, 5468);
let br2 = calculate_bitrate(12, 8, 125_000);
assert!(br2 > 0);
assert!(br2 < br);
assert_eq!(calculate_bitrate(0, 5, 125_000), 0);
assert_eq!(calculate_bitrate(7, 0, 125_000), 0);
assert_eq!(calculate_bitrate(7, 5, 0), 0);
}
#[test]
fn test_detect_sequence() {
let seq = build_detect_sequence();
assert!(!seq.is_empty());
let mut deframer = kiss::RawKissDeframer::new();
let frames = deframer.feed(&seq);
assert_eq!(frames.len(), 4);
assert_eq!(frames[0].0, CMD_DETECT);
}
#[test]
fn test_airtime_sequence() {
let mut cfg = RNodeConfig::new("rnode0", "/dev/ttyACM0");
assert!(build_airtime_sequence(&cfg).is_empty());
cfg.st_alock = Some(15.0);
cfg.lt_alock = Some(25.0);
let seq = build_airtime_sequence(&cfg);
assert!(!seq.is_empty());
let mut deframer = kiss::RawKissDeframer::new();
let frames = deframer.feed(&seq);
assert_eq!(frames.len(), 2);
assert_eq!(frames[0].0, CMD_ST_ALOCK);
assert_eq!(frames[1].0, CMD_LT_ALOCK);
}
#[test]
fn test_rnode_admin_constants_match_upstream() {
assert_eq!(CMD_BOARD, 0x47);
assert_eq!(CMD_BT_PIN, 0x62);
assert_eq!(CMD_DISP_INT, 0x45);
assert_eq!(CMD_DISP_ADR, 0x63);
assert_eq!(CMD_WIFI_IP, 0x84);
assert_eq!(CMD_WIFI_NM, 0x85);
}
}
+170
View File
@@ -0,0 +1,170 @@
//! Extended-KISS admin codec shared by RNode runtime and `rnodeconf`.
use std::net::Ipv4Addr;
use crate::{kiss, rnode};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AdminFrame {
pub command: u8,
pub payload: Vec<u8>,
}
pub fn encode_frame(command: u8, payload: &[u8]) -> Vec<u8> {
kiss::frame_with_command(command, payload)
}
pub fn decode_frames(raw: &[u8]) -> Vec<AdminFrame> {
let mut deframer = kiss::RawKissDeframer::new();
deframer
.feed(raw)
.into_iter()
.map(|(command, payload)| AdminFrame { command, payload })
.collect()
}
pub fn u32_payload(value: u32) -> [u8; 4] {
value.to_be_bytes()
}
pub fn parse_u32(payload: &[u8]) -> Option<u32> {
let bytes: [u8; 4] = payload.try_into().ok()?;
Some(u32::from_be_bytes(bytes))
}
pub fn parse_bt_pin(frame: &AdminFrame) -> Option<u32> {
(frame.command == rnode::CMD_BT_PIN)
.then(|| parse_u32(&frame.payload))
.flatten()
}
pub fn bool_payload(enabled: bool) -> [u8; 1] {
[u8::from(enabled)]
}
pub fn nullable_string_payload(value: Option<&str>) -> Vec<u8> {
match value {
Some(value) if !value.is_empty() => {
let mut out = value.as_bytes().to_vec();
out.push(0);
out
}
_ => vec![0],
}
}
pub fn ipv4_payload(addr: Ipv4Addr) -> [u8; 4] {
addr.octets()
}
pub fn detect_sequence() -> Vec<AdminFrame> {
vec![
frame(rnode::CMD_DETECT, &[rnode::DETECT_REQ]),
frame(rnode::CMD_FW_VERSION, &[0]),
frame(rnode::CMD_PLATFORM, &[0]),
frame(rnode::CMD_MCU, &[0]),
frame(rnode::CMD_BOARD, &[0]),
frame(rnode::CMD_DEV_HASH, &[1]),
frame(rnode::CMD_HASHES, &[1]),
frame(rnode::CMD_HASHES, &[2]),
]
}
pub fn eeprom_read_frame() -> AdminFrame {
frame(rnode::CMD_ROM_READ, &[0])
}
pub fn eeprom_write_frame(address: u8, value: u8) -> AdminFrame {
frame(rnode::CMD_ROM_WRITE, &[address, value])
}
pub fn eeprom_wipe_frame() -> AdminFrame {
frame(rnode::CMD_ROM_WIPE, &[0xF8])
}
pub fn reset_frame() -> AdminFrame {
frame(rnode::CMD_RESET, &[0xF8])
}
pub fn firmware_update_frame() -> AdminFrame {
frame(rnode::CMD_FW_UPD, &[1])
}
pub fn firmware_hash_frame(hash: &[u8; 32]) -> AdminFrame {
frame(rnode::CMD_FW_HASH, hash)
}
pub fn device_signature_frame(signature: &[u8; 64]) -> AdminFrame {
frame(rnode::CMD_DEV_SIG, signature)
}
pub fn frame(command: u8, payload: &[u8]) -> AdminFrame {
AdminFrame {
command,
payload: payload.to_vec(),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum WifiMode {
Off = 0,
Station = 1,
AccessPoint = 2,
}
impl WifiMode {
pub fn payload(self) -> [u8; 1] {
[self as u8]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extended_commands_round_trip_without_masking() {
let mut raw = Vec::new();
raw.extend_from_slice(&encode_frame(rnode::CMD_WIFI_IP, &[192, 168, 1, 10]));
raw.extend_from_slice(&encode_frame(rnode::CMD_WIFI_NM, &[255, 255, 255, 0]));
raw.extend_from_slice(&encode_frame(rnode::CMD_BT_PIN, &123456u32.to_be_bytes()));
let frames = decode_frames(&raw);
assert_eq!(frames[0].command, 0x84);
assert_eq!(frames[0].payload, vec![192, 168, 1, 10]);
assert_eq!(frames[1].command, 0x85);
assert_eq!(frames[2].command, 0x62);
assert_eq!(parse_bt_pin(&frames[2]), Some(123456));
}
#[test]
fn payload_helpers_match_upstream_shapes() {
assert_eq!(u32_payload(868_000_000), [0x33, 0xBC, 0xA1, 0x00]);
assert_eq!(bool_payload(true), [1]);
assert_eq!(WifiMode::AccessPoint.payload(), [2]);
assert_eq!(nullable_string_payload(None), vec![0]);
assert_eq!(nullable_string_payload(Some("RNode")), b"RNode\0");
assert_eq!(
ipv4_payload(Ipv4Addr::new(192, 168, 1, 10)),
[192, 168, 1, 10]
);
}
#[test]
fn admin_frame_builders_match_upstream_commands() {
let sequence = detect_sequence();
assert_eq!(
sequence.iter().map(|f| f.command).collect::<Vec<_>>(),
vec![0x08, 0x50, 0x48, 0x49, 0x47, 0x56, 0x60, 0x60]
);
assert_eq!(eeprom_read_frame(), frame(rnode::CMD_ROM_READ, &[0]));
assert_eq!(
eeprom_write_frame(0x9B, 0x73),
frame(rnode::CMD_ROM_WRITE, &[0x9B, 0x73])
);
assert_eq!(eeprom_wipe_frame(), frame(rnode::CMD_ROM_WIPE, &[0xF8]));
assert_eq!(reset_frame(), frame(rnode::CMD_RESET, &[0xF8]));
assert_eq!(firmware_update_frame(), frame(rnode::CMD_FW_UPD, &[1]));
}
}
File diff suppressed because it is too large. Load diff
+222
View File
@@ -0,0 +1,222 @@
//! HDLC-framed data over a serial port. Uses `serialport` with
//! `spawn_blocking` because no mature async driver exists yet.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;
use bytes::Bytes;
use tokio::sync::mpsc;
use crate::hdlc;
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
use rns_transport::messages::{InboundPacket, TransportMessage};
pub const DEFAULT_BAUD: u32 = 9600;
const SERIAL_READ_TIMEOUT_MS: u64 = 100;
#[derive(Debug, Clone)]
pub struct SerialConfig {
pub name: String,
pub port: String,
pub baud_rate: u32,
pub data_bits: serialport::DataBits,
pub parity: serialport::Parity,
pub stop_bits: serialport::StopBits,
pub mode: InterfaceMode,
}
impl SerialConfig {
pub fn new(name: &str, port: &str) -> Self {
Self {
name: name.to_string(),
port: port.to_string(),
baud_rate: DEFAULT_BAUD,
data_bits: serialport::DataBits::Eight,
parity: serialport::Parity::None,
stop_bits: serialport::StopBits::One,
mode: InterfaceMode::Full,
}
}
pub fn baud(mut self, baud: u32) -> Self {
self.baud_rate = baud;
self
}
}
pub async fn spawn_serial_interface(
config: SerialConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let port = serialport::new(&config.port, config.baud_rate)
.data_bits(config.data_bits)
.parity(config.parity)
.stop_bits(config.stop_bits)
.timeout(Duration::from_millis(SERIAL_READ_TIMEOUT_MS))
.open()
.map_err(|e| crate::traits::InterfaceError::SendFailed(format!("serial open: {}", e)))?;
tracing::info!(
name = %config.name,
port = %config.port,
baud = config.baud_rate,
"serial interface opened"
);
let online = Arc::new(AtomicBool::new(true));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let (tx, mut rx) = mpsc::channel::<Bytes>(256);
let name = config.name.clone();
let mode = config.mode;
let port_write = port
.try_clone()
.map_err(|e| crate::traits::InterfaceError::SendFailed(format!("serial clone: {}", e)))?;
let online_w = online.clone();
let txb_w = shared_txb.clone();
tokio::spawn(async move {
let mut port_w = port_write;
while let Some(data) = rx.recv().await {
txb_w.fetch_add(data.len() as u64, std::sync::atomic::Ordering::Relaxed);
let framed = hdlc::frame(&data);
let online_ref = online_w.clone();
let result = tokio::task::spawn_blocking(move || {
use std::io::Write;
port_w.write_all(&framed)?;
port_w.flush()?;
Ok::<_, std::io::Error>(port_w)
})
.await;
match result {
Ok(Ok(p)) => {
port_w = p;
}
Ok(Err(e)) => {
tracing::warn!(error = %e, "serial write error");
online_ref.store(false, Ordering::SeqCst);
break;
}
Err(e) => {
tracing::warn!(error = %e, "serial write task panicked");
break;
}
}
}
});
let online_r = online.clone();
let rxb_r = shared_rxb.clone();
let read_task = tokio::spawn(async move {
let mut port_r = port;
let mut deframer = hdlc::HdlcDeframer::new();
let mut buf = [0u8; 1024];
loop {
if !online_r.load(Ordering::SeqCst) {
break;
}
let result = tokio::task::spawn_blocking(move || {
use std::io::Read;
match port_r.read(&mut buf) {
Ok(n) => Ok((port_r, buf, n)),
Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok((port_r, buf, 0)),
Err(e) => Err((port_r, e)),
}
})
.await;
match result {
Ok(Ok((p, b, n))) => {
port_r = p;
buf = b;
if n > 0 {
rxb_r.fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed);
for frame in deframer.feed(&buf[..n]) {
if frame.is_empty() {
continue;
}
let msg = TransportMessage::Inbound(InboundPacket {
raw: Bytes::from(frame),
interface_id: id,
rssi: None,
snr: None,
q: None,
});
if transport_tx.send(msg).await.is_err() {
tracing::warn!(id, "transport channel closed");
online_r.store(false, Ordering::SeqCst);
return;
}
}
}
}
Ok(Err((_p, e))) => {
tracing::warn!(error = %e, "serial read error");
online_r.store(false, Ordering::SeqCst);
return;
}
Err(e) => {
tracing::warn!(error = %e, "serial read task panicked");
online_r.store(false, Ordering::SeqCst);
return;
}
}
}
});
Ok(InterfaceHandle {
id,
name,
mode,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: config.baud_rate as u64,
mtu: 564,
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
tx,
read_task,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_serial_config() {
let cfg = SerialConfig::new("serial0", "/dev/ttyUSB0").baud(115200);
assert_eq!(cfg.baud_rate, 115200);
assert_eq!(cfg.port, "/dev/ttyUSB0");
}
#[test]
fn test_serial_config_custom_baud() {
let cfg = SerialConfig::new("ser0", "/dev/ttyUSB0").baud(9600);
assert_eq!(cfg.baud_rate, 9600);
}
#[test]
fn test_serial_config_default_mode() {
let cfg = SerialConfig::new("ser0", "/dev/ttyUSB0");
assert_eq!(cfg.mode, InterfaceMode::Full);
}
#[test]
fn test_serial_config_builder_chain() {
let cfg = SerialConfig::new("serial0", "/dev/ttyACM0").baud(115200);
assert_eq!(cfg.name, "serial0");
assert_eq!(cfg.port, "/dev/ttyACM0");
assert_eq!(cfg.baud_rate, 115200);
}
}
+208
View File
@@ -0,0 +1,208 @@
//! Shared TCP socket tuning for [`crate::tcp`] and [`crate::backbone`].
//! `set_keepalive`: portable SO_KEEPALIVE. `set_keepalive_tuned`: adds Linux
//! TCP_KEEPIDLE/INTVL/CNT + TCP_USER_TIMEOUT.
//! `iface_addr_for`: kernel iface name → IpAddr for Backbone `device =` key.
use std::net::IpAddr;
use std::time::Duration;
use tokio::net::TcpStream;
/// Enable portable `SO_KEEPALIVE`; for tuned, use [`set_keepalive_tuned`].
#[cfg(unix)]
pub fn set_keepalive(stream: &TcpStream) -> std::io::Result<()> {
use std::os::fd::{AsRawFd, FromRawFd};
let raw_fd = stream.as_ref().as_raw_fd();
// SAFETY: we borrow the fd without taking ownership (ManuallyDrop ensures
// the socket2::Socket destructor does not close the fd).
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
sock.set_keepalive(true)?;
Ok(())
}
#[cfg(windows)]
pub fn set_keepalive(stream: &TcpStream) -> std::io::Result<()> {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_ref().as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
sock.set_keepalive(true)?;
Ok(())
}
/// Tuned keepalive: idle/interval/retries + Linux TCP_USER_TIMEOUT. Best-effort.
#[cfg(unix)]
pub fn set_keepalive_tuned(
stream: &TcpStream,
idle: Duration,
intvl: Duration,
retries: u32,
user_timeout: Duration,
) {
use std::os::fd::{AsRawFd, FromRawFd};
let raw_fd = stream.as_ref().as_raw_fd();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
}
#[cfg(windows)]
pub fn set_keepalive_tuned(
stream: &TcpStream,
idle: Duration,
intvl: Duration,
retries: u32,
user_timeout: Duration,
) {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_ref().as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
}
fn apply_tuned_keepalive(
sock: &socket2::Socket,
idle: Duration,
intvl: Duration,
retries: u32,
user_timeout: Duration,
) {
let ka = socket2::TcpKeepalive::new().with_time(idle);
#[cfg(any(unix, windows))]
let ka = ka.with_interval(intvl);
#[cfg(not(any(unix, windows)))]
let _ = intvl;
#[cfg(unix)]
let ka = ka.with_retries(retries);
#[cfg(not(unix))]
let _ = retries;
if let Err(e) = sock.set_tcp_keepalive(&ka) {
tracing::warn!(error = %e, "set_tcp_keepalive failed");
}
// TCP_USER_TIMEOUT — Linux-family only.
#[cfg(any(target_os = "linux", target_os = "android", target_os = "fuchsia"))]
if let Err(e) = sock.set_tcp_user_timeout(Some(user_timeout)) {
tracing::warn!(error = %e, "set_tcp_user_timeout failed");
}
#[cfg(not(any(target_os = "linux", target_os = "android", target_os = "fuchsia")))]
let _ = user_timeout;
}
/// Raise TCP send/recv buffers; best-effort.
#[cfg(unix)]
pub fn set_socket_buffers(stream: &TcpStream, size: usize) {
use std::os::fd::{AsRawFd, FromRawFd};
let raw_fd = stream.as_ref().as_raw_fd();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
let _ = sock.set_recv_buffer_size(size);
let _ = sock.set_send_buffer_size(size);
}
#[cfg(windows)]
pub fn set_socket_buffers(stream: &TcpStream, size: usize) {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_ref().as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
let _ = sock.set_recv_buffer_size(size);
let _ = sock.set_send_buffer_size(size);
}
/// Resolve interface name to `IpAddr`; `None` if missing. Caller falls back
/// to wildcard bind.
pub fn iface_addr_for(name: &str, prefer_ipv6: bool) -> Option<IpAddr> {
let ifaces = match if_addrs::get_if_addrs() {
Ok(v) => v,
Err(e) => {
tracing::warn!(error = %e, "if_addrs::get_if_addrs() failed");
return None;
}
};
let matches: Vec<IpAddr> = ifaces
.into_iter()
.filter(|i| i.name == name)
.map(|i| i.addr.ip())
.collect();
if matches.is_empty() {
return None;
}
if prefer_ipv6 {
matches
.iter()
.find(|a| a.is_ipv6())
.copied()
.or_else(|| matches.first().copied())
} else {
matches
.iter()
.find(|a| a.is_ipv4())
.copied()
.or_else(|| matches.first().copied())
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::net::TcpListener;
#[tokio::test]
async fn keepalive_and_buffers_apply_without_panic() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let (server_accept, client_connect) =
tokio::join!(listener.accept(), TcpStream::connect(addr));
let (server, _) = server_accept.unwrap();
let client = client_connect.unwrap();
set_keepalive(&server).expect("server set_keepalive");
set_keepalive(&client).expect("client set_keepalive");
// Tuned keepalive — must not panic on any platform.
set_keepalive_tuned(
&server,
Duration::from_secs(5),
Duration::from_secs(2),
12,
Duration::from_secs(24),
);
set_keepalive_tuned(
&client,
Duration::from_secs(5),
Duration::from_secs(2),
12,
Duration::from_secs(24),
);
set_socket_buffers(&server, 131_072);
set_socket_buffers(&client, 131_072);
}
#[test]
fn iface_addr_for_loopback_resolves() {
// Loopback name varies by OS; iterate candidates.
let candidates = ["lo", "lo0", "Loopback Pseudo-Interface 1"];
let mut found_v4 = false;
for name in candidates {
if let Some(IpAddr::V4(v4)) = iface_addr_for(name, false)
&& v4.is_loopback()
{
found_v4 = true;
break;
}
}
// Hermetic CI may not expose loopback by name; only assert when seen.
if let Ok(ifaces) = if_addrs::get_if_addrs()
&& ifaces.iter().any(|i| candidates.contains(&i.name.as_str()))
{
assert!(
found_v4,
"expected a loopback IPv4 on one of {candidates:?}"
);
}
}
#[test]
fn iface_addr_for_missing_returns_none() {
assert!(iface_addr_for("definitely-not-a-real-interface-zzz", false).is_none());
}
}
+799
View File
@@ -0,0 +1,799 @@
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use bytes::Bytes;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::mpsc;
use crate::hdlc;
use crate::kiss;
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
use rns_transport::messages::{InboundPacket, TransportMessage};
pub const RECONNECT_WAIT_INITIAL: u64 = 5;
pub const RECONNECT_WAIT_MAX: u64 = 300;
pub const DEFAULT_CONNECT_TIMEOUT: u64 = 5;
pub const DEFAULT_TCP_USER_TIMEOUT: u32 = 24;
/// I2P tunnels need a longer `TCP_USER_TIMEOUT` to absorb latency spikes.
pub const I2P_TCP_USER_TIMEOUT: u32 = 45;
pub const TCP_HW_MTU: u32 = 262144;
pub const TCP_KEEPIDLE: u32 = 5;
pub const TCP_KEEPINTVL: u32 = 2;
pub const TCP_KEEPCNT: u32 = 12;
#[derive(Debug, Clone)]
pub struct TcpClientConfig {
pub name: String,
pub target_host: String,
pub target_port: u16,
pub kiss_framing: bool,
pub connect_timeout_secs: u64,
pub max_reconnect_tries: Option<usize>,
pub mode: InterfaceMode,
}
impl TcpClientConfig {
pub fn new(name: &str, host: &str, port: u16) -> Self {
Self {
name: name.to_string(),
target_host: host.to_string(),
target_port: port,
kiss_framing: false,
connect_timeout_secs: DEFAULT_CONNECT_TIMEOUT,
max_reconnect_tries: None,
mode: InterfaceMode::Full,
}
}
}
#[derive(Debug, Clone)]
pub struct TcpServerConfig {
pub name: String,
pub listen_ip: String,
pub listen_port: u16,
pub kiss_framing: bool,
pub prefer_ipv6: bool,
pub mode: InterfaceMode,
}
impl TcpServerConfig {
pub fn new(name: &str, ip: &str, port: u16) -> Self {
Self {
name: name.to_string(),
listen_ip: ip.to_string(),
listen_port: port,
kiss_framing: false,
prefer_ipv6: false,
mode: InterfaceMode::Full,
}
}
}
pub struct TcpInterfaceState {
pub online: AtomicBool,
pub detached: AtomicBool,
pub rx_bytes: AtomicU64,
pub tx_bytes: AtomicU64,
pub rx_packets: AtomicU64,
pub tx_packets: AtomicU64,
/// Aggregate counters that persist across reconnections.
pub shared_rxb: Option<Arc<AtomicU64>>,
pub shared_txb: Option<Arc<AtomicU64>>,
}
impl TcpInterfaceState {
pub fn new() -> Arc<Self> {
Arc::new(Self {
online: AtomicBool::new(false),
detached: AtomicBool::new(false),
rx_bytes: AtomicU64::new(0),
tx_bytes: AtomicU64::new(0),
rx_packets: AtomicU64::new(0),
tx_packets: AtomicU64::new(0),
shared_rxb: None,
shared_txb: None,
})
}
pub fn with_shared_counters(rxb: Arc<AtomicU64>, txb: Arc<AtomicU64>) -> Arc<Self> {
Arc::new(Self {
online: AtomicBool::new(false),
detached: AtomicBool::new(false),
rx_bytes: AtomicU64::new(0),
tx_bytes: AtomicU64::new(0),
rx_packets: AtomicU64::new(0),
tx_packets: AtomicU64::new(0),
shared_rxb: Some(rxb),
shared_txb: Some(txb),
})
}
pub fn record_rx(&self, bytes: usize) {
self.rx_bytes.fetch_add(bytes as u64, Ordering::Relaxed);
self.rx_packets.fetch_add(1, Ordering::Relaxed);
if let Some(shared) = &self.shared_rxb {
shared.fetch_add(bytes as u64, Ordering::Relaxed);
}
}
pub fn record_tx(&self, bytes: usize) {
self.tx_bytes.fetch_add(bytes as u64, Ordering::Relaxed);
self.tx_packets.fetch_add(1, Ordering::Relaxed);
if let Some(shared) = &self.shared_txb {
shared.fetch_add(bytes as u64, Ordering::Relaxed);
}
}
}
impl Default for TcpInterfaceState {
fn default() -> Self {
Self {
online: AtomicBool::new(false),
detached: AtomicBool::new(false),
rx_bytes: AtomicU64::new(0),
tx_bytes: AtomicU64::new(0),
rx_packets: AtomicU64::new(0),
tx_packets: AtomicU64::new(0),
shared_rxb: None,
shared_txb: None,
}
}
}
pub fn frame_for_tcp(data: &[u8], kiss_framing: bool) -> Vec<u8> {
if kiss_framing {
crate::kiss::frame(data)
} else {
hdlc::frame(data)
}
}
use crate::socket_tuning::{set_keepalive, set_socket_buffers};
async fn tcp_read_loop(
mut reader: tokio::net::tcp::OwnedReadHalf,
interface_id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
state: Arc<TcpInterfaceState>,
kiss_framing: bool,
) {
let mut buf = [0u8; 32768];
if kiss_framing {
let mut deframer = kiss::KissDeframer::new();
loop {
match reader.read(&mut buf).await {
Ok(0) => {
tracing::info!(interface_id, "TCP read: EOF");
break;
}
Ok(n) => {
for (_cmd, frame) in deframer.feed(&buf[..n]) {
if frame.is_empty() {
continue;
}
state.record_rx(frame.len());
let msg = TransportMessage::Inbound(InboundPacket {
raw: Bytes::from(frame),
interface_id,
rssi: None,
snr: None,
q: None,
});
if transport_tx.send(msg).await.is_err() {
tracing::warn!(interface_id, "transport channel closed");
return;
}
}
}
Err(e) => {
tracing::warn!(interface_id, error = %e, "TCP read error");
break;
}
}
}
} else {
let mut deframer = hdlc::HdlcDeframer::new();
loop {
match reader.read(&mut buf).await {
Ok(0) => {
tracing::info!(interface_id, "TCP read: EOF");
break;
}
Ok(n) => {
for frame in deframer.feed(&buf[..n]) {
if frame.is_empty() {
continue;
}
tracing::debug!(
interface_id,
frame_len = frame.len(),
first_byte = format!("0x{:02x}", frame.first().copied().unwrap_or(0)),
"TCP read: deframed packet"
);
state.record_rx(frame.len());
let msg = TransportMessage::Inbound(InboundPacket {
raw: Bytes::from(frame),
interface_id,
rssi: None,
snr: None,
q: None,
});
if transport_tx.send(msg).await.is_err() {
tracing::warn!(interface_id, "transport channel closed");
return;
}
}
}
Err(e) => {
tracing::warn!(interface_id, error = %e, "TCP read error");
break;
}
}
}
}
state.online.store(false, Ordering::SeqCst);
}
async fn tcp_write_loop(
mut writer: tokio::net::tcp::OwnedWriteHalf,
mut rx: mpsc::Receiver<Bytes>,
state: Arc<TcpInterfaceState>,
kiss_framing: bool,
) {
while let Some(data) = rx.recv().await {
let framed = frame_for_tcp(&data, kiss_framing);
tracing::debug!(
raw_len = data.len(),
framed_len = framed.len(),
first_byte = format!("0x{:02x}", data.first().copied().unwrap_or(0)),
"TCP write: sending frame"
);
state.record_tx(data.len());
if let Err(e) = writer.write_all(&framed).await {
tracing::warn!(error = %e, "TCP write error");
break;
}
}
state.online.store(false, Ordering::SeqCst);
}
/// Spawn an auto-reconnecting TCP client interface.
pub async fn spawn_tcp_client(
config: TcpClientConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
_ifac: Option<crate::traits::IfacConfig>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let online = Arc::new(AtomicBool::new(false));
let online2 = online.clone();
let (tx, rx) = mpsc::channel::<Bytes>(1024);
let name = config.name.clone();
let mode = config.mode;
let kiss_framing = config.kiss_framing;
// Wrap rx so it survives reconnects; forwarder task feeds per-connection channel.
let rx = Arc::new(tokio::sync::Mutex::new(rx));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let task_rxb = shared_rxb.clone();
let task_txb = shared_txb.clone();
let read_task = tokio::spawn(async move {
let max_tries = config.max_reconnect_tries;
let mut tries: usize = 0;
let mut backoff = RECONNECT_WAIT_INITIAL;
loop {
let addr = format!("{}:{}", config.target_host, config.target_port);
let stream = match tokio::time::timeout(
std::time::Duration::from_secs(config.connect_timeout_secs),
TcpStream::connect(&addr),
)
.await
{
Ok(Ok(s)) => s,
Ok(Err(e)) => {
tracing::warn!(name = %config.name, error = %e, "TCP connect failed");
if let Some(max) = max_tries {
tries += 1;
if tries >= max {
tracing::warn!(name = %config.name, "max reconnect tries reached");
return;
}
}
tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
continue;
}
Err(_) => {
tracing::warn!(name = %config.name, "TCP connect timed out");
if let Some(max) = max_tries {
tries += 1;
if tries >= max {
tracing::warn!(name = %config.name, "max reconnect tries reached");
return;
}
}
tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
continue;
}
};
if let Err(e) = set_keepalive(&stream) {
tracing::debug!(error = %e, "failed to set TCP keepalive");
}
// Nagle off for low-latency packets; larger buffers for bulk transfers.
let _ = stream.set_nodelay(true);
set_socket_buffers(&stream, 131072);
let state = TcpInterfaceState::with_shared_counters(task_rxb.clone(), task_txb.clone());
state.online.store(true, Ordering::SeqCst);
online2.store(true, Ordering::SeqCst);
tries = 0;
backoff = RECONNECT_WAIT_INITIAL;
let (reader, writer) = stream.into_split();
let (conn_tx, conn_rx) = mpsc::channel::<Bytes>(1024);
let state_w = state.clone();
let write_handle = tokio::spawn(tcp_write_loop(writer, conn_rx, state_w, kiss_framing));
let rx_ref = rx.clone();
let fwd_handle = tokio::spawn(async move {
let mut guard = rx_ref.lock().await;
while let Some(data) = guard.recv().await {
if conn_tx.send(data).await.is_err() {
break;
}
}
});
tcp_read_loop(
reader,
id,
transport_tx.clone(),
state.clone(),
kiss_framing,
)
.await;
online2.store(false, Ordering::SeqCst);
fwd_handle.abort();
let _ = fwd_handle.await;
write_handle.abort();
let _ = write_handle.await;
if let Some(max) = max_tries {
tries += 1;
if tries >= max {
tracing::warn!(name = %config.name, "max reconnect tries reached");
// Notify transport immediately rather than waiting for auto-drop.
let _ = transport_tx
.send(TransportMessage::DeregisterInterface { id })
.await;
return;
}
}
tracing::info!(name = %config.name, "reconnecting in {}s", backoff);
tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
}
});
let bitrate: u64 = 10_000_000;
Ok(InterfaceHandle {
id,
name,
mode,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate,
mtu: crate::traits::optimise_mtu(bitrate).unwrap_or(TCP_HW_MTU),
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
tx,
read_task,
})
}
/// Wrap an accepted TCP stream as an interface; no reconnect on disconnect.
#[tracing::instrument(
level = "debug",
name = "tcp.server.accept",
skip_all,
fields(client_id = id, name = %name),
)]
async fn spawn_tcp_accepted(
stream: TcpStream,
id: InterfaceId,
name: String,
transport_tx: mpsc::Sender<TransportMessage>,
kiss_framing: bool,
mode: InterfaceMode,
) -> InterfaceHandle {
let online = Arc::new(AtomicBool::new(true));
let online2 = online.clone();
let (tx, conn_rx) = mpsc::channel::<Bytes>(1024);
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let state = TcpInterfaceState::with_shared_counters(shared_rxb.clone(), shared_txb.clone());
state.online.store(true, Ordering::SeqCst);
if let Err(e) = set_keepalive(&stream) {
tracing::debug!(error = %e, "failed to set keepalive on accepted socket");
}
let _ = stream.set_nodelay(true);
set_socket_buffers(&stream, 131072);
let (reader, writer) = stream.into_split();
let state_w = state.clone();
tokio::spawn(tcp_write_loop(writer, conn_rx, state_w, kiss_framing));
let handle_name = name.clone();
let dereg_tx = transport_tx.clone();
let read_task = tokio::spawn(async move {
tcp_read_loop(reader, id, transport_tx, state, kiss_framing).await;
online2.store(false, Ordering::SeqCst);
tracing::info!(name = %handle_name, "accepted TCP client disconnected");
// Proactively notify transport so broadcasts stop targeting this dead tx.
let _ = dereg_tx
.send(TransportMessage::DeregisterInterface { id })
.await;
});
let bitrate: u64 = 10_000_000;
InterfaceHandle {
id,
name,
mode,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate,
mtu: crate::traits::optimise_mtu(bitrate).unwrap_or(TCP_HW_MTU),
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
tx,
read_task,
}
}
/// Spawn a TCP server. Each accepted connection becomes its own
/// `InterfaceHandle`, delivered via `handle_tx` for caller registration.
pub async fn spawn_tcp_server(
config: TcpServerConfig,
id: InterfaceId,
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let addr = format!("{}:{}", config.listen_ip, config.listen_port);
let listener = TcpListener::bind(&addr).await?;
let local_addr = listener.local_addr()?;
tracing::info!(name = %config.name, addr = %local_addr, "TCP server listening");
let online = Arc::new(AtomicBool::new(true));
let online2 = online.clone();
let name = config.name.clone();
let mode = config.mode;
let kiss_framing = config.kiss_framing;
// Server handle tx is unused; only accepted connections send.
let (tx, _rx) = mpsc::channel::<Bytes>(1);
let read_task = tokio::spawn(async move {
loop {
match listener.accept().await {
Ok((stream, peer)) => {
let client_id = id_gen.fetch_add(1, Ordering::SeqCst);
let client_name = format!("{}/client_{}", config.name, client_id);
tracing::info!(name = %client_name, peer = %peer, "accepted TCP connection");
let handle = spawn_tcp_accepted(
stream,
client_id,
client_name,
transport_tx.clone(),
kiss_framing,
mode,
)
.await;
if handle_tx.send(handle).await.is_err() {
tracing::warn!("handle registry channel closed, stopping accept loop");
break;
}
}
Err(e) => {
tracing::warn!(error = %e, "TCP accept error");
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
}
online2.store(false, Ordering::SeqCst);
});
let bitrate: u64 = 10_000_000;
Ok(InterfaceHandle {
id,
name,
mode,
direction: InterfaceDirection {
inbound: true,
outbound: false,
forward: false,
repeat: false,
},
bitrate,
mtu: crate::traits::optimise_mtu(bitrate).unwrap_or(TCP_HW_MTU),
online,
rxb: Some(Arc::new(AtomicU64::new(0))),
txb: Some(Arc::new(AtomicU64::new(0))),
tx,
read_task,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tcp_client_config() {
let config = TcpClientConfig::new("test", "127.0.0.1", 4242);
assert_eq!(config.target_port, 4242);
assert!(!config.kiss_framing);
assert_eq!(config.connect_timeout_secs, DEFAULT_CONNECT_TIMEOUT);
}
#[test]
fn test_tcp_server_config() {
let config = TcpServerConfig::new("server", "0.0.0.0", 4242);
assert_eq!(config.listen_port, 4242);
assert!(!config.prefer_ipv6);
}
#[test]
fn test_frame_for_tcp_hdlc() {
let data = b"test packet";
let framed = frame_for_tcp(data, false);
assert_eq!(framed[0], hdlc::FLAG);
assert_eq!(framed[framed.len() - 1], hdlc::FLAG);
}
#[test]
fn test_frame_for_tcp_kiss() {
let data = b"test packet";
let framed = frame_for_tcp(data, true);
assert_eq!(framed[0], crate::kiss::FEND);
assert_eq!(framed[framed.len() - 1], crate::kiss::FEND);
}
#[test]
fn test_interface_state() {
let state = TcpInterfaceState::new();
state.record_rx(100);
state.record_tx(200);
assert_eq!(state.rx_bytes.load(Ordering::Relaxed), 100);
assert_eq!(state.tx_bytes.load(Ordering::Relaxed), 200);
assert_eq!(state.rx_packets.load(Ordering::Relaxed), 1);
assert_eq!(state.tx_packets.load(Ordering::Relaxed), 1);
}
/// TCP loopback: spawn server + client on localhost:0, roundtrip a packet.
#[tokio::test]
async fn test_tcp_loopback_roundtrip() {
let (transport_tx, mut transport_rx) = mpsc::channel::<TransportMessage>(64);
let (handle_tx, mut handle_rx) = mpsc::channel::<InterfaceHandle>(8);
let id_gen = Arc::new(AtomicU64::new(100));
// Bind-then-drop to grab a free port for the server config.
let server_cfg = TcpServerConfig::new("test-server", "127.0.0.1", 0);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
drop(listener);
let mut server_cfg2 = server_cfg;
server_cfg2.listen_port = port;
let server_handle =
spawn_tcp_server(server_cfg2, 99, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
assert_eq!(server_handle.id, 99);
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
let client_cfg = TcpClientConfig {
name: "test-client".into(),
target_host: "127.0.0.1".into(),
target_port: port,
kiss_framing: false,
connect_timeout_secs: 5,
max_reconnect_tries: Some(1),
mode: InterfaceMode::Full,
};
let client_handle = spawn_tcp_client(client_cfg, 1, transport_tx.clone(), None)
.await
.unwrap();
let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for accepted handle")
.expect("handle channel closed");
let payload = Bytes::from_static(b"hello from client");
client_handle.tx.send(payload.clone()).await.unwrap();
let msg = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv())
.await
.expect("timeout waiting for transport message")
.expect("transport channel closed");
match msg {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, payload);
assert_eq!(pkt.interface_id, accepted.id);
}
other => panic!("unexpected message: {:?}", other),
}
let reply = Bytes::from_static(b"hello from server");
accepted.tx.send(reply.clone()).await.unwrap();
let msg2 = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv())
.await
.expect("timeout waiting for reply")
.expect("transport channel closed");
match msg2 {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, reply);
assert_eq!(pkt.interface_id, 1);
}
other => panic!("unexpected reply message: {:?}", other),
}
server_handle.read_task.abort();
client_handle.read_task.abort();
}
/// HDLC streaming: feed partial frames and verify correct reassembly.
#[test]
fn test_hdlc_streaming_partial_feeds() {
let mut deframer = hdlc::HdlcDeframer::new();
let data1 = b"packet one";
let data2 = b"packet two";
let framed1 = hdlc::frame(data1);
let framed2 = hdlc::frame(data2);
let mut combined = Vec::new();
combined.extend_from_slice(&framed1);
combined.extend_from_slice(&framed2);
let mut all_frames = Vec::new();
for &b in &combined {
all_frames.extend(deframer.feed(&[b]));
}
assert_eq!(all_frames.len(), 2);
assert_eq!(all_frames[0], data1);
assert_eq!(all_frames[1], data2);
}
/// TCP reconnection: client retries after connection failure.
#[tokio::test]
async fn test_tcp_client_reconnection_max_tries() {
let (transport_tx, _transport_rx) = mpsc::channel::<TransportMessage>(8);
// Port 1 is closed, forcing every connect to fail.
let config = TcpClientConfig {
name: "reconnect-test".into(),
target_host: "127.0.0.1".into(),
target_port: 1,
kiss_framing: false,
connect_timeout_secs: 1,
max_reconnect_tries: Some(2),
mode: InterfaceMode::Full,
};
let handle = spawn_tcp_client(config, 99, transport_tx, None)
.await
.unwrap();
// Two failed tries with 5s waits each; 20s headroom.
let result =
tokio::time::timeout(std::time::Duration::from_secs(20), handle.read_task).await;
assert!(result.is_ok(), "task should have finished within timeout");
}
/// Server's per-client read_task must DeregisterInterface on EOF
/// so transport stops targeting the dead tx channel.
#[tokio::test]
async fn test_tcp_server_deregisters_on_client_disconnect() {
let (transport_tx, mut transport_rx) = mpsc::channel::<TransportMessage>(64);
let (handle_tx, mut handle_rx) = mpsc::channel::<InterfaceHandle>(8);
let id_gen = Arc::new(AtomicU64::new(800));
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
drop(listener);
let mut server_cfg = TcpServerConfig::new("dereg-server", "127.0.0.1", 0);
server_cfg.listen_port = port;
let server_handle =
spawn_tcp_server(server_cfg, 88, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
let client_cfg = TcpClientConfig {
name: "dereg-client".into(),
target_host: "127.0.0.1".into(),
target_port: port,
kiss_framing: false,
connect_timeout_secs: 5,
max_reconnect_tries: Some(1),
mode: InterfaceMode::Full,
};
let client_handle = spawn_tcp_client(client_cfg, 321, transport_tx.clone(), None)
.await
.unwrap();
let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for accepted handle")
.expect("handle channel closed");
let server_side_client_id = accepted.id;
// Abort client-side tasks; server's per-client reader sees EOF and exits.
client_handle.read_task.abort();
drop(client_handle.tx);
let mut saw_dereg = false;
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(3);
while tokio::time::Instant::now() < deadline {
match tokio::time::timeout(std::time::Duration::from_millis(500), transport_rx.recv())
.await
{
Ok(Some(TransportMessage::DeregisterInterface { id }))
if id == server_side_client_id =>
{
saw_dereg = true;
break;
}
Ok(Some(_)) => continue,
Ok(None) => break,
Err(_) => continue,
}
}
assert!(
saw_dereg,
"server must emit DeregisterInterface for disconnected client id {server_side_client_id}"
);
server_handle.read_task.abort();
}
}
+244
View File
@@ -0,0 +1,244 @@
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64};
use bytes::Bytes;
use tokio::sync::mpsc;
pub type InterfaceId = u64;
/// Handle returned by every `spawn_*`: write channel, status flag, and read task.
pub struct InterfaceHandle {
pub id: InterfaceId,
pub name: String,
pub mode: InterfaceMode,
pub direction: InterfaceDirection,
pub bitrate: u64,
pub mtu: u32,
pub online: Arc<AtomicBool>,
pub rxb: Option<Arc<AtomicU64>>,
pub txb: Option<Arc<AtomicU64>>,
pub tx: mpsc::Sender<Bytes>,
pub read_task: tokio::task::JoinHandle<()>,
}
/// Optional per-interface IFAC (Interface Authentication Code) configuration.
pub struct IfacConfig {
pub ifac_key: [u8; 64],
pub ifac_size: usize,
}
/// Interface operating mode. Byte values are on-wire constants.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
#[derive(Default)]
pub enum InterfaceMode {
#[default]
Full = 0x01,
PointToPoint = 0x02,
AccessPoint = 0x03,
Roaming = 0x04,
Boundary = 0x05,
Gateway = 0x06,
}
pub const MODE_FULL: InterfaceMode = InterfaceMode::Full;
pub const MODE_POINT_TO_POINT: InterfaceMode = InterfaceMode::PointToPoint;
/// Modes for which a Transport Node actively discovers paths.
pub const DISCOVER_PATHS_FOR: &[InterfaceMode] = &[
InterfaceMode::AccessPoint,
InterfaceMode::Gateway,
InterfaceMode::Roaming,
];
impl InterfaceMode {
pub fn from_u8(val: u8) -> Option<Self> {
match val {
0x01 => Some(Self::Full),
0x02 => Some(Self::PointToPoint),
0x03 => Some(Self::AccessPoint),
0x04 => Some(Self::Roaming),
0x05 => Some(Self::Boundary),
0x06 => Some(Self::Gateway),
_ => None,
}
}
}
/// Interface direction flags.
#[derive(Debug, Clone, Copy, Default)]
pub struct InterfaceDirection {
pub inbound: bool,
pub outbound: bool,
pub forward: bool,
pub repeat: bool,
}
/// Interface statistics.
#[derive(Debug, Clone, Default)]
pub struct InterfaceStats {
pub rx_bytes: u64,
pub tx_bytes: u64,
pub rx_packets: u64,
pub tx_packets: u64,
pub online: bool,
pub bitrate: u64,
pub mtu: u32,
}
/// Base trait for all network interfaces.
pub trait Interface: Send + Sync {
fn process_incoming(&self, data: &[u8]);
fn process_outgoing(&self, data: &[u8]) -> Result<(), InterfaceError>;
fn get_stats(&self) -> InterfaceStats;
fn detach(&mut self);
fn name(&self) -> &str;
fn mode(&self) -> InterfaceMode;
/// Interface bitrate in bits/sec.
fn bitrate(&self) -> u64;
fn mtu(&self) -> u32 {
rns_wire::constants::MTU as u32
}
fn online(&self) -> bool;
/// 16-byte interface identifier: truncated SHA-256 of the interface name.
fn get_hash(&self) -> [u8; 16] {
let full = rns_crypto::sha::full_hash(self.name().as_bytes());
let mut h = [0u8; 16];
h.copy_from_slice(&full[..16]);
h
}
}
/// Select an MTU for the given bitrate; `None` below 62.5 kbps minimum.
pub fn optimise_mtu(bitrate: u64) -> Option<u32> {
if bitrate >= 1_000_000_000 {
Some(524_288)
} else if bitrate > 750_000_000 {
Some(262_144)
} else if bitrate > 400_000_000 {
Some(131_072)
} else if bitrate > 200_000_000 {
Some(65_536)
} else if bitrate > 100_000_000 {
Some(32_768)
} else if bitrate > 10_000_000 {
Some(16_384)
} else if bitrate > 5_000_000 {
Some(8_192)
} else if bitrate > 2_000_000 {
Some(4_096)
} else if bitrate > 1_000_000 {
Some(2_048)
} else if bitrate > 62_500 {
Some(1_024)
} else {
None
}
}
/// Length of interface name hash (80 bits / 10 bytes).
pub const NAME_HASH_LENGTH: usize = 10;
// Ingress control constants — must match Reticulum reference.
pub const IA_FREQ_SAMPLES: usize = 6;
pub const OA_FREQ_SAMPLES: usize = 6;
pub const MAX_HELD_ANNOUNCES: usize = 256;
/// Duration a new interface stays in "new" state (seconds).
pub const IC_NEW_TIME: f64 = 7200.0;
/// Burst threshold for new interfaces (announces/sec).
pub const IC_BURST_FREQ_NEW: f64 = 3.5;
/// Burst threshold for established interfaces (announces/sec).
pub const IC_BURST_FREQ: f64 = 12.0;
/// Burst detection window duration (seconds).
pub const IC_BURST_HOLD: f64 = 60.0;
/// Penalty duration after a detected burst (seconds).
pub const IC_BURST_PENALTY: f64 = 300.0;
/// Interval between released held announces (seconds).
pub const IC_HELD_RELEASE_INTERVAL: f64 = 30.0;
#[derive(Debug, thiserror::Error)]
pub enum InterfaceError {
#[error("interface offline")]
Offline,
#[error("send failed: {0}")]
SendFailed(String),
#[error("interface detached")]
Detached,
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_optimise_mtu() {
assert_eq!(optimise_mtu(1_000_000_000), Some(524_288));
assert_eq!(optimise_mtu(100_000_001), Some(32_768));
assert_eq!(optimise_mtu(10_000_001), Some(16_384));
assert_eq!(optimise_mtu(62_500), None);
assert_eq!(optimise_mtu(62_501), Some(1_024));
}
#[test]
fn test_interface_mode_repr() {
assert_eq!(InterfaceMode::Full as u8, 0x01);
assert_eq!(InterfaceMode::PointToPoint as u8, 0x02);
assert_eq!(InterfaceMode::AccessPoint as u8, 0x03);
assert_eq!(InterfaceMode::Roaming as u8, 0x04);
assert_eq!(InterfaceMode::Boundary as u8, 0x05);
assert_eq!(InterfaceMode::Gateway as u8, 0x06);
}
#[test]
fn test_interface_mode_from_u8() {
assert_eq!(InterfaceMode::from_u8(0x01), Some(InterfaceMode::Full));
assert_eq!(
InterfaceMode::from_u8(0x02),
Some(InterfaceMode::PointToPoint)
);
assert_eq!(InterfaceMode::from_u8(0x06), Some(InterfaceMode::Gateway));
assert_eq!(InterfaceMode::from_u8(0x00), None);
assert_eq!(InterfaceMode::from_u8(0xFF), None);
}
#[test]
fn test_mode_aliases() {
assert_eq!(MODE_FULL, InterfaceMode::Full);
assert_eq!(MODE_POINT_TO_POINT, InterfaceMode::PointToPoint);
}
#[test]
fn test_discover_paths_for() {
assert!(DISCOVER_PATHS_FOR.contains(&InterfaceMode::AccessPoint));
assert!(DISCOVER_PATHS_FOR.contains(&InterfaceMode::Gateway));
assert!(DISCOVER_PATHS_FOR.contains(&InterfaceMode::Roaming));
assert!(!DISCOVER_PATHS_FOR.contains(&InterfaceMode::Full));
}
#[test]
fn test_name_hash_length() {
assert_eq!(NAME_HASH_LENGTH, 10);
assert_eq!(NAME_HASH_LENGTH * 8, 80);
}
#[test]
fn test_ingress_control_constants() {
assert_eq!(IC_BURST_FREQ, 12.0);
assert_eq!(IC_BURST_FREQ_NEW, 3.5);
assert_eq!(IC_BURST_HOLD, 60.0);
assert_eq!(IC_BURST_PENALTY, 300.0);
assert_eq!(IC_NEW_TIME, 7200.0);
assert_eq!(IC_HELD_RELEASE_INTERVAL, 30.0);
}
}
+286
View File
@@ -0,0 +1,286 @@
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use bytes::Bytes;
use tokio::net::UdpSocket;
use tokio::sync::mpsc;
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
use rns_transport::messages::{InboundPacket, TransportMessage};
pub const HW_MTU: u32 = 1064;
#[derive(Debug, Clone)]
pub struct UdpInterfaceConfig {
pub name: String,
pub listen_ip: Option<String>,
pub listen_port: Option<u16>,
pub forward_ip: Option<String>,
pub forward_port: Option<u16>,
pub device: Option<String>,
pub mode: InterfaceMode,
}
impl UdpInterfaceConfig {
pub fn new(name: &str) -> Self {
Self {
name: name.to_string(),
listen_ip: None,
listen_port: None,
forward_ip: None,
forward_port: None,
device: None,
mode: InterfaceMode::Full,
}
}
pub fn listen(mut self, ip: &str, port: u16) -> Self {
self.listen_ip = Some(ip.to_string());
self.listen_port = Some(port);
self
}
pub fn forward(mut self, ip: &str, port: u16) -> Self {
self.forward_ip = Some(ip.to_string());
self.forward_port = Some(port);
self
}
}
/// Spawn a UDP interface — datagrams are unframed (1 send/recv = 1 packet).
pub async fn spawn_udp_interface(
config: UdpInterfaceConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let listen_ip = config.listen_ip.as_deref().unwrap_or("0.0.0.0");
let listen_port = config.listen_port.unwrap_or(0);
let bind_addr = format!("{}:{}", listen_ip, listen_port);
let socket = Arc::new(UdpSocket::bind(&bind_addr).await?);
// Needed for directed broadcasts (255.255.255.255).
socket.set_broadcast(true)?;
let local_addr = socket.local_addr()?;
tracing::info!(name = %config.name, addr = %local_addr, "UDP interface bound");
let online = Arc::new(AtomicBool::new(true));
let online2 = online.clone();
let (tx, mut rx) = mpsc::channel::<Bytes>(256);
let name = config.name.clone();
let mode = config.mode;
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let task_rxb = shared_rxb.clone();
let task_txb = shared_txb.clone();
let forward_addr: Option<SocketAddr> = match (&config.forward_ip, config.forward_port) {
(Some(ip), Some(port)) => {
let addr_str = format!("{}:{}", ip, port);
match addr_str.parse() {
Ok(a) => Some(a),
Err(e) => {
tracing::warn!(error = %e, "invalid forward address, trying DNS");
tokio::net::lookup_host(&addr_str)
.await
.ok()
.and_then(|mut addrs| addrs.next())
}
}
}
_ => None,
};
let socket_w = socket.clone();
tokio::spawn(async move {
while let Some(data) = rx.recv().await {
if let Some(addr) = forward_addr {
let len = data.len();
if let Err(e) = socket_w.send_to(&data, addr).await {
tracing::warn!(error = %e, "UDP send_to failed");
} else {
task_txb.fetch_add(len as u64, Ordering::Relaxed);
}
} else {
tracing::debug!("UDP write: no forward address configured, dropping packet");
}
}
});
let read_task = tokio::spawn(async move {
let mut buf = [0u8; 2048];
loop {
match socket.recv_from(&mut buf).await {
Ok((n, src)) => {
if n == 0 {
continue;
}
task_rxb.fetch_add(n as u64, Ordering::Relaxed);
let raw = Bytes::copy_from_slice(&buf[..n]);
tracing::debug!(
interface_id = id,
from = %src,
len = n,
"UDP read: received packet"
);
let msg = TransportMessage::Inbound(InboundPacket {
raw,
interface_id: id,
rssi: None,
snr: None,
q: None,
});
if transport_tx.send(msg).await.is_err() {
tracing::warn!(id, "transport channel closed");
break;
}
}
Err(e) => {
tracing::warn!(error = %e, "UDP recv_from error");
break;
}
}
}
online2.store(false, Ordering::SeqCst);
});
Ok(InterfaceHandle {
id,
name,
mode,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: 10_000_000,
mtu: HW_MTU,
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
tx,
read_task,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_udp_config() {
let config = UdpInterfaceConfig::new("udp0")
.listen("0.0.0.0", 4242)
.forward("192.168.1.1", 4243);
assert_eq!(config.listen_ip.as_deref(), Some("0.0.0.0"));
assert_eq!(config.listen_port, Some(4242));
assert_eq!(config.forward_ip.as_deref(), Some("192.168.1.1"));
assert_eq!(config.forward_port, Some(4243));
}
#[test]
fn test_hw_mtu() {
assert_eq!(HW_MTU, 1064);
}
#[test]
fn test_udp_config_defaults() {
let cfg = UdpInterfaceConfig::new("udp0");
assert_eq!(cfg.name, "udp0");
assert!(cfg.listen_ip.is_none());
assert!(cfg.listen_port.is_none());
assert!(cfg.forward_ip.is_none());
assert!(cfg.forward_port.is_none());
assert_eq!(cfg.mode, InterfaceMode::Full);
}
#[test]
fn test_udp_config_listen_only() {
let cfg = UdpInterfaceConfig::new("udp-rx").listen("0.0.0.0", 5555);
assert_eq!(cfg.listen_ip.as_deref(), Some("0.0.0.0"));
assert_eq!(cfg.listen_port, Some(5555));
assert!(cfg.forward_ip.is_none());
assert!(cfg.forward_port.is_none());
}
#[test]
fn test_udp_config_builder_chain() {
let cfg = UdpInterfaceConfig::new("udp-bidir")
.listen("0.0.0.0", 4242)
.forward("10.0.0.1", 6666);
assert_eq!(cfg.listen_ip.as_deref(), Some("0.0.0.0"));
assert_eq!(cfg.listen_port, Some(4242));
assert_eq!(cfg.forward_ip.as_deref(), Some("10.0.0.1"));
assert_eq!(cfg.forward_port, Some(6666));
}
#[tokio::test]
async fn test_udp_loopback() {
let (transport_tx, mut transport_rx) = mpsc::channel::<TransportMessage>(64);
let cfg_a = UdpInterfaceConfig::new("udp-a").listen("127.0.0.1", 0);
let handle_a = spawn_udp_interface(cfg_a, 10, transport_tx.clone())
.await
.unwrap();
// Reserve two free ports via bind-drop; handle doesn't expose its addr.
let sock_tmp1 = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let port_a = sock_tmp1.local_addr().unwrap().port();
let sock_tmp2 = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let port_b = sock_tmp2.local_addr().unwrap().port();
drop(sock_tmp1);
drop(sock_tmp2);
handle_a.read_task.abort();
let cfg_a = UdpInterfaceConfig::new("udp-a")
.listen("127.0.0.1", port_a)
.forward("127.0.0.1", port_b);
let cfg_b = UdpInterfaceConfig::new("udp-b")
.listen("127.0.0.1", port_b)
.forward("127.0.0.1", port_a);
let handle_a = spawn_udp_interface(cfg_a, 10, transport_tx.clone())
.await
.unwrap();
let handle_b = spawn_udp_interface(cfg_b, 20, transport_tx.clone())
.await
.unwrap();
// A → B's listen port; inbound carries B's interface_id (20).
let payload = Bytes::from_static(b"udp test data");
handle_a.tx.send(payload.clone()).await.unwrap();
let msg = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv())
.await
.expect("timeout")
.expect("channel closed");
match msg {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, payload);
assert_eq!(pkt.interface_id, 20);
}
other => panic!("unexpected: {:?}", other),
}
let reply = Bytes::from_static(b"udp reply");
handle_b.tx.send(reply.clone()).await.unwrap();
let msg2 = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv())
.await
.expect("timeout")
.expect("channel closed");
match msg2 {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, reply);
assert_eq!(pkt.interface_id, 10);
}
other => panic!("unexpected: {:?}", other),
}
handle_a.read_task.abort();
handle_b.read_task.abort();
}
}
+491
View File
@@ -0,0 +1,491 @@
//! Weave switching fabric — protocol primitives only.
//!
//! Wire format (WDCL inside HDLC):
//! ```text
//! [HDLC_FLAG] [escaped WDCL] [HDLC_FLAG]
//! WDCL = [ADDR u32][TYPE u8][PAYLOAD…] ADDR 0xFFFFFFFF = broadcast
//! ```
//! Discovery: Ed25519 challenge-response over WDCL_T_DISCOVER / WDCL_T_CONNECT.
//! Runtime spawn (serial I/O, peer mgmt) not yet wired up.
use crate::traits::InterfaceMode;
pub const WDCL_T_DISCOVER: u8 = 0x00;
pub const WDCL_T_CONNECT: u8 = 0x01;
pub const WDCL_T_CMD: u8 = 0x02;
pub const WDCL_T_LOG: u8 = 0x03;
pub const WDCL_T_DISP: u8 = 0x04;
pub const WDCL_T_ENDPOINT_PKT: u8 = 0x05;
pub const WDCL_T_ENCAP_PROTO: u8 = 0x06;
pub const WDCL_BROADCAST: [u8; 4] = [0xFF, 0xFF, 0xFF, 0xFF];
pub const WDCL_HANDSHAKE_TIMEOUT: f64 = 2.0;
/// WDCL header = `ADDR(4) + TYPE(1)`.
pub const HEADER_MINSIZE: usize = 5;
pub const SWITCH_ID_LEN: usize = 4;
pub const ENDPOINT_ID_LEN: usize = 8;
pub const FLOWSEQ_LEN: usize = 2;
pub const HMAC_LEN: usize = 8;
pub const AUTH_LEN: usize = ENDPOINT_ID_LEN + HMAC_LEN;
pub const PUBKEY_SIZE: usize = 32;
pub const PRVKEY_SIZE: usize = 64;
pub const SIGNATURE_LEN: usize = 64;
pub const HW_MTU: u32 = 1024;
pub const FIXED_MTU: bool = true;
pub const DEFAULT_IFAC_SIZE: usize = 16;
pub const PEERING_TIMEOUT: f64 = 20.0;
pub const BITRATE_GUESS: u64 = 250_000;
pub const MULTI_IF_DEQUE_LEN: usize = 48;
pub const MULTI_IF_DEQUE_TTL: f64 = 0.75;
pub const STATLEN_MAX: usize = 120;
pub const STAT_UPDATE_THROTTLE: f64 = 0.5;
pub const ENDPOINT_QUEUE_LEN: usize = 1024;
pub const CMD_ENDPOINT_PKT: u16 = 0x0001;
pub const CMD_ENDPOINTS_LIST: u16 = 0x0100;
pub const CMD_REMOTE_DISPLAY: u16 = 0x0A00;
pub const CMD_REMOTE_INPUT: u16 = 0x0A01;
// LOG frame payload: [flags u8][ts_ms u32 BE][level u8][event u16 BE][data…]
pub const EVT_MSG: u16 = 0x0000;
pub const EVT_SYSTEM_BOOT: u16 = 0x0001;
pub const EVT_CORE_INIT: u16 = 0x0002;
// Driver events (0x1xxx)
pub const EVT_DRV_UART_INIT: u16 = 0x1000;
pub const EVT_DRV_USB_CDC_INIT: u16 = 0x1010;
pub const EVT_DRV_USB_CDC_HOST_AVAIL: u16 = 0x1011;
pub const EVT_DRV_USB_CDC_HOST_SUSPEND: u16 = 0x1012;
pub const EVT_DRV_USB_CDC_HOST_RESUME: u16 = 0x1013;
pub const EVT_DRV_USB_CDC_CONNECTED: u16 = 0x1014;
pub const EVT_DRV_USB_CDC_READ_ERR: u16 = 0x1015;
pub const EVT_DRV_USB_CDC_OVERFLOW: u16 = 0x1016;
pub const EVT_DRV_USB_CDC_DROPPED: u16 = 0x1017;
pub const EVT_DRV_USB_CDC_TX_TIMEOUT: u16 = 0x1018;
pub const EVT_DRV_I2C_INIT: u16 = 0x1020;
pub const EVT_DRV_NVS_INIT: u16 = 0x1030;
pub const EVT_DRV_NVS_ERASE: u16 = 0x1031;
pub const EVT_DRV_CRYPTO_INIT: u16 = 0x1040;
pub const EVT_DRV_DISPLAY_INIT: u16 = 0x1050;
pub const EVT_DRV_DISPLAY_BUS_AVAILABLE: u16 = 0x1051;
pub const EVT_DRV_DISPLAY_IO_CONFIGURED: u16 = 0x1052;
pub const EVT_DRV_DISPLAY_PANEL_CREATED: u16 = 0x1053;
pub const EVT_DRV_DISPLAY_PANEL_RESET: u16 = 0x1054;
pub const EVT_DRV_DISPLAY_PANEL_INIT: u16 = 0x1055;
pub const EVT_DRV_DISPLAY_PANEL_ENABLE: u16 = 0x1056;
pub const EVT_DRV_DISPLAY_REMOTE_ENABLE: u16 = 0x1057;
pub const EVT_DRV_W80211_INIT: u16 = 0x1060;
pub const EVT_DRV_W80211_CHANNEL: u16 = 0x1062;
pub const EVT_DRV_W80211_POWER: u16 = 0x1063;
// Kernel events (0x2xxx)
pub const EVT_KRN_LOGGER_INIT: u16 = 0x2000;
pub const EVT_KRN_LOGGER_OUTPUT: u16 = 0x2001;
pub const EVT_KRN_UI_INIT: u16 = 0x2010;
// Protocol events (0x3xxx)
pub const EVT_PROTO_WDCL_INIT: u16 = 0x3000;
pub const EVT_PROTO_WDCL_RUNNING: u16 = 0x3001;
pub const EVT_PROTO_WDCL_CONNECTION: u16 = 0x3002;
pub const EVT_PROTO_WDCL_HOST_ENDPOINT: u16 = 0x3003;
pub const EVT_PROTO_WEAVE_INIT: u16 = 0x3100;
pub const EVT_PROTO_WEAVE_RUNNING: u16 = 0x3101;
pub const EVT_PROTO_WEAVE_EP_ALIVE: u16 = 0x3102;
pub const EVT_PROTO_WEAVE_EP_TIMEOUT: u16 = 0x3103;
pub const EVT_PROTO_WEAVE_EP_VIA: u16 = 0x3104;
// Service events
pub const EVT_SRVCTL_REMOTE_DISPLAY: u16 = 0xA000;
pub const EVT_INTERFACE_REGISTERED: u16 = 0xD000;
// Stats events (0xExxx)
pub const EVT_STAT_STATE: u16 = 0xE000;
pub const EVT_STAT_UPTIME: u16 = 0xE001;
pub const EVT_STAT_TIMEBASE: u16 = 0xE002;
pub const EVT_STAT_CPU: u16 = 0xE003;
pub const EVT_STAT_TASK_CPU: u16 = 0xE004;
pub const EVT_STAT_MEMORY: u16 = 0xE005;
pub const EVT_STAT_STORAGE: u16 = 0xE006;
// Error events
pub const EVT_SYSERR_MEM_EXHAUSTED: u16 = 0xF000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum PhysicalMedium {
Usb = 0x01,
Uart = 0x02,
W80211 = 0x03,
Ble = 0x04,
Lora = 0x05,
Ethernet = 0x06,
Wifi = 0x07,
Tcp = 0x08,
Udp = 0x09,
Ir = 0x0A,
Afsk = 0x0B,
Gpio = 0x0C,
Spi = 0x0D,
I2c = 0x0E,
Can = 0x0F,
Dma = 0x10,
}
impl PhysicalMedium {
pub fn from_u8(val: u8) -> Option<Self> {
match val {
0x01 => Some(Self::Usb),
0x02 => Some(Self::Uart),
0x03 => Some(Self::W80211),
0x04 => Some(Self::Ble),
0x05 => Some(Self::Lora),
0x06 => Some(Self::Ethernet),
0x07 => Some(Self::Wifi),
0x08 => Some(Self::Tcp),
0x09 => Some(Self::Udp),
0x0A => Some(Self::Ir),
0x0B => Some(Self::Afsk),
0x0C => Some(Self::Gpio),
0x0D => Some(Self::Spi),
0x0E => Some(Self::I2c),
0x0F => Some(Self::Can),
0x10 => Some(Self::Dma),
_ => None,
}
}
pub fn short_name(self) -> &'static str {
match self {
Self::Usb => "usb",
Self::Uart => "uart",
Self::W80211 => "mw",
Self::Ble => "ble",
Self::Lora => "lora",
Self::Ethernet => "eth",
Self::Wifi => "wifi",
Self::Tcp => "tcp",
Self::Udp => "udp",
Self::Ir => "ir",
Self::Afsk => "afsk",
Self::Gpio => "gpio",
Self::Spi => "spi",
Self::I2c => "i2c",
Self::Can => "can",
Self::Dma => "dma",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum DeviceLogLevel {
Force = 0,
Critical = 1,
Error = 2,
Warning = 3,
Notice = 4,
Info = 5,
Verbose = 6,
Debug = 7,
Extreme = 8,
System = 9,
}
impl DeviceLogLevel {
pub fn from_u8(val: u8) -> Option<Self> {
match val {
0 => Some(Self::Force),
1 => Some(Self::Critical),
2 => Some(Self::Error),
3 => Some(Self::Warning),
4 => Some(Self::Notice),
5 => Some(Self::Info),
6 => Some(Self::Verbose),
7 => Some(Self::Debug),
8 => Some(Self::Extreme),
9 => Some(Self::System),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WdclFrame {
pub addr: [u8; 4],
pub msg_type: u8,
pub payload: Vec<u8>,
}
pub fn wdcl_frame(addr: [u8; 4], msg_type: u8, payload: &[u8]) -> Vec<u8> {
let mut frame = Vec::with_capacity(HEADER_MINSIZE + payload.len());
frame.extend_from_slice(&addr);
frame.push(msg_type);
frame.extend_from_slice(payload);
frame
}
/// Parse WDCL after HDLC deframing; `None` if shorter than `HEADER_MINSIZE`.
pub fn wdcl_parse(data: &[u8]) -> Option<WdclFrame> {
if data.len() < HEADER_MINSIZE {
return None;
}
let mut addr = [0u8; 4];
addr.copy_from_slice(&data[..4]);
Some(WdclFrame {
addr,
msg_type: data[4],
payload: data[5..].to_vec(),
})
}
/// `WDCL_T_CMD` with big-endian u16 command ID prefix.
pub fn wdcl_command(dest: [u8; 4], command: u16, data: &[u8]) -> Vec<u8> {
let mut payload = Vec::with_capacity(2 + data.len());
payload.push((command >> 8) as u8);
payload.push((command & 0xFF) as u8);
payload.extend_from_slice(data);
wdcl_frame(dest, WDCL_T_CMD, &payload)
}
#[derive(Debug, Clone)]
pub struct LogFrame {
/// Milliseconds since device boot.
pub timestamp_ms: u32,
pub level: u8,
pub event: u16,
pub data: Vec<u8>,
}
pub fn parse_log_frame(payload: &[u8]) -> Option<LogFrame> {
if payload.len() < 8 {
return None;
}
let _flags = payload[0];
let timestamp_ms = u32::from_be_bytes([payload[1], payload[2], payload[3], payload[4]]);
let level = payload[5];
let event = u16::from_be_bytes([payload[6], payload[7]]);
let data = payload[8..].to_vec();
Some(LogFrame {
timestamp_ms,
level,
event,
data,
})
}
/// Weave interface config (runtime spawn not yet implemented).
#[derive(Debug, Clone)]
pub struct WeaveInterfaceConfig {
pub name: String,
pub port: String,
pub configured_bitrate: Option<u64>,
pub mode: InterfaceMode,
}
impl WeaveInterfaceConfig {
pub fn new(name: &str, port: &str) -> Self {
Self {
name: name.to_string(),
port: port.to_string(),
configured_bitrate: None,
mode: InterfaceMode::Full,
}
}
}
// Runtime spawn is not wired yet. A production path needs WDCL discovery and
// handshake over serial, Ed25519 verification, per-peer sub-interfaces with
// PEERING_TIMEOUT/MULTI_IF_DEQUE_*, and interface_factory wiring.
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_wdcl_message_types() {
assert_eq!(WDCL_T_DISCOVER, 0x00);
assert_eq!(WDCL_T_CONNECT, 0x01);
assert_eq!(WDCL_T_CMD, 0x02);
assert_eq!(WDCL_T_LOG, 0x03);
assert_eq!(WDCL_T_DISP, 0x04);
assert_eq!(WDCL_T_ENDPOINT_PKT, 0x05);
assert_eq!(WDCL_T_ENCAP_PROTO, 0x06);
}
#[test]
fn test_wdcl_broadcast() {
assert_eq!(WDCL_BROADCAST, [0xFF, 0xFF, 0xFF, 0xFF]);
}
#[test]
fn test_header_minsize() {
assert_eq!(HEADER_MINSIZE, 5);
}
#[test]
fn test_weave_constants() {
assert_eq!(HW_MTU, 1024);
const { assert!(FIXED_MTU) };
assert_eq!(PEERING_TIMEOUT, 20.0);
assert_eq!(BITRATE_GUESS, 250_000);
assert_eq!(DEFAULT_IFAC_SIZE, 16);
}
#[test]
fn test_identity_sizes() {
assert_eq!(SWITCH_ID_LEN, 4);
assert_eq!(ENDPOINT_ID_LEN, 8);
assert_eq!(PUBKEY_SIZE, 32);
assert_eq!(SIGNATURE_LEN, 64);
assert_eq!(AUTH_LEN, ENDPOINT_ID_LEN + HMAC_LEN);
}
#[test]
fn test_dedup_constants() {
assert_eq!(MULTI_IF_DEQUE_LEN, 48);
assert_eq!(MULTI_IF_DEQUE_TTL, 0.75);
}
#[test]
fn test_wdcl_frame_encode() {
let frame = wdcl_frame([0x01, 0x02, 0x03, 0x04], WDCL_T_ENDPOINT_PKT, b"hello");
assert_eq!(frame.len(), 10);
assert_eq!(&frame[..4], &[0x01, 0x02, 0x03, 0x04]);
assert_eq!(frame[4], WDCL_T_ENDPOINT_PKT);
assert_eq!(&frame[5..], b"hello");
}
#[test]
fn test_wdcl_frame_broadcast() {
let frame = wdcl_frame(WDCL_BROADCAST, WDCL_T_DISCOVER, &[0xAA]);
assert_eq!(&frame[..4], &WDCL_BROADCAST);
assert_eq!(frame[4], WDCL_T_DISCOVER);
assert_eq!(&frame[5..], &[0xAA]);
}
#[test]
fn test_wdcl_frame_empty_payload() {
let frame = wdcl_frame([0; 4], WDCL_T_CMD, &[]);
assert_eq!(frame.len(), 5);
}
#[test]
fn test_wdcl_parse_valid() {
let raw = [0x0A, 0x0B, 0x0C, 0x0D, WDCL_T_LOG, 0x01, 0x02];
let parsed = wdcl_parse(&raw).unwrap();
assert_eq!(parsed.addr, [0x0A, 0x0B, 0x0C, 0x0D]);
assert_eq!(parsed.msg_type, WDCL_T_LOG);
assert_eq!(parsed.payload, vec![0x01, 0x02]);
}
#[test]
fn test_wdcl_parse_minimum() {
let raw = [0x00, 0x00, 0x00, 0x00, WDCL_T_DISCOVER];
let parsed = wdcl_parse(&raw).unwrap();
assert_eq!(parsed.addr, [0; 4]);
assert_eq!(parsed.msg_type, WDCL_T_DISCOVER);
assert!(parsed.payload.is_empty());
}
#[test]
fn test_wdcl_parse_too_short() {
assert!(wdcl_parse(&[]).is_none());
assert!(wdcl_parse(&[0x00]).is_none());
assert!(wdcl_parse(&[0x00, 0x00, 0x00, 0x00]).is_none());
}
#[test]
fn test_wdcl_frame_roundtrip() {
let addr = [0xDE, 0xAD, 0xBE, 0xEF];
let payload = b"test data";
let encoded = wdcl_frame(addr, WDCL_T_ENDPOINT_PKT, payload);
let decoded = wdcl_parse(&encoded).unwrap();
assert_eq!(decoded.addr, addr);
assert_eq!(decoded.msg_type, WDCL_T_ENDPOINT_PKT);
assert_eq!(decoded.payload, payload);
}
#[test]
fn test_wdcl_command() {
let dest = [0x01, 0x02, 0x03, 0x04];
let frame = wdcl_command(dest, CMD_ENDPOINT_PKT, &[0xFF]);
let parsed = wdcl_parse(&frame).unwrap();
assert_eq!(parsed.msg_type, WDCL_T_CMD);
assert_eq!(parsed.payload, vec![0x00, 0x01, 0xFF]);
}
#[test]
fn test_wdcl_command_remote_display() {
let frame = wdcl_command([0; 4], CMD_REMOTE_DISPLAY, &[0x01]);
let parsed = wdcl_parse(&frame).unwrap();
assert_eq!(parsed.payload[0], 0x0A);
assert_eq!(parsed.payload[1], 0x00);
assert_eq!(parsed.payload[2], 0x01);
}
#[test]
fn test_parse_log_frame() {
// flags=0, ts=1000ms, level=INFO, event=EVT_SYSTEM_BOOT, data="ok"
let payload = [0x00, 0x00, 0x00, 0x03, 0xE8, 0x05, 0x00, 0x01, b'o', b'k'];
let frame = parse_log_frame(&payload).unwrap();
assert_eq!(frame.timestamp_ms, 1000);
assert_eq!(frame.level, 5);
assert_eq!(frame.event, EVT_SYSTEM_BOOT);
assert_eq!(frame.data, b"ok");
}
#[test]
fn test_parse_log_frame_too_short() {
assert!(parse_log_frame(&[0; 7]).is_none());
assert!(parse_log_frame(&[]).is_none());
}
#[test]
fn test_parse_log_frame_no_data() {
let payload = [0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x30, 0x00];
let frame = parse_log_frame(&payload).unwrap();
assert_eq!(frame.event, EVT_PROTO_WDCL_INIT);
assert!(frame.data.is_empty());
}
#[test]
fn test_physical_medium_from_u8() {
assert_eq!(PhysicalMedium::from_u8(0x03), Some(PhysicalMedium::W80211));
assert_eq!(PhysicalMedium::from_u8(0x05), Some(PhysicalMedium::Lora));
assert_eq!(PhysicalMedium::from_u8(0x10), Some(PhysicalMedium::Dma));
assert_eq!(PhysicalMedium::from_u8(0x00), None);
assert_eq!(PhysicalMedium::from_u8(0xFF), None);
}
#[test]
fn test_physical_medium_short_name() {
assert_eq!(PhysicalMedium::W80211.short_name(), "mw");
assert_eq!(PhysicalMedium::Lora.short_name(), "lora");
assert_eq!(PhysicalMedium::Ethernet.short_name(), "eth");
}
#[test]
fn test_device_log_level() {
assert_eq!(DeviceLogLevel::from_u8(0), Some(DeviceLogLevel::Force));
assert_eq!(DeviceLogLevel::from_u8(5), Some(DeviceLogLevel::Info));
assert_eq!(DeviceLogLevel::from_u8(9), Some(DeviceLogLevel::System));
assert_eq!(DeviceLogLevel::from_u8(10), None);
}
#[test]
fn test_config_defaults() {
let cfg = WeaveInterfaceConfig::new("weave0", "/dev/ttyUSB0");
assert_eq!(cfg.name, "weave0");
assert_eq!(cfg.port, "/dev/ttyUSB0");
assert_eq!(cfg.mode, InterfaceMode::Full);
assert!(cfg.configured_bitrate.is_none());
}
}
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "rns-link"
description = "Link layer and encrypted channel for Reticulum"
version.workspace = true
edition.workspace = true
license.workspace = true
[features]
default = ["std"]
std = ["rns-crypto/std", "rns-wire/std"]
[dependencies]
rns-crypto = { workspace = true }
rns-wire = { workspace = true }
rns-identity = { workspace = true }
thiserror = { workspace = true }
zeroize = { workspace = true }
rmpv = { workspace = true }
rand = { workspace = true }
tracing = { workspace = true }
hex = { workspace = true }
[dev-dependencies]
proptest = { workspace = true }
+99
View File
@@ -0,0 +1,99 @@
//! Link-level protocol constants.
/// X25519 public key size in bytes.
pub const KEYSIZE: usize = 32;
/// Combined ephemeral public key size: X25519(32) + Ed25519(32) = 64 bytes.
pub const ECPUBSIZE: usize = 64;
/// MTU signalling field size in bytes.
pub const LINK_MTU_SIZE: usize = 3;
/// Seconds per hop for establishment timeout calculation.
pub const ESTABLISHMENT_TIMEOUT_PER_HOP: f64 = 6.0;
/// Traffic timeout as a multiple of measured RTT.
pub const TRAFFIC_TIMEOUT_FACTOR: f64 = 6.0;
/// RTT ceiling for keepalive scaling.
pub const KEEPALIVE_MAX_RTT: f64 = 1.75;
/// Stale->closed timeout as a multiple of measured RTT.
pub const KEEPALIVE_TIMEOUT_FACTOR: f64 = 4.0;
/// Grace seconds after going stale before teardown.
pub const STALE_GRACE: f64 = 5.0;
pub const KEEPALIVE_MAX: f64 = 360.0;
pub const KEEPALIVE_MIN: f64 = 5.0;
pub const KEEPALIVE_DEFAULT: f64 = 360.0;
/// Stale threshold as a multiple of keepalive interval.
pub const STALE_FACTOR: f64 = 2.0;
pub const STALE_TIME_DEFAULT: f64 = 720.0;
/// Max sleep per watchdog cycle.
pub const WATCHDOG_MAX_SLEEP: f64 = 5.0;
/// Lower bound for traffic timeout; prevents sub-millisecond spins on tiny RTTs.
pub const TRAFFIC_TIMEOUT_FLOOR_MS: u64 = 5;
pub const MODE_AES128_CBC: u8 = 0x00;
/// Default: AES-256-CBC.
pub const MODE_AES256_CBC: u8 = 0x01;
/// Reserved for future AES-256-GCM support.
pub const MODE_AES256_GCM: u8 = 0x02;
pub const MODE_OTP_RESERVED: u8 = 0x03;
pub const MODE_PQ_RESERVED_1: u8 = 0x04;
pub const MODE_PQ_RESERVED_2: u8 = 0x05;
pub const MODE_PQ_RESERVED_3: u8 = 0x06;
pub const MODE_PQ_RESERVED_4: u8 = 0x07;
/// Encryption modes accepted by this implementation; others are advertised-but-refused.
pub const ENABLED_MODES: &[u8] = &[MODE_AES256_CBC];
pub const DEFAULT_MODE: u8 = MODE_AES256_CBC;
pub const TIMEOUT: u8 = 0x01;
pub const INITIATOR_CLOSED: u8 = 0x02;
pub const DESTINATION_CLOSED: u8 = 0x03;
pub const ACCEPT_NONE: u8 = 0x00;
/// Defer acceptance to an application callback.
pub const ACCEPT_APP: u8 = 0x01;
pub const ACCEPT_ALL: u8 = 0x02;
/// Low 21 bits of the 24-bit MTU signalling value carry the MTU.
pub const MTU_BYTEMASK: u32 = 0x001F_FFFF;
/// Bits 21-23 of the MTU signalling value carry the encryption mode.
pub const MODE_BYTEMASK: u32 = 0x00E0;
/// Derived key length for AES-256-CBC: 32 bytes cipher key || 32 bytes HMAC key.
pub const AES256_DERIVED_KEY_LENGTH: usize = 64;
/// Derived key length for AES-128-CBC: 16 bytes cipher key || 16 bytes HMAC key.
pub const AES128_DERIVED_KEY_LENGTH: usize = 32;
/// Seconds of slack granted to a response beyond its nominal transfer time.
pub const RESPONSE_MAX_GRACE_TIME: f64 = 10.0;
/// Sentinel byte sent by the initiator.
pub const KEEPALIVE_REQUEST: u8 = 0xFF;
/// Sentinel byte returned by the destination.
pub const KEEPALIVE_RESPONSE: u8 = 0xFE;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_constants() {
assert_eq!(ECPUBSIZE, 64);
assert_eq!(STALE_TIME_DEFAULT, KEEPALIVE_DEFAULT * STALE_FACTOR);
assert!(ENABLED_MODES.contains(&MODE_AES256_CBC));
assert!(!ENABLED_MODES.contains(&MODE_AES128_CBC));
}
}
+112
View File
@@ -0,0 +1,112 @@
use crate::key_derivation::LinkKeys;
use zeroize::Zeroizing;
/// Encrypt a plaintext frame with the link's session keys.
///
/// Wire format: `IV(16) || AES-CBC(PKCS7(pt)) || HMAC-SHA256(32)`.
pub fn link_encrypt(keys: &LinkKeys, plaintext: &[u8]) -> Result<Vec<u8>, LinkCryptoError> {
// Token keying is signing(32) || encryption(32); Zeroizing wipes it on drop.
let mut combined_key = Zeroizing::new(Vec::with_capacity(
keys.signing_key.len() + keys.encryption_key.len(),
));
combined_key.extend_from_slice(&keys.signing_key);
combined_key.extend_from_slice(&keys.encryption_key);
rns_crypto::token::encrypt(plaintext, &combined_key)
.map_err(|_| LinkCryptoError::EncryptionFailed)
}
/// Decrypt a ciphertext frame with the link's session keys.
///
/// Errors are deliberately opaque — padding and HMAC failures are indistinguishable
/// to callers so timing side channels cannot leak which check failed.
pub fn link_decrypt(keys: &LinkKeys, ciphertext: &[u8]) -> Result<Vec<u8>, LinkCryptoError> {
let mut combined_key = Zeroizing::new(Vec::with_capacity(
keys.signing_key.len() + keys.encryption_key.len(),
));
combined_key.extend_from_slice(&keys.signing_key);
combined_key.extend_from_slice(&keys.encryption_key);
rns_crypto::token::decrypt(ciphertext, &combined_key)
.map_err(|_| LinkCryptoError::DecryptionFailed)
}
#[derive(Debug, thiserror::Error)]
pub enum LinkCryptoError {
#[error("encryption failed")]
EncryptionFailed,
#[error("decryption failed")]
DecryptionFailed,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::constants::MODE_AES256_CBC;
use crate::key_derivation::LinkKeys;
use rns_crypto::x25519::X25519PrivateKey;
fn make_test_keys() -> (LinkKeys, LinkKeys) {
let prv_a = X25519PrivateKey::generate();
let pub_a = prv_a.public_key();
let prv_b = X25519PrivateKey::generate();
let pub_b = prv_b.public_key();
let link_id = [0x42; 16];
let keys_a = LinkKeys::derive(&prv_a, &pub_b, &link_id, MODE_AES256_CBC).unwrap();
let keys_b = LinkKeys::derive(&prv_b, &pub_a, &link_id, MODE_AES256_CBC).unwrap();
(keys_a, keys_b)
}
#[test]
fn test_encrypt_decrypt_roundtrip() {
let (keys_a, keys_b) = make_test_keys();
let plaintext = b"Hello, Reticulum Link!";
let ct = link_encrypt(&keys_a, plaintext).unwrap();
let pt = link_decrypt(&keys_b, &ct).unwrap();
assert_eq!(pt, plaintext);
}
#[test]
fn test_bidirectional() {
let (keys_a, keys_b) = make_test_keys();
// A -> B
let msg1 = b"from A to B";
let ct1 = link_encrypt(&keys_a, msg1).unwrap();
let pt1 = link_decrypt(&keys_b, &ct1).unwrap();
assert_eq!(pt1, msg1);
// B -> A uses the same keys: the link is symmetric.
let msg2 = b"from B to A";
let ct2 = link_encrypt(&keys_b, msg2).unwrap();
let pt2 = link_decrypt(&keys_a, &ct2).unwrap();
assert_eq!(pt2, msg2);
}
#[test]
fn test_wrong_keys_fail() {
let (keys_a, _) = make_test_keys();
let prv = X25519PrivateKey::generate();
let pub_key = X25519PrivateKey::generate().public_key();
let wrong_keys = LinkKeys::derive(&prv, &pub_key, &[0xFF; 16], MODE_AES256_CBC).unwrap();
let ct = link_encrypt(&keys_a, b"secret").unwrap();
assert!(link_decrypt(&wrong_keys, &ct).is_err());
}
#[test]
fn test_tampered_ciphertext() {
let (keys_a, keys_b) = make_test_keys();
let mut ct = link_encrypt(&keys_a, b"test").unwrap();
ct[20] ^= 0xFF;
assert!(link_decrypt(&keys_b, &ct).is_err());
}
#[test]
fn test_empty_plaintext() {
let (keys_a, keys_b) = make_test_keys();
let ct = link_encrypt(&keys_a, b"").unwrap();
let pt = link_decrypt(&keys_b, &ct).unwrap();
assert_eq!(pt, b"");
}
}
+574
View File
@@ -0,0 +1,574 @@
use rns_crypto::ed25519::{Ed25519PrivateKey, Ed25519PublicKey};
use rns_crypto::sha::truncated_hash;
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
use zeroize::Zeroize;
use crate::constants::{DEFAULT_MODE, ECPUBSIZE, LINK_MTU_SIZE};
use crate::key_derivation::{LinkKeyError, LinkKeys};
use crate::mtu_discovery::SignallingData;
/// Ephemeral key pair generated per link (initiator or responder).
///
/// The inner `X25519PrivateKey` and `Ed25519PrivateKey` zeroize themselves;
/// the `Drop` impl below propagates that through the composite struct.
pub struct EphemeralKeys {
pub x25519_prv: X25519PrivateKey,
pub x25519_pub: X25519PublicKey,
pub ed25519_prv: Ed25519PrivateKey,
pub ed25519_pub: Ed25519PublicKey,
}
impl Zeroize for EphemeralKeys {
fn zeroize(&mut self) {
self.x25519_prv.zeroize();
self.ed25519_prv.zeroize();
}
}
impl Drop for EphemeralKeys {
fn drop(&mut self) {
self.zeroize();
}
}
impl EphemeralKeys {
/// Generate a fresh ephemeral key pair for link establishment.
pub fn generate() -> Self {
let x25519_prv = X25519PrivateKey::generate();
let x25519_pub = x25519_prv.public_key();
let ed25519_prv = Ed25519PrivateKey::generate();
let ed25519_pub = ed25519_prv.public_key();
Self {
x25519_prv,
x25519_pub,
ed25519_prv,
ed25519_pub,
}
}
}
/// Link request payload (Message 1: initiator -> destination).
///
/// Wire format: `X25519_pub(32) || Ed25519_pub(32) || signalling(3)` — 67 bytes.
#[derive(Debug, Clone)]
pub struct LinkRequestData {
pub peer_x25519_pub: [u8; 32],
pub peer_ed25519_pub: [u8; 32],
pub signalling: SignallingData,
}
impl LinkRequestData {
/// Serialize as `x25519_pub(32) || ed25519_pub(32) || signalling(3)`.
pub fn pack(keys: &EphemeralKeys, signalling: SignallingData) -> Vec<u8> {
let mut data = Vec::with_capacity(ECPUBSIZE + LINK_MTU_SIZE);
data.extend_from_slice(&keys.x25519_pub.to_bytes());
data.extend_from_slice(&keys.ed25519_pub.to_bytes());
data.extend_from_slice(&signalling.pack());
data
}
/// Parse a link request payload.
///
/// Python accepts exactly the legacy 64-byte key payload or the modern
/// 67-byte key payload with signalling. Other lengths are dropped.
pub fn unpack(data: &[u8]) -> Result<Self, HandshakeError> {
if data.len() < ECPUBSIZE {
return Err(HandshakeError::TooShort);
}
if data.len() != ECPUBSIZE && data.len() != ECPUBSIZE + LINK_MTU_SIZE {
return Err(HandshakeError::InvalidLength(data.len()));
}
let mut x25519_pub = [0u8; 32];
x25519_pub.copy_from_slice(&data[0..32]);
let mut ed25519_pub = [0u8; 32];
ed25519_pub.copy_from_slice(&data[32..64]);
let signalling = if data.len() == ECPUBSIZE + LINK_MTU_SIZE {
SignallingData::unpack(&data[ECPUBSIZE..ECPUBSIZE + LINK_MTU_SIZE]).unwrap_or(
SignallingData::new(DEFAULT_MODE, rns_wire::constants::MTU as u32),
)
} else {
SignallingData::new(DEFAULT_MODE, rns_wire::constants::MTU as u32)
};
Ok(Self {
peer_x25519_pub: x25519_pub,
peer_ed25519_pub: ed25519_pub,
signalling,
})
}
}
/// Compute the link ID from a link request.
///
/// The hashable body is `flags_low_nibble || dest_hash || context || data[..ECPUBSIZE]`
/// — the signalling trailer is intentionally excluded so both sides agree on the same
/// link ID regardless of MTU/mode negotiation.
pub fn compute_link_id(destination_hash: &[u8; 16], request_data: &[u8]) -> [u8; 16] {
// LinkRequest(0x02) | DestinationType::Single(0x00); context is PacketContext::None.
let flags_low_nibble = 0x02u8;
let context = 0x00u8;
let data_len = request_data.len().min(ECPUBSIZE);
let mut hashable = Vec::with_capacity(1 + 16 + 1 + data_len);
hashable.push(flags_low_nibble);
hashable.extend_from_slice(destination_hash);
hashable.push(context);
hashable.extend_from_slice(&request_data[..data_len]);
truncated_hash(&hashable)
}
/// Compute the link ID from a full raw packet (for transport relay paths).
pub fn compute_link_id_from_raw(raw: &[u8], header_type: rns_wire::flags::HeaderType) -> [u8; 16] {
rns_wire::hash::link_id_from_raw(raw, header_type)
}
/// Link proof payload (Message 2: destination -> initiator).
///
/// Wire format: `signature(64) || X25519_pub(32) || signalling(3)` — 99 bytes.
/// The signature covers `link_id || responder_x25519_pub || identity_ed25519_pub || signalling`
/// under the destination's long-term identity Ed25519 key.
#[derive(Debug, Clone)]
pub struct LinkProofData {
pub signature: [u8; 64],
pub responder_x25519_pub: [u8; 32],
pub signalling: SignallingData,
}
impl LinkProofData {
/// Create and sign a link proof.
///
/// The signature binds the link to the destination's long-term identity key, not
/// the ephemeral responder key — this is what authenticates the responder to the
/// initiator.
pub fn create(
identity_signing_key: &Ed25519PrivateKey,
responder_x25519_pub: &[u8; 32],
identity_ed25519_pub: &[u8; 32],
link_id: &[u8; 16],
signalling: SignallingData,
) -> Self {
let sig_bytes = signalling.pack();
let mut signed_data = Vec::with_capacity(16 + 32 + 32 + 3);
signed_data.extend_from_slice(link_id);
signed_data.extend_from_slice(responder_x25519_pub);
signed_data.extend_from_slice(identity_ed25519_pub);
signed_data.extend_from_slice(&sig_bytes);
let signature = identity_signing_key.sign(&signed_data);
Self {
signature,
responder_x25519_pub: *responder_x25519_pub,
signalling,
}
}
/// Create a link proof using an external signer (e.g. YubiKey/PIV).
///
/// Variant of [`LinkProofData::create`] for identities whose private key cannot
/// be exported — the closure receives the signed-data blob and must return a
/// 64-byte Ed25519 signature.
pub fn create_with<F>(
sign_fn: F,
responder_x25519_pub: &[u8; 32],
identity_ed25519_pub: &[u8; 32],
link_id: &[u8; 16],
signalling: SignallingData,
) -> Self
where
F: FnOnce(&[u8]) -> [u8; 64],
{
let sig_bytes = signalling.pack();
let mut signed_data = Vec::with_capacity(16 + 32 + 32 + 3);
signed_data.extend_from_slice(link_id);
signed_data.extend_from_slice(responder_x25519_pub);
signed_data.extend_from_slice(identity_ed25519_pub);
signed_data.extend_from_slice(&sig_bytes);
let signature = sign_fn(&signed_data);
Self {
signature,
responder_x25519_pub: *responder_x25519_pub,
signalling,
}
}
/// Serialize as `signature(64) || responder_x25519_pub(32) || signalling(3)`.
pub fn pack(&self) -> Vec<u8> {
let mut data = Vec::with_capacity(64 + 32 + LINK_MTU_SIZE);
data.extend_from_slice(&self.signature);
data.extend_from_slice(&self.responder_x25519_pub);
data.extend_from_slice(&self.signalling.pack());
data
}
/// Parse a proof payload, accepting exactly 96-byte legacy frames or
/// 99-byte frames with signalling.
pub fn unpack(data: &[u8]) -> Result<Self, HandshakeError> {
if data.len() < 96 {
return Err(HandshakeError::TooShort);
}
if data.len() != 96 && data.len() != 96 + LINK_MTU_SIZE {
return Err(HandshakeError::InvalidLength(data.len()));
}
let mut signature = [0u8; 64];
signature.copy_from_slice(&data[0..64]);
let mut responder_pub = [0u8; 32];
responder_pub.copy_from_slice(&data[64..96]);
let signalling = if data.len() == 96 + LINK_MTU_SIZE {
SignallingData::unpack(&data[96..96 + LINK_MTU_SIZE]).unwrap_or(SignallingData::new(
DEFAULT_MODE,
rns_wire::constants::MTU as u32,
))
} else {
SignallingData::new(DEFAULT_MODE, rns_wire::constants::MTU as u32)
};
Ok(Self {
signature,
responder_x25519_pub: responder_pub,
signalling,
})
}
/// Verify the proof signature against the destination's identity public key.
pub fn validate(
&self,
identity_verify_key: &Ed25519PublicKey,
link_id: &[u8; 16],
peer_ed25519_pub: &[u8; 32],
) -> bool {
let sig_bytes = self.signalling.pack();
let mut signed_data = Vec::with_capacity(16 + 32 + 32 + 3);
signed_data.extend_from_slice(link_id);
signed_data.extend_from_slice(&self.responder_x25519_pub);
signed_data.extend_from_slice(peer_ed25519_pub);
signed_data.extend_from_slice(&sig_bytes);
identity_verify_key
.verify(&signed_data, &self.signature)
.is_ok()
}
}
/// Perform the ECDH handshake and derive session keys.
pub fn perform_handshake(
my_x25519_prv: &X25519PrivateKey,
peer_x25519_pub_bytes: &[u8; 32],
link_id: &[u8; 16],
mode: u8,
) -> Result<LinkKeys, LinkKeyError> {
let peer_pub = X25519PublicKey::from_bytes(peer_x25519_pub_bytes);
LinkKeys::derive(my_x25519_prv, &peer_pub, link_id, mode)
}
#[derive(Debug, thiserror::Error)]
pub enum HandshakeError {
#[error("handshake data too short")]
TooShort,
#[error("invalid handshake data length: {0}")]
InvalidLength(usize),
#[error("invalid signature")]
InvalidSignature,
#[error("key derivation failed: {0}")]
KeyDerivation(#[from] LinkKeyError),
#[error("unsupported encryption mode: {0}")]
UnsupportedMode(u8),
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_link_request_pack_unpack() {
let keys = EphemeralKeys::generate();
let sig = SignallingData::new(1, 500);
let packed = LinkRequestData::pack(&keys, sig);
assert_eq!(packed.len(), ECPUBSIZE + LINK_MTU_SIZE);
let unpacked = LinkRequestData::unpack(&packed).unwrap();
assert_eq!(unpacked.peer_x25519_pub, keys.x25519_pub.to_bytes());
assert_eq!(unpacked.peer_ed25519_pub, keys.ed25519_pub.to_bytes());
assert_eq!(unpacked.signalling.mode, 1);
assert_eq!(unpacked.signalling.mtu, 500);
}
#[test]
fn test_link_request_unpack_accepts_only_python_lengths() {
let keys = EphemeralKeys::generate();
let sig = SignallingData::new(1, 500);
let modern = LinkRequestData::pack(&keys, sig);
let legacy = &modern[..ECPUBSIZE];
let unpacked = LinkRequestData::unpack(legacy).unwrap();
assert_eq!(unpacked.peer_x25519_pub, keys.x25519_pub.to_bytes());
assert_eq!(unpacked.peer_ed25519_pub, keys.ed25519_pub.to_bytes());
assert_eq!(unpacked.signalling.mode, DEFAULT_MODE);
assert_eq!(unpacked.signalling.mtu, rns_wire::constants::MTU as u32);
assert!(matches!(
LinkRequestData::unpack(&modern[..ECPUBSIZE - 1]),
Err(HandshakeError::TooShort)
));
for len in [ECPUBSIZE + 1, ECPUBSIZE + 2] {
assert!(matches!(
LinkRequestData::unpack(&modern[..len]),
Err(HandshakeError::InvalidLength(actual)) if actual == len
));
}
let mut over = modern.clone();
over.push(0xCC);
assert!(matches!(
LinkRequestData::unpack(&over),
Err(HandshakeError::InvalidLength(actual)) if actual == ECPUBSIZE + LINK_MTU_SIZE + 1
));
}
#[test]
fn test_link_id_computation() {
let keys = EphemeralKeys::generate();
let sig = SignallingData::new(1, 500);
let packed = LinkRequestData::pack(&keys, sig);
let dest_hash = [0xAA; 16];
let link_id = compute_link_id(&dest_hash, &packed);
assert_eq!(link_id.len(), 16);
let link_id2 = compute_link_id(&dest_hash, &packed);
assert_eq!(link_id, link_id2);
}
#[test]
fn test_link_id_excludes_signalling() {
let keys = EphemeralKeys::generate();
let dest_hash = [0xBB; 16];
let sig1 = SignallingData::new(1, 500);
let packed1 = LinkRequestData::pack(&keys, sig1);
let sig2 = SignallingData::new(2, 1000);
let packed2 = LinkRequestData::pack(&keys, sig2);
// Different signalling, same keys -> same link_id.
let id1 = compute_link_id(&dest_hash, &packed1);
let id2 = compute_link_id(&dest_hash, &packed2);
assert_eq!(id1, id2);
}
#[test]
fn test_link_id_includes_dest_hash() {
let keys = EphemeralKeys::generate();
let sig = SignallingData::new(1, 500);
let packed = LinkRequestData::pack(&keys, sig);
let id1 = compute_link_id(&[0xAA; 16], &packed);
let id2 = compute_link_id(&[0xBB; 16], &packed);
assert_ne!(id1, id2);
}
#[test]
fn test_link_id_from_raw_matches_components() {
let keys = EphemeralKeys::generate();
let sig = SignallingData::new(1, 500);
let request_data = LinkRequestData::pack(&keys, sig);
let dest_hash = [0xCC; 16];
// Build a synthetic Header1 packet: LinkRequest + Single, 3 hops, no context.
let flags = 0x02u8;
let hops = 3u8;
let context = 0x00u8;
let mut raw = Vec::new();
raw.push(flags);
raw.push(hops);
raw.extend_from_slice(&dest_hash);
raw.push(context);
raw.extend_from_slice(&request_data);
let id_components = compute_link_id(&dest_hash, &request_data);
let id_raw = compute_link_id_from_raw(&raw, rns_wire::flags::HeaderType::Header1);
assert_eq!(id_components, id_raw);
}
#[test]
fn test_link_proof_create_validate() {
let identity_key = Ed25519PrivateKey::generate();
let identity_pub = identity_key.public_key();
let identity_ed25519_pub = identity_pub.to_bytes();
let responder_keys = EphemeralKeys::generate();
let link_id = [0xAB; 16];
let signalling = SignallingData::new(1, 500);
let proof = LinkProofData::create(
&identity_key,
&responder_keys.x25519_pub.to_bytes(),
&identity_ed25519_pub,
&link_id,
signalling,
);
let packed = proof.pack();
assert_eq!(packed.len(), 99);
let unpacked = LinkProofData::unpack(&packed).unwrap();
assert!(unpacked.validate(&identity_pub, &link_id, &identity_ed25519_pub,));
}
#[test]
fn test_link_proof_unpack_accepts_only_python_lengths() {
let proof = LinkProofData {
signature: [0xAA; 64],
responder_x25519_pub: [0xBB; 32],
signalling: SignallingData::new(1, 500),
};
let modern = proof.pack();
let legacy = LinkProofData::unpack(&modern[..96]).unwrap();
assert_eq!(legacy.signature, [0xAA; 64]);
assert_eq!(legacy.responder_x25519_pub, [0xBB; 32]);
assert_eq!(legacy.signalling.mode, DEFAULT_MODE);
assert_eq!(legacy.signalling.mtu, rns_wire::constants::MTU as u32);
assert!(matches!(
LinkProofData::unpack(&modern[..95]),
Err(HandshakeError::TooShort)
));
for len in [97, 98] {
assert!(matches!(
LinkProofData::unpack(&modern[..len]),
Err(HandshakeError::InvalidLength(actual)) if actual == len
));
}
let mut over = modern.clone();
over.push(0xCC);
assert!(matches!(
LinkProofData::unpack(&over),
Err(HandshakeError::InvalidLength(100))
));
}
#[test]
fn test_link_proof_wrong_identity_fails() {
let identity_key = Ed25519PrivateKey::generate();
let wrong_key = Ed25519PrivateKey::generate();
let wrong_pub = wrong_key.public_key();
let responder_keys = EphemeralKeys::generate();
let identity_ed25519_pub = identity_key.public_key().to_bytes();
let link_id = [0xAB; 16];
let signalling = SignallingData::new(1, 500);
let proof = LinkProofData::create(
&identity_key,
&responder_keys.x25519_pub.to_bytes(),
&identity_ed25519_pub,
&link_id,
signalling,
);
assert!(!proof.validate(&wrong_pub, &link_id, &identity_ed25519_pub,));
}
#[test]
fn test_full_handshake_key_agreement() {
let initiator_keys = EphemeralKeys::generate();
let signalling = SignallingData::new(1, 500);
let request_data = LinkRequestData::pack(&initiator_keys, signalling);
let dest_hash = [0xDD; 16];
let link_id = compute_link_id(&dest_hash, &request_data);
let _request = LinkRequestData::unpack(&request_data).unwrap();
let responder_keys = EphemeralKeys::generate();
let initiator_session = perform_handshake(
&initiator_keys.x25519_prv,
&responder_keys.x25519_pub.to_bytes(),
&link_id,
DEFAULT_MODE,
)
.unwrap();
let responder_session = perform_handshake(
&responder_keys.x25519_prv,
&initiator_keys.x25519_pub.to_bytes(),
&link_id,
DEFAULT_MODE,
)
.unwrap();
assert_eq!(initiator_session.signing_key, responder_session.signing_key);
assert_eq!(
initiator_session.encryption_key,
responder_session.encryption_key
);
}
use proptest::prelude::*;
proptest! {
/// LinkRequest round-trip over arbitrary key + signalling input.
/// The wire layout is `x25519_pub(32) || ed25519_pub(32) ||
/// signalling(3)`, so pack → unpack → re-pack must be stable for
/// any bit pattern in the key fields (we don't need valid curve
/// points — the wire codec doesn't care).
#[test]
fn proptest_link_request_pack_unpack_roundtrip(
x25519_pub: [u8; 32],
ed25519_pub: [u8; 32],
mode in 0u8..=7,
mtu in 0u32..=crate::constants::MTU_BYTEMASK,
) {
let signalling = SignallingData::new(mode, mtu);
// EphemeralKeys is the higher-level wrapper; we pack the
// bytes directly here to avoid generating live ECDH keys in
// the property loop.
let mut data = Vec::with_capacity(ECPUBSIZE + LINK_MTU_SIZE);
data.extend_from_slice(&x25519_pub);
data.extend_from_slice(&ed25519_pub);
data.extend_from_slice(&signalling.pack());
let unpacked = LinkRequestData::unpack(&data).unwrap();
prop_assert_eq!(unpacked.peer_x25519_pub, x25519_pub);
prop_assert_eq!(unpacked.peer_ed25519_pub, ed25519_pub);
prop_assert_eq!(unpacked.signalling, signalling);
}
/// LinkProof round-trip. Wire: `signature(64) || x25519_pub(32) ||
/// signalling(3)` = 99 bytes. Like the request, we skip signature
/// validity and only check the packing byte layout — validity is
/// covered by the non-proptest tests.
#[test]
fn proptest_link_proof_pack_unpack_roundtrip(
signature: [u8; 64],
responder_x25519_pub: [u8; 32],
mode in 0u8..=7,
mtu in 0u32..=crate::constants::MTU_BYTEMASK,
) {
let signalling = SignallingData::new(mode, mtu);
let proof = LinkProofData {
signature,
responder_x25519_pub,
signalling,
};
let packed = proof.pack();
prop_assert_eq!(packed.len(), 64 + 32 + LINK_MTU_SIZE);
let unpacked = LinkProofData::unpack(&packed).unwrap();
prop_assert_eq!(unpacked.signature, signature);
prop_assert_eq!(unpacked.responder_x25519_pub, responder_x25519_pub);
prop_assert_eq!(unpacked.signalling, signalling);
prop_assert_eq!(unpacked.pack(), packed);
}
}
}
+285
View File
@@ -0,0 +1,285 @@
use std::time::{Duration, Instant};
use crate::constants::*;
/// Keepalive timing state for a single link.
///
/// Only the initiator side schedules keepalives; the responder simply echoes them.
#[derive(Debug, Clone)]
pub struct KeepaliveState {
pub keepalive_interval: Duration,
pub stale_time: Duration,
pub is_initiator: bool,
pub last_inbound: Instant,
pub last_keepalive_sent: Option<Instant>,
/// Last data packet received, excluding keepalives.
pub last_data: Instant,
pub last_outbound: Option<Instant>,
pub last_proof: Option<Instant>,
pub activated_at: Option<Instant>,
/// Per-link ±10% random jitter so neighbouring links don't all fire at the same
/// phase and cause synchronised bursts on shared media.
jitter_offset: Duration,
jitter_negative: bool,
}
impl KeepaliveState {
pub fn new(is_initiator: bool) -> Self {
use rand::Rng;
let mut rng = rand::thread_rng();
let jitter_frac: f64 = rng.gen_range(-0.1..0.1);
let now = Instant::now();
Self {
keepalive_interval: Duration::from_secs_f64(KEEPALIVE_DEFAULT),
stale_time: Duration::from_secs_f64(STALE_TIME_DEFAULT),
is_initiator,
last_inbound: now,
last_keepalive_sent: None,
last_data: now,
last_outbound: None,
last_proof: None,
activated_at: None,
jitter_offset: Duration::from_secs_f64(jitter_frac.abs() * KEEPALIVE_DEFAULT),
jitter_negative: jitter_frac < 0.0,
}
}
/// Rescale the keepalive interval after a new RTT measurement.
///
/// Interval scales linearly with RTT up to `KEEPALIVE_MAX_RTT`, then saturates.
/// Jitter is re-rolled so the ±10% spread is relative to the new interval.
pub fn update_from_rtt(&mut self, rtt: Duration) {
let rtt_secs = rtt.as_secs_f64();
let scale_factor = KEEPALIVE_MAX / KEEPALIVE_MAX_RTT;
let interval = (rtt_secs * scale_factor).clamp(KEEPALIVE_MIN, KEEPALIVE_MAX);
self.keepalive_interval = Duration::from_secs_f64(interval);
self.stale_time = Duration::from_secs_f64(interval * STALE_FACTOR);
use rand::Rng;
let mut rng = rand::thread_rng();
let jitter_frac: f64 = rng.gen_range(-0.1..0.1);
self.jitter_offset = Duration::from_secs_f64(jitter_frac.abs() * interval);
self.jitter_negative = jitter_frac < 0.0;
}
pub fn record_inbound(&mut self) {
self.last_inbound = Instant::now();
}
/// Record an inbound data packet (distinct from a keepalive beat).
pub fn record_data(&mut self) {
let now = Instant::now();
self.last_data = now;
self.last_inbound = now;
}
pub fn record_outbound(&mut self) {
self.last_outbound = Some(Instant::now());
}
pub fn record_proof(&mut self) {
let now = Instant::now();
self.last_proof = Some(now);
self.last_inbound = now;
}
pub fn mark_activated(&mut self) {
self.activated_at = Some(Instant::now());
}
/// Whether the initiator should emit a keepalive now (jitter applied).
pub fn should_send_keepalive(&self) -> bool {
let jittered = if self.jitter_negative {
self.keepalive_interval
.saturating_sub(self.jitter_offset)
.max(Duration::from_secs_f64(KEEPALIVE_MIN))
} else {
self.keepalive_interval + self.jitter_offset
};
let inbound_elapsed = self.last_inbound.elapsed();
let keepalive_elapsed = self
.last_keepalive_sent
.map(|t| t.elapsed())
.unwrap_or(Duration::MAX);
self.is_initiator && inbound_elapsed >= jittered && keepalive_elapsed >= jittered
}
/// Whether the link should transition to STALE.
///
/// Uses the most recent of inbound, proof, or activation as the baseline so a
/// link that just came up isn't immediately flagged stale on a quiet channel.
pub fn is_stale(&self) -> bool {
let mut latest = self.last_inbound;
if let Some(proof) = self.last_proof
&& proof > latest
{
latest = proof;
}
if let Some(outbound) = self.last_outbound
&& outbound > latest
{
latest = outbound;
}
if let Some(activated) = self.activated_at
&& activated > latest
{
latest = activated;
}
latest.elapsed() >= self.stale_time
}
/// How long to wait in STALE before tearing the link down.
pub fn stale_grace_timeout(&self, rtt: Duration) -> Duration {
rtt * KEEPALIVE_TIMEOUT_FACTOR as u32 + Duration::from_secs_f64(STALE_GRACE)
}
pub fn mark_keepalive_sent(&mut self) {
self.last_keepalive_sent = Some(Instant::now());
}
pub fn since_inbound(&self) -> Duration {
self.last_inbound.elapsed()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::thread;
#[test]
fn test_rtt_scaling() {
let mut ks = KeepaliveState::new(true);
// Very fast link saturates at the minimum interval.
ks.update_from_rtt(Duration::from_millis(10));
assert_eq!(
ks.keepalive_interval,
Duration::from_secs_f64(KEEPALIVE_MIN)
);
ks.update_from_rtt(Duration::from_millis(100));
let expected = 0.1 * (KEEPALIVE_MAX / KEEPALIVE_MAX_RTT);
let diff = (ks.keepalive_interval.as_secs_f64() - expected).abs();
assert!(diff < 0.01);
// Very slow link saturates at the maximum interval.
ks.update_from_rtt(Duration::from_secs(2));
assert_eq!(
ks.keepalive_interval,
Duration::from_secs_f64(KEEPALIVE_MAX)
);
}
#[test]
fn test_stale_time_follows_keepalive() {
let mut ks = KeepaliveState::new(true);
ks.update_from_rtt(Duration::from_millis(100));
let expected_stale =
Duration::from_secs_f64(ks.keepalive_interval.as_secs_f64() * STALE_FACTOR);
// Tolerance absorbs sub-ns Duration round-trip drift.
let diff = ks.stale_time.as_secs_f64() - expected_stale.as_secs_f64();
assert!(
diff.abs() < 1e-6,
"stale_time {:?} should match recomputed expected {:?}",
ks.stale_time,
expected_stale
);
}
#[test]
fn test_should_send_keepalive_timing() {
let mut ks = KeepaliveState::new(true);
ks.keepalive_interval = Duration::from_millis(50);
ks.jitter_offset = Duration::ZERO;
ks.jitter_negative = false;
assert!(!ks.should_send_keepalive());
thread::sleep(Duration::from_millis(60));
assert!(ks.should_send_keepalive());
// Non-initiator side never emits keepalives.
let mut ks2 = KeepaliveState::new(false);
ks2.keepalive_interval = Duration::from_millis(1);
ks2.jitter_offset = Duration::ZERO;
thread::sleep(Duration::from_millis(5));
assert!(!ks2.should_send_keepalive());
}
#[test]
fn test_stale_detection() {
let mut ks = KeepaliveState::new(true);
ks.stale_time = Duration::from_millis(50);
assert!(!ks.is_stale());
thread::sleep(Duration::from_millis(60));
assert!(ks.is_stale());
ks.record_inbound();
assert!(!ks.is_stale());
}
#[test]
fn test_jitter_desynchronizes_keepalives() {
let links: Vec<KeepaliveState> = (0..20)
.map(|_| {
let mut ks = KeepaliveState::new(true);
ks.update_from_rtt(Duration::from_millis(500));
// Push last_inbound just past the interval boundary.
ks.last_inbound = Instant::now() - ks.keepalive_interval;
ks
})
.collect();
let firing: usize = links.iter().filter(|ks| ks.should_send_keepalive()).count();
let links_past: Vec<KeepaliveState> = (0..20)
.map(|_| {
let mut ks = KeepaliveState::new(true);
ks.update_from_rtt(Duration::from_millis(500));
ks.last_inbound = Instant::now() - ks.keepalive_interval * 2;
ks
})
.collect();
let firing_past: usize = links_past
.iter()
.filter(|ks| ks.should_send_keepalive())
.count();
assert!(
firing < 20,
"jitter should prevent all links firing simultaneously"
);
assert_eq!(
firing_past, 20,
"all links should fire well past the interval"
);
}
#[test]
fn test_jitter_bounded() {
for _ in 0..100 {
let mut ks = KeepaliveState::new(true);
ks.update_from_rtt(Duration::from_millis(500));
let max_jitter = ks.keepalive_interval.as_secs_f64() * 0.1;
assert!(
ks.jitter_offset.as_secs_f64() <= max_jitter + 0.001,
"jitter {:?} exceeds ±10% of interval {:?}",
ks.jitter_offset,
ks.keepalive_interval
);
}
}
#[test]
fn test_option_sentinels() {
let ks = KeepaliveState::new(true);
assert!(ks.last_keepalive_sent.is_none());
assert!(ks.last_outbound.is_none());
assert!(ks.last_proof.is_none());
assert!(ks.activated_at.is_none());
}
}
+109
View File
@@ -0,0 +1,109 @@
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
use zeroize::{Zeroize, Zeroizing};
use crate::constants::{
AES128_DERIVED_KEY_LENGTH, AES256_DERIVED_KEY_LENGTH, MODE_AES128_CBC, MODE_AES256_CBC,
};
/// Derived session keys for a link.
#[derive(Clone)]
pub struct LinkKeys {
/// HMAC-SHA256 signing key.
pub signing_key: Vec<u8>,
/// AES encryption key.
pub encryption_key: Vec<u8>,
}
impl LinkKeys {
/// Derive link session keys from an ECDH exchange.
///
/// Runs `HKDF-SHA256(ECDH(my_prv, peer_pub), salt = link_id)` and splits the
/// output into `signing_key || encryption_key`. Intermediate shared secrets
/// are zeroized as soon as HKDF consumes them.
pub fn derive(
my_prv: &X25519PrivateKey,
peer_pub: &X25519PublicKey,
link_id: &[u8; 16],
mode: u8,
) -> Result<Self, LinkKeyError> {
let derived_key_length = match mode {
MODE_AES128_CBC => AES128_DERIVED_KEY_LENGTH,
MODE_AES256_CBC => AES256_DERIVED_KEY_LENGTH,
_ => return Err(LinkKeyError::UnsupportedMode(mode)),
};
let mut shared_key = my_prv.exchange(peer_pub);
let derived_result =
rns_crypto::hkdf::hkdf_sha256(derived_key_length, &shared_key, Some(link_id), None)
.map_err(|_| LinkKeyError::HkdfFailed);
shared_key.zeroize();
let derived = Zeroizing::new(derived_result?);
let half = derived_key_length / 2;
let signing_key = derived[..half].to_vec();
let encryption_key = derived[half..].to_vec();
Ok(Self {
signing_key,
encryption_key,
})
}
}
impl Drop for LinkKeys {
fn drop(&mut self) {
self.signing_key.zeroize();
self.encryption_key.zeroize();
}
}
#[derive(Debug, thiserror::Error)]
pub enum LinkKeyError {
#[error("unsupported encryption mode: {0}")]
UnsupportedMode(u8),
#[error("HKDF key derivation failed")]
HkdfFailed,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_derive_aes256() {
let prv_a = X25519PrivateKey::generate();
let pub_a = prv_a.public_key();
let prv_b = X25519PrivateKey::generate();
let pub_b = prv_b.public_key();
let link_id = [0xAA; 16];
let keys_a = LinkKeys::derive(&prv_a, &pub_b, &link_id, MODE_AES256_CBC).unwrap();
let keys_b = LinkKeys::derive(&prv_b, &pub_a, &link_id, MODE_AES256_CBC).unwrap();
assert_eq!(keys_a.signing_key, keys_b.signing_key);
assert_eq!(keys_a.encryption_key, keys_b.encryption_key);
assert_eq!(keys_a.signing_key.len(), 32);
assert_eq!(keys_a.encryption_key.len(), 32);
}
#[test]
fn test_derive_different_link_ids() {
let prv_a = X25519PrivateKey::generate();
let pub_b = X25519PrivateKey::generate().public_key();
let keys1 = LinkKeys::derive(&prv_a, &pub_b, &[0x01; 16], MODE_AES256_CBC).unwrap();
let keys2 = LinkKeys::derive(&prv_a, &pub_b, &[0x02; 16], MODE_AES256_CBC).unwrap();
assert_ne!(keys1.signing_key, keys2.signing_key);
assert_ne!(keys1.encryption_key, keys2.encryption_key);
}
#[test]
fn test_unsupported_mode() {
let prv = X25519PrivateKey::generate();
let pub_key = prv.public_key();
let result = LinkKeys::derive(&prv, &pub_key, &[0; 16], 0xFF);
assert!(result.is_err());
}
}
+12
View File
@@ -0,0 +1,12 @@
//! Encrypted point-to-point Links between two Reticulum destinations.
//! LR/LRPROOF handshake → AES-256 + HMAC-SHA256 session, MTU discovery,
//! keepalives, request/response. Python reference: `RNS/Link.py`.
pub mod constants;
pub mod encryption;
pub mod handshake;
pub mod keepalive;
pub mod key_derivation;
pub mod link;
pub mod mtu_discovery;
pub mod request;
File diff suppressed because it is too large. Load diff
+116
View File
@@ -0,0 +1,116 @@
use crate::constants::{MODE_BYTEMASK, MTU_BYTEMASK};
/// MTU and encryption-mode signalling packed into 3 bytes (big-endian).
///
/// Wire layout: `[23:21] mode (0..=7)`, `[20:0] mtu (0..=2_097_151)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SignallingData {
pub mode: u8,
pub mtu: u32,
}
impl SignallingData {
pub fn new(mode: u8, mtu: u32) -> Self {
Self {
mode: mode & 0x07,
mtu: mtu & MTU_BYTEMASK,
}
}
/// Pack into 3 big-endian bytes.
pub fn pack(&self) -> [u8; 3] {
let value = (self.mtu & MTU_BYTEMASK) | ((((self.mode as u32) << 5) & MODE_BYTEMASK) << 16);
let bytes = value.to_be_bytes();
// Value fits in 24 bits; drop the high byte of the u32.
[bytes[1], bytes[2], bytes[3]]
}
/// Parse 3 big-endian bytes. Returns `None` if the input is shorter.
pub fn unpack(bytes: &[u8]) -> Option<Self> {
if bytes.len() < 3 {
return None;
}
let value = ((bytes[0] as u32) << 16) | ((bytes[1] as u32) << 8) | (bytes[2] as u32);
let mtu = value & MTU_BYTEMASK;
let mode = ((value >> 21) & 0x07) as u8;
Some(Self { mode, mtu })
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::constants::{DEFAULT_MODE, MODE_AES256_CBC};
#[test]
fn test_pack_unpack_roundtrip() {
let sd = SignallingData::new(MODE_AES256_CBC, 500);
let packed = sd.pack();
let unpacked = SignallingData::unpack(&packed).unwrap();
assert_eq!(unpacked.mode, MODE_AES256_CBC);
assert_eq!(unpacked.mtu, 500);
}
#[test]
fn test_mode_zero_mtu_500() {
let sd = SignallingData::new(0, 500);
let packed = sd.pack();
let unpacked = SignallingData::unpack(&packed).unwrap();
assert_eq!(unpacked.mode, 0);
assert_eq!(unpacked.mtu, 500);
}
#[test]
fn test_mode_bits_isolated() {
// Setting the mode must not corrupt the MTU field.
let sd = SignallingData::new(1, 500);
let packed = sd.pack();
let unpacked = SignallingData::unpack(&packed).unwrap();
assert_eq!(unpacked.mtu, 500);
assert_eq!(unpacked.mode, 1);
}
#[test]
fn test_max_mtu_value() {
let max_mtu = MTU_BYTEMASK;
let sd = SignallingData::new(7, max_mtu);
let packed = sd.pack();
let unpacked = SignallingData::unpack(&packed).unwrap();
assert_eq!(unpacked.mtu, max_mtu);
assert_eq!(unpacked.mode, 7);
}
#[test]
fn test_default_mode() {
let sd = SignallingData::new(DEFAULT_MODE, 500);
assert_eq!(sd.mode, MODE_AES256_CBC);
}
#[test]
fn test_too_short() {
assert!(SignallingData::unpack(&[0x00, 0x01]).is_none());
}
use proptest::prelude::*;
proptest! {
#[test]
fn proptest_signalling_pack_unpack_roundtrip(
mode in 0u8..=7,
mtu in 0u32..=MTU_BYTEMASK,
) {
let sd = SignallingData::new(mode, mtu);
let packed = sd.pack();
let unpacked = SignallingData::unpack(&packed).unwrap();
prop_assert_eq!(unpacked.mode, mode);
prop_assert_eq!(unpacked.mtu, mtu);
prop_assert_eq!(unpacked.pack(), packed);
}
#[test]
fn proptest_signalling_bytes_canonical(bytes: [u8; 3]) {
let sd = SignallingData::unpack(&bytes).unwrap();
prop_assert_eq!(sd.pack(), bytes);
}
}
}
+248
View File
@@ -0,0 +1,248 @@
use std::time::{Duration, Instant};
/// State of a request receipt.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RequestState {
Sent,
/// Response is arriving as a resource transfer rather than a single packet.
Receiving,
Delivered,
Failed,
/// Response payload has arrived; kept distinct from [`Delivered`] so callers
/// can distinguish "ack with data" from "ack only".
///
/// [`Delivered`]: RequestState::Delivered
ResponseReceived,
}
/// Callbacks for request receipt state changes.
#[derive(Default)]
pub struct RequestCallbacks {
pub response: Option<RequestCallback>,
pub failed: Option<RequestCallback>,
pub progress: Option<ProgressCallback>,
}
/// Callback invoked once when a request receives a response or terminal failure.
pub type RequestCallback = Box<dyn FnOnce(&RequestReceipt) + Send>;
/// Progress callback for resource-backed request responses.
pub type ProgressCallback = Box<dyn Fn(f32) + Send + Sync>;
/// Tracks the lifecycle of an outbound request over a link.
pub struct RequestReceipt {
pub request_id: [u8; 32],
pub link_id: [u8; 16],
pub state: RequestState,
pub sent_at: Instant,
pub timeout: Duration,
pub response: Option<Vec<u8>>,
pub rtt: Option<Duration>,
/// Transfer progress in [0.0, 1.0]; only meaningful for resource responses.
pub progress: f32,
pub callbacks: RequestCallbacks,
}
impl RequestReceipt {
pub fn new(request_id: [u8; 32], link_id: [u8; 16], timeout: Duration) -> Self {
Self {
request_id,
link_id,
state: RequestState::Sent,
sent_at: Instant::now(),
timeout,
response: None,
rtt: None,
progress: 0.0,
callbacks: RequestCallbacks::default(),
}
}
/// Record a response payload, transition to `Delivered`, and fire the response callback.
pub fn deliver(&mut self, response: Vec<u8>) {
if self.state == RequestState::Sent || self.state == RequestState::Receiving {
self.rtt = Some(self.sent_at.elapsed());
self.response = Some(response);
self.state = RequestState::Delivered;
self.progress = 1.0;
if let Some(cb) = self.callbacks.response.take() {
cb(self);
}
}
}
/// Transition to `Failed` and fire the failure callback.
pub fn fail(&mut self) {
if self.state == RequestState::Sent || self.state == RequestState::Receiving {
self.state = RequestState::Failed;
if let Some(cb) = self.callbacks.failed.take() {
cb(self);
}
}
}
pub fn is_timed_out(&self) -> bool {
self.state == RequestState::Sent && self.sent_at.elapsed() > self.timeout
}
pub fn is_pending(&self) -> bool {
self.state == RequestState::Sent
}
/// Store the response payload and advance to `ResponseReceived`.
///
/// Distinct from `deliver()`: `receive_response` can fire after `mark_delivered()`
/// for protocols that ack then stream the payload.
pub fn receive_response(&mut self, data: Vec<u8>) {
if self.state == RequestState::Sent || self.state == RequestState::Delivered {
self.rtt = Some(self.sent_at.elapsed());
self.response = Some(data);
self.state = RequestState::ResponseReceived;
}
}
/// Transition to `Delivered` without a response payload (ack-only).
pub fn mark_delivered(&mut self) {
if self.state == RequestState::Sent {
self.state = RequestState::Delivered;
}
}
/// Transition to `Failed` without firing the failure callback.
pub fn mark_failed(&mut self) {
if self.state == RequestState::Sent {
self.state = RequestState::Failed;
}
}
/// True once the request has reached a terminal state (delivered, failed, or response received).
pub fn concluded(&self) -> bool {
matches!(
self.state,
RequestState::Delivered | RequestState::Failed | RequestState::ResponseReceived
)
}
pub fn get_response_time(&self) -> Option<Duration> {
self.rtt
}
pub fn get_progress(&self) -> f32 {
self.progress
}
pub fn update_progress(&mut self, progress: f32) {
self.progress = progress;
if let Some(ref cb) = self.callbacks.progress {
cb(progress);
}
}
pub fn set_response_callback(&mut self, cb: impl FnOnce(&RequestReceipt) + Send + 'static) {
self.callbacks.response = Some(Box::new(cb));
}
pub fn set_failed_callback(&mut self, cb: impl FnOnce(&RequestReceipt) + Send + 'static) {
self.callbacks.failed = Some(Box::new(cb));
}
pub fn set_progress_callback(&mut self, cb: impl Fn(f32) + Send + Sync + 'static) {
self.callbacks.progress = Some(Box::new(cb));
}
/// Expire the request if past its deadline, firing the failure callback. Returns `true` if expired.
pub fn check_timeout(&mut self) -> bool {
if self.is_timed_out() {
self.state = RequestState::Failed;
if let Some(cb) = self.callbacks.failed.take() {
cb(self);
}
true
} else {
false
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_request_receipt_lifecycle() {
let mut receipt = RequestReceipt::new([0xAA; 32], [0xBB; 16], Duration::from_secs(10));
assert_eq!(receipt.state, RequestState::Sent);
assert!(receipt.is_pending());
assert!(receipt.response.is_none());
receipt.deliver(b"response data".to_vec());
assert_eq!(receipt.state, RequestState::Delivered);
assert!(!receipt.is_pending());
assert!(receipt.response.is_some());
assert!(receipt.rtt.is_some());
}
#[test]
fn test_request_receipt_fail() {
let mut receipt = RequestReceipt::new([0xAA; 32], [0xBB; 16], Duration::from_secs(10));
receipt.fail();
assert_eq!(receipt.state, RequestState::Failed);
assert!(!receipt.is_pending());
}
#[test]
fn test_cannot_deliver_after_fail() {
let mut receipt = RequestReceipt::new([0xAA; 32], [0xBB; 16], Duration::from_secs(10));
receipt.fail();
receipt.deliver(b"too late".to_vec());
assert_eq!(receipt.state, RequestState::Failed);
assert!(receipt.response.is_none());
}
#[test]
fn test_receive_response() {
let mut receipt = RequestReceipt::new([0xCC; 32], [0xDD; 16], Duration::from_secs(10));
assert_eq!(receipt.state, RequestState::Sent);
receipt.receive_response(b"response payload".to_vec());
assert_eq!(receipt.state, RequestState::ResponseReceived);
assert_eq!(
receipt.response.as_deref(),
Some(b"response payload".as_slice())
);
assert!(receipt.rtt.is_some());
}
#[test]
fn test_mark_delivered_then_response() {
let mut receipt = RequestReceipt::new([0xEE; 32], [0xFF; 16], Duration::from_secs(10));
receipt.mark_delivered();
assert_eq!(receipt.state, RequestState::Delivered);
receipt.receive_response(b"late response".to_vec());
assert_eq!(receipt.state, RequestState::ResponseReceived);
assert!(receipt.response.is_some());
}
#[test]
fn test_mark_failed_method() {
let mut receipt = RequestReceipt::new([0x11; 32], [0x22; 16], Duration::from_secs(10));
receipt.mark_failed();
assert_eq!(receipt.state, RequestState::Failed);
assert!(!receipt.is_pending());
}
#[test]
fn test_cannot_receive_response_after_fail() {
let mut receipt = RequestReceipt::new([0x33; 32], [0x44; 16], Duration::from_secs(10));
receipt.mark_failed();
receipt.receive_response(b"too late".to_vec());
assert_eq!(receipt.state, RequestState::Failed);
assert!(receipt.response.is_none());
}
}
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "rns-protocol"
description = "Resource, Channel, and Buffer protocols for Reticulum"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
rns-crypto = { workspace = true, features = ["std"] }
rns-wire = { workspace = true, features = ["std"] }
rns-link = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
bzip2 = { workspace = true }
rmpv = { workspace = true }
rmp-serde = { workspace = true }
hex = { workspace = true }
[dev-dependencies]
proptest = { workspace = true }
+499
View File
@@ -0,0 +1,499 @@
use std::collections::VecDeque;
use crate::compression;
use crate::stream_data::{STREAM_ID_MAX, StreamDataMessage};
/// Upper bound on a single chunk before the writer splits (16 KiB).
pub const MAX_CHUNK_LEN: usize = 16384;
/// Number of progressively smaller segments the writer will try when
/// compressing a chunk before giving up and sending it uncompressed.
pub const COMPRESSION_TRIES: usize = 4;
/// Accumulates inbound [`StreamDataMessage`] payloads into a byte queue and
/// tracks explicit EOF.
pub struct StreamReader {
stream_id: u16,
buffer: VecDeque<u8>,
eof: bool,
}
impl StreamReader {
pub fn new(stream_id: u16) -> Self {
Self {
stream_id: stream_id & STREAM_ID_MAX,
buffer: VecDeque::new(),
eof: false,
}
}
/// Append `msg` to the buffer. Returns `false` (and ignores the payload)
/// if the message belongs to a different stream.
pub fn feed(&mut self, msg: &StreamDataMessage) -> bool {
if msg.stream_id != self.stream_id {
return false;
}
if !msg.data.is_empty() {
self.buffer.extend(&msg.data);
}
if msg.eof {
self.eof = true;
}
true
}
/// Pop up to `size` bytes off the front of the buffer.
///
/// Returns `None` when the buffer is empty and EOF has not yet arrived,
/// and `Some(Vec::new())` once it has — letting callers distinguish "wait"
/// from "end of stream".
pub fn read(&mut self, size: usize) -> Option<Vec<u8>> {
if self.buffer.is_empty() {
if self.eof {
return Some(Vec::new());
}
return None;
}
let n = size.min(self.buffer.len());
let data: Vec<u8> = self.buffer.drain(..n).collect();
Some(data)
}
/// Drain the entire buffer. Same empty/`None` semantics as [`Self::read`].
pub fn read_all(&mut self) -> Option<Vec<u8>> {
if self.buffer.is_empty() {
if self.eof {
return Some(Vec::new());
}
return None;
}
let data: Vec<u8> = self.buffer.drain(..).collect();
Some(data)
}
pub fn available(&self) -> usize {
self.buffer.len()
}
pub fn is_eof(&self) -> bool {
self.eof
}
/// True once EOF has been received *and* all buffered data has been drained.
pub fn is_done(&self) -> bool {
self.eof && self.buffer.is_empty()
}
}
/// Chunks outbound bytes into [`StreamDataMessage`]s sized for the underlying
/// channel, opportunistically compressing each chunk with bzip2.
pub struct StreamWriter {
stream_id: u16,
max_data_len: usize,
closed: bool,
}
impl StreamWriter {
pub fn new(stream_id: u16, max_data_len: usize) -> Self {
Self {
stream_id: stream_id & STREAM_ID_MAX,
max_data_len,
closed: false,
}
}
/// Slice `data` into channel-sized frames. Each frame is sent compressed
/// if bzip2 would fit a larger source segment into `max_data_len` than the
/// uncompressed alternative; otherwise the chunk is sent raw.
pub fn write(&mut self, data: &[u8]) -> Result<Vec<StreamDataMessage>, BufferError> {
if self.closed {
return Err(BufferError::WriterClosed);
}
if data.is_empty() {
return Ok(Vec::new());
}
let mut messages = Vec::new();
let mut offset = 0;
while offset < data.len() {
let remaining = &data[offset..];
let chunk_len = remaining.len().min(MAX_CHUNK_LEN);
let chunk = &remaining[..chunk_len];
let (msg_data, consumed, compressed) = self.try_compress_chunk(chunk);
let mut msg = StreamDataMessage::new(self.stream_id, msg_data, false);
msg.compressed = compressed;
messages.push(msg);
offset += consumed;
}
Ok(messages)
}
/// Compress `chunk` at progressively smaller prefixes (chunk/1, chunk/2, …)
/// until the bzip2 output fits within `max_data_len` and is actually
/// shorter than the source, returning the first match. Falls back to a raw
/// send when no prefix benefits from compression.
fn try_compress_chunk(&self, chunk: &[u8]) -> (Vec<u8>, usize, bool) {
if chunk.len() <= 32 {
// bzip2 overhead dominates for very small inputs.
let send_len = chunk.len().min(self.max_data_len);
return (chunk[..send_len].to_vec(), send_len, false);
}
for comp_try in 1..COMPRESSION_TRIES {
let segment_len = chunk.len() / comp_try;
if segment_len <= 32 {
break;
}
if let Ok(compressed) = compression::bz2_compress(&chunk[..segment_len])
&& compressed.len() < self.max_data_len
&& compressed.len() < segment_len
{
return (compressed, segment_len, true);
}
}
let send_len = chunk.len().min(self.max_data_len);
(chunk[..send_len].to_vec(), send_len, false)
}
/// Close the writer and return the EOF frame paired with a drain contract:
/// the caller must ensure every message produced by prior `write()` calls
/// has been sent (and acknowledged) before transmitting `eof_message`.
pub fn close(&mut self) -> DrainClose {
self.closed = true;
DrainClose {
eof_message: StreamDataMessage::new(self.stream_id, Vec::new(), true),
}
}
/// Close the writer and return a bare EOF frame. Use when the caller
/// already manages ordering with the underlying channel.
pub fn close_simple(&mut self) -> StreamDataMessage {
self.closed = true;
StreamDataMessage::new(self.stream_id, Vec::new(), true)
}
pub fn is_closed(&self) -> bool {
self.closed
}
}
/// EOF frame handed back by [`StreamWriter::close`]. Must be sent only after
/// every earlier frame produced by the writer has been delivered.
pub struct DrainClose {
pub eof_message: StreamDataMessage,
}
#[derive(Debug, thiserror::Error)]
pub enum BufferError {
#[error("writer is closed")]
WriterClosed,
}
/// Bidirectional convenience wrapper that pairs a [`StreamWriter`] and
/// [`StreamReader`] on the same stream ID.
pub struct ChannelBuffer {
writer: StreamWriter,
reader: StreamReader,
stream_id: u16,
}
impl ChannelBuffer {
pub fn new(stream_id: u16, max_data_len: usize) -> Self {
Self {
writer: StreamWriter::new(stream_id, max_data_len),
reader: StreamReader::new(stream_id),
stream_id,
}
}
pub fn write(&mut self, data: &[u8]) -> Result<Vec<StreamDataMessage>, BufferError> {
self.writer.write(data)
}
/// Close the write side, returning a bare EOF frame. Send after prior
/// write output has flowed through the channel.
pub fn close_writer(&mut self) -> StreamDataMessage {
self.writer.close_simple()
}
/// Close the write side with the stricter drain contract — see
/// [`StreamWriter::close`].
pub fn drain_and_close_writer(&mut self) -> DrainClose {
self.writer.close()
}
pub fn feed_reader(&mut self, msg: &StreamDataMessage) -> bool {
self.reader.feed(msg)
}
pub fn read(&mut self, size: usize) -> Option<Vec<u8>> {
self.reader.read(size)
}
pub fn read_all(&mut self) -> Option<Vec<u8>> {
self.reader.read_all()
}
pub fn is_done(&self) -> bool {
self.reader.is_done()
}
pub fn is_writer_closed(&self) -> bool {
self.writer.is_closed()
}
pub fn stream_id(&self) -> u16 {
self.stream_id
}
pub fn available(&self) -> usize {
self.reader.available()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_reader_basic() {
let mut reader = StreamReader::new(1);
assert!(!reader.is_eof());
assert!(reader.read(100).is_none());
let msg = StreamDataMessage::new(1, b"hello".to_vec(), false);
assert!(reader.feed(&msg));
assert_eq!(reader.available(), 5);
let data = reader.read(3).unwrap();
assert_eq!(data, b"hel");
assert_eq!(reader.available(), 2);
}
#[test]
fn test_reader_eof() {
let mut reader = StreamReader::new(1);
let msg1 = StreamDataMessage::new(1, b"data".to_vec(), false);
reader.feed(&msg1);
let msg2 = StreamDataMessage::new(1, Vec::new(), true);
reader.feed(&msg2);
assert!(reader.is_eof());
let data = reader.read(100).unwrap();
assert_eq!(data, b"data");
// Once the buffer is drained, further reads must yield an explicit EOF marker.
let eof = reader.read(100).unwrap();
assert!(eof.is_empty());
assert!(reader.is_done());
}
#[test]
fn test_reader_wrong_stream() {
let mut reader = StreamReader::new(1);
let msg = StreamDataMessage::new(2, b"wrong".to_vec(), false);
assert!(!reader.feed(&msg));
assert_eq!(reader.available(), 0);
}
#[test]
fn test_writer_basic() {
let mut writer = StreamWriter::new(1, 10);
let msgs = writer.write(b"hello world, this is a test").unwrap();
// 27-byte input split at 10 bytes per frame must produce multiple messages.
assert!(msgs.len() >= 2);
for msg in &msgs {
assert_eq!(msg.stream_id, 1);
assert!(!msg.eof);
}
}
#[test]
fn test_writer_close() {
let mut writer = StreamWriter::new(1, 100);
let drain = writer.close();
assert!(drain.eof_message.eof);
assert!(drain.eof_message.data.is_empty());
assert!(writer.is_closed());
assert!(writer.write(b"after close").is_err());
}
#[test]
fn test_writer_close_simple() {
let mut writer = StreamWriter::new(1, 100);
let eof_msg = writer.close_simple();
assert!(eof_msg.eof);
assert!(eof_msg.data.is_empty());
assert!(writer.is_closed());
}
#[test]
fn test_roundtrip() {
let mut writer = StreamWriter::new(42, 50);
let mut reader = StreamReader::new(42);
let data = b"Hello, this is a complete stream test with some data!";
let msgs = writer.write(data).unwrap();
let eof = writer.close_simple();
for msg in &msgs {
reader.feed(msg);
}
reader.feed(&eof);
let received = reader.read_all().unwrap();
assert_eq!(received, data);
assert!(reader.is_eof());
}
#[test]
fn test_writer_compression_roundtrip() {
// Decompression lives in StreamDataMessage::unpack, so the roundtrip must
// go through pack/unpack — feeding the writer's output directly would skip it.
use crate::channel_message::MessageBase;
let mut writer = StreamWriter::new(1, 500);
let mut reader = StreamReader::new(1);
let data = b"AAAA".repeat(500);
let msgs = writer.write(&data).unwrap();
let any_compressed = msgs.iter().any(|m| m.compressed);
assert!(any_compressed, "Expected at least one compressed message");
for msg in &msgs {
let packed = msg.pack();
let mut received_msg = StreamDataMessage::new(0, Vec::new(), false);
received_msg.unpack(&packed).unwrap();
reader.feed(&received_msg);
}
let received = reader.read_all().unwrap();
assert_eq!(received, data);
}
#[test]
fn test_writer_small_data_no_compression() {
// bzip2 overhead dominates below 32 bytes, so short inputs must be sent raw.
let mut writer = StreamWriter::new(1, 500);
let data = b"tiny";
let msgs = writer.write(data).unwrap();
assert_eq!(msgs.len(), 1);
assert!(!msgs[0].compressed);
assert_eq!(msgs[0].data, b"tiny");
}
#[test]
fn test_writer_empty_write() {
let mut writer = StreamWriter::new(1, 100);
let msgs = writer.write(b"").unwrap();
assert!(msgs.is_empty());
}
#[test]
fn test_drain_close_semantics() {
let mut writer = StreamWriter::new(1, 100);
let _msgs = writer.write(b"some data").unwrap();
let drain = writer.close();
assert!(drain.eof_message.eof);
assert!(drain.eof_message.data.is_empty());
}
#[test]
fn test_channel_buffer_write_read() {
let stream_id = 7;
let mut buf = ChannelBuffer::new(stream_id, 100);
assert_eq!(buf.stream_id(), 7);
assert!(!buf.is_done());
assert!(!buf.is_writer_closed());
let msgs = buf.write(b"hello buffer").unwrap();
assert!(!msgs.is_empty());
for msg in &msgs {
assert!(buf.feed_reader(msg));
}
assert_eq!(buf.available(), 12);
let data = buf.read_all().unwrap();
assert_eq!(data, b"hello buffer");
}
#[test]
fn test_channel_buffer_roundtrip() {
let mut buf = ChannelBuffer::new(99, 20);
let input = b"This is a channel buffer roundtrip test with enough data to split";
let msgs = buf.write(input).unwrap();
let eof_msg = buf.close_writer();
assert!(buf.is_writer_closed());
for msg in &msgs {
buf.feed_reader(msg);
}
buf.feed_reader(&eof_msg);
let output = buf.read_all().unwrap();
assert_eq!(output, input);
assert!(buf.is_done());
}
#[test]
fn test_channel_buffer_partial_read() {
let mut buf = ChannelBuffer::new(5, 100);
let msgs = buf.write(b"abcdefghij").unwrap();
for msg in &msgs {
buf.feed_reader(msg);
}
let partial = buf.read(5).unwrap();
assert_eq!(partial, b"abcde");
assert_eq!(buf.available(), 5);
let rest = buf.read_all().unwrap();
assert_eq!(rest, b"fghij");
}
#[test]
fn test_channel_buffer_no_data() {
// Reads before any frames arrive must distinguish "wait" (None) from EOF.
let mut buf = ChannelBuffer::new(1, 100);
assert!(buf.read(10).is_none());
assert!(buf.read_all().is_none());
}
#[test]
fn test_channel_buffer_close_then_write_fails() {
let mut buf = ChannelBuffer::new(1, 100);
buf.close_writer();
assert!(buf.write(b"after close").is_err());
}
#[test]
fn test_channel_buffer_drain_and_close() {
let mut buf = ChannelBuffer::new(1, 100);
let _msgs = buf.write(b"data to drain").unwrap();
let drain = buf.drain_and_close_writer();
assert!(drain.eof_message.eof);
assert!(buf.is_writer_closed());
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,50 @@
/// Base trait for channel messages.
///
/// All channel messages must define a MSGTYPE (< 0xF000 for user messages),
/// and implement pack/unpack for serialization.
pub trait MessageBase: Send {
/// Unique message type identifier.
/// Must be < 0xF000 for user messages, >= 0xF000 for system messages.
fn msg_type(&self) -> u16;
/// Serialize the message payload.
fn pack(&self) -> Vec<u8>;
/// Deserialize from raw bytes.
fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError>;
}
/// Reserved message type namespace for system messages.
pub const SYSTEM_MESSAGE_TYPE_MIN: u16 = 0xF000;
/// System message type for stream data (Buffer).
pub const SMT_STREAM_DATA: u16 = 0xFF00;
/// Message lifecycle state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MessageState {
New,
Sent,
Delivered,
Failed,
}
#[derive(Debug, thiserror::Error)]
pub enum ChannelMessageError {
#[error("message unpack failed")]
UnpackFailed,
#[error("invalid message type")]
InvalidType,
#[error("message too short")]
TooShort,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_system_message_range() {
const { assert!(SMT_STREAM_DATA >= SYSTEM_MESSAGE_TYPE_MIN) };
}
}
+101
View File
@@ -0,0 +1,101 @@
use std::io::{Read, Write};
/// Maximum size for auto-compression (64 MiB).
pub const AUTO_COMPRESS_MAX_SIZE: usize = 67_108_864;
/// Compress `data` with bzip2 at the default level.
pub fn bz2_compress(data: &[u8]) -> Result<Vec<u8>, CompressionError> {
let mut encoder = bzip2::write::BzEncoder::new(Vec::new(), bzip2::Compression::default());
encoder
.write_all(data)
.map_err(|_| CompressionError::CompressFailed)?;
encoder
.finish()
.map_err(|_| CompressionError::CompressFailed)
}
/// Decompress bzip2 `data`, failing once the output would exceed `max_size`.
///
/// Decoding in chunks lets us stop early on a decompression bomb rather than
/// allocating the full expanded buffer.
pub fn bz2_decompress(data: &[u8], max_size: usize) -> Result<Vec<u8>, CompressionError> {
let mut decoder = bzip2::read::BzDecoder::new(data);
let mut output = Vec::new();
let mut buf = [0u8; 8192];
loop {
let n = decoder
.read(&mut buf)
.map_err(|_| CompressionError::DecompressFailed)?;
if n == 0 {
break;
}
output.extend_from_slice(&buf[..n]);
if output.len() > max_size {
return Err(CompressionError::DecompressedTooLarge);
}
}
Ok(output)
}
/// Compress opportunistically: return the bzip2 output only when it actually
/// shrinks the buffer. The boolean reports which variant was chosen so the
/// caller can set the `compressed` wire flag.
pub fn try_compress(data: &[u8]) -> (Vec<u8>, bool) {
if data.len() > AUTO_COMPRESS_MAX_SIZE {
return (data.to_vec(), false);
}
match bz2_compress(data) {
Ok(compressed) if compressed.len() < data.len() => (compressed, true),
_ => (data.to_vec(), false),
}
}
#[derive(Debug, thiserror::Error)]
pub enum CompressionError {
#[error("bz2 compression failed")]
CompressFailed,
#[error("bz2 decompression failed")]
DecompressFailed,
#[error("decompressed data exceeds size limit")]
DecompressedTooLarge,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_compress_decompress_roundtrip() {
let data = b"Hello, this is test data for compression!".repeat(100);
let compressed = bz2_compress(&data).unwrap();
assert!(compressed.len() < data.len());
let decompressed = bz2_decompress(&compressed, data.len() * 2).unwrap();
assert_eq!(decompressed, data);
}
#[test]
fn test_decompress_size_limit() {
let data = vec![0u8; 10000];
let compressed = bz2_compress(&data).unwrap();
let result = bz2_decompress(&compressed, 100);
assert!(result.is_err());
}
#[test]
fn test_try_compress_beneficial() {
let data = b"AAAA".repeat(1000);
let (result, was_compressed) = try_compress(&data);
assert!(was_compressed);
assert!(result.len() < data.len());
}
#[test]
fn test_try_compress_not_beneficial() {
// Short, incompressible input must still return without panicking.
let data: Vec<u8> = (0..100).map(|i| (i * 37 + 13) as u8).collect();
let (_result, was_compressed) = try_compress(&data);
let _ = was_compressed;
}
}
+12
View File
@@ -0,0 +1,12 @@
//! Higher-level protocol layers over Links: resource transfer, channels,
//! buffers, and stream I/O. Python reference: `RNS/Resource.py`,
//! `RNS/Channel.py`, `RNS/Buffer.py`.
pub mod buffer;
pub mod channel;
pub mod channel_message;
pub mod compression;
pub mod resource;
pub mod resource_adv;
pub mod rnsh;
pub mod stream_data;
File diff suppressed because it is too large. Load diff
+423
View File
@@ -0,0 +1,423 @@
use crate::resource::{MAPHASH_LEN, ResourceFlags};
/// Advertisement overhead in bytes (non-hashmap data).
pub const OVERHEAD: usize = 134;
/// Maximum map-hash entries that fit alongside the advertisement overhead in one MDU.
pub fn hashmap_max_len(mdu: usize) -> usize {
if mdu > OVERHEAD {
(mdu - OVERHEAD) / MAPHASH_LEN
} else {
0
}
}
/// Space reserved to absorb a burst of out-of-order part requests without
/// churning the main hashmap: `2 * WINDOW_MAX_FAST + hashmap_max_len(mdu)`.
pub fn collision_guard_size(mdu: usize) -> usize {
2 * crate::resource::WINDOW_MAX_FAST + hashmap_max_len(mdu)
}
/// Msgpack-encoded announcement that precedes a resource transfer.
///
/// Keys in the packed map:
/// - `t`: transfer_size, `d`: data_size, `n`: num_parts
/// - `h`: resource_hash, `r`: random_hash, `o`: original_hash
/// - `i`: segment_index, `l`: total_segments, `q`: request_id
/// - `f`: flags byte, `m`: hashmap
///
/// When `flags.has_metadata` is set the reassembled data begins with a
/// length-prefixed metadata block that the receiver strips before delivering
/// the payload.
#[derive(Debug, Clone)]
pub struct ResourceAdvertisement {
pub transfer_size: usize,
pub data_size: usize,
pub num_parts: usize,
pub resource_hash: [u8; 32],
pub random_hash: Vec<u8>,
pub original_hash: [u8; 32],
pub segment_index: usize,
pub total_segments: usize,
pub request_id: Option<Vec<u8>>,
pub flags: ResourceFlags,
pub hashmap: Vec<u8>,
/// Length of the metadata prefix embedded in the resource data when
/// `flags.has_metadata` is set. Not transmitted on the wire.
pub metadata_size: usize,
}
impl ResourceAdvertisement {
/// Build an advertisement with no metadata prefix. Equivalent to
/// [`Self::with_metadata_size`] with `metadata_size = 0`.
// Mirrors the Resource ADV wire fields; grouping these into a builder
// would hide the packet layout this constructor exists to preserve.
#[allow(clippy::too_many_arguments)]
pub fn new(
transfer_size: usize,
data_size: usize,
num_parts: usize,
resource_hash: [u8; 32],
random_hash: Vec<u8>,
flags: ResourceFlags,
map_hashes: &[[u8; MAPHASH_LEN]],
mdu: usize,
) -> Self {
Self::with_metadata_size(
transfer_size,
data_size,
num_parts,
resource_hash,
random_hash,
flags,
map_hashes,
mdu,
0,
)
}
/// Build an advertisement, truncating `map_hashes` to what actually fits in
/// the MDU. Callers are expected to send the remaining hashes in a
/// subsequent hashmap-update packet.
// Same Resource ADV field set as `new`, plus the local metadata prefix
// size needed to split payload from metadata after receive.
#[allow(clippy::too_many_arguments)]
pub fn with_metadata_size(
transfer_size: usize,
data_size: usize,
num_parts: usize,
resource_hash: [u8; 32],
random_hash: Vec<u8>,
flags: ResourceFlags,
map_hashes: &[[u8; MAPHASH_LEN]],
mdu: usize,
metadata_size: usize,
) -> Self {
let max_hashes = hashmap_max_len(mdu);
let initial_hashes = map_hashes.len().min(max_hashes);
let mut hashmap = Vec::with_capacity(initial_hashes * MAPHASH_LEN);
for hash in map_hashes.iter().take(initial_hashes) {
hashmap.extend_from_slice(hash);
}
Self {
transfer_size,
data_size,
num_parts,
resource_hash,
random_hash,
original_hash: resource_hash,
segment_index: 1,
total_segments: 1,
request_id: None,
flags,
hashmap,
metadata_size,
}
}
/// Decode an advertisement produced by [`Self::pack`] or by the Python
/// reference implementation.
pub fn unpack(data: &[u8]) -> Result<Self, String> {
use rmpv::Value;
let value =
rmpv::decode::read_value(&mut &data[..]).map_err(|e| format!("msgpack decode: {e}"))?;
let map = match &value {
Value::Map(m) => m,
_ => return Err("expected msgpack map".into()),
};
let get = |key: &str| -> Option<&Value> {
map.iter()
.find(|(k, _)| matches!(k, Value::String(s) if s.as_str() == Some(key)))
.map(|(_, v)| v)
};
let get_usize = |key: &str| -> Result<usize, String> {
get(key)
.and_then(|v| v.as_u64())
.map(|v| v as usize)
.ok_or_else(|| format!("missing or invalid key: {key}"))
};
let get_bytes = |key: &str, len: usize| -> Result<Vec<u8>, String> {
let bytes = get(key)
.and_then(|v| v.as_slice())
.ok_or_else(|| format!("missing or invalid key: {key}"))?;
if bytes.len() < len {
return Err(format!("{key}: expected {len} bytes, got {}", bytes.len()));
}
Ok(bytes.to_vec())
};
let transfer_size = get_usize("t")?;
let data_size = get_usize("d")?;
let num_parts = get_usize("n")?;
let h_bytes = get_bytes("h", 32)?;
let mut resource_hash = [0u8; 32];
resource_hash.copy_from_slice(&h_bytes[..32]);
// Python sends a 16-byte random tag, but any length >= 4 is acceptable.
let random_hash = get_bytes("r", 4)?;
let o_bytes = get_bytes("o", 32)?;
let mut original_hash = [0u8; 32];
original_hash.copy_from_slice(&o_bytes[..32]);
let segment_index = get_usize("i")?;
let total_segments = get_usize("l")?;
let request_id = get("q").and_then(|v| {
if v.is_nil() {
None
} else {
v.as_slice().map(|s| s.to_vec())
}
});
let flags_byte = get("f").and_then(|v| v.as_u64()).unwrap_or(0) as u8;
let flags = ResourceFlags::from_byte(flags_byte);
let hashmap = get("m")
.and_then(|v| v.as_slice())
.map(|s| s.to_vec())
.unwrap_or_default();
Ok(Self {
transfer_size,
data_size,
num_parts,
resource_hash,
random_hash,
original_hash,
segment_index,
total_segments,
request_id,
flags,
hashmap,
metadata_size: 0,
})
}
/// Encode as the msgpack map described on the struct docs.
pub fn pack(&self) -> Vec<u8> {
use rmpv::Value;
let q_val = match &self.request_id {
Some(id) => Value::Binary(id.clone()),
None => Value::Nil,
};
let pairs: Vec<(Value, Value)> = vec![
(
Value::String("t".into()),
Value::Integer(self.transfer_size.into()),
),
(
Value::String("d".into()),
Value::Integer(self.data_size.into()),
),
(
Value::String("n".into()),
Value::Integer(self.num_parts.into()),
),
(
Value::String("h".into()),
Value::Binary(self.resource_hash.to_vec()),
),
(
Value::String("r".into()),
Value::Binary(self.random_hash.to_vec()),
),
(
Value::String("o".into()),
Value::Binary(self.original_hash.to_vec()),
),
(
Value::String("i".into()),
Value::Integer(self.segment_index.into()),
),
(
Value::String("l".into()),
Value::Integer(self.total_segments.into()),
),
(Value::String("q".into()), q_val),
(
Value::String("f".into()),
Value::Integer(self.flags.to_byte().into()),
),
(
Value::String("m".into()),
Value::Binary(self.hashmap.clone()),
),
];
let value = Value::Map(pairs);
let mut buf = Vec::new();
rmpv::encode::write_value(&mut buf, &value).expect("msgpack encode should succeed");
buf
}
/// Split the packed `hashmap` field into fixed-length map-hash entries.
pub fn get_map_hashes(&self) -> Vec<[u8; MAPHASH_LEN]> {
self.hashmap
.chunks_exact(MAPHASH_LEN)
.map(|chunk| {
let mut hash = [0u8; MAPHASH_LEN];
hash.copy_from_slice(chunk);
hash
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_hashmap_max_len() {
// 415 is a typical link MDU on LoRa.
let max = hashmap_max_len(415);
assert_eq!(max, (415 - 134) / 4);
assert_eq!(max, 70);
}
#[test]
fn test_default_link_mdu_matches_python_hashmap_capacity() {
assert_eq!(rns_wire::constants::ENCRYPTED_MDU, 431);
assert_eq!(hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU), 74);
}
#[test]
fn test_advertisement_creation() {
let hashes: Vec<[u8; 4]> = (0..100).map(|i| [i as u8; 4]).collect();
let adv = ResourceAdvertisement::new(
1000,
800,
3,
[0xAA; 32],
vec![0xBB; 4],
ResourceFlags::default(),
&hashes,
415,
);
let extracted = adv.get_map_hashes();
// Construction must truncate to whatever fits in the MDU.
assert_eq!(extracted.len(), 70);
assert_eq!(extracted[0], [0; 4]);
}
#[test]
fn test_collision_guard() {
let guard = collision_guard_size(415);
assert_eq!(guard, 2 * 75 + 70);
assert_eq!(guard, 220);
}
#[test]
fn test_advertisement_with_metadata() {
let hashes: Vec<[u8; 4]> = (0..10).map(|i| [i as u8; 4]).collect();
let flags = ResourceFlags {
has_metadata: true,
..Default::default()
};
let adv = ResourceAdvertisement::with_metadata_size(
1000,
800,
3,
[0xAA; 32],
vec![0xBB; 4],
flags,
&hashes,
415,
42,
);
assert!(adv.flags.has_metadata);
assert_eq!(adv.metadata_size, 42);
}
#[test]
fn test_advertisement_default_no_metadata() {
let hashes: Vec<[u8; 4]> = (0..5).map(|i| [i as u8; 4]).collect();
let adv = ResourceAdvertisement::new(
500,
400,
2,
[0xCC; 32],
vec![0xDD; 4],
ResourceFlags::default(),
&hashes,
415,
);
assert!(!adv.flags.has_metadata);
assert_eq!(adv.metadata_size, 0);
}
use proptest::prelude::*;
proptest! {
/// ResourceAdvertisement msgpack round-trip. The existing tests
/// check construction / field-level behavior but not the pack →
/// unpack cycle. This samples the whole-struct space and locks
/// in: all top-level fields survive the msgpack round-trip,
/// including the optional `request_id` variants (Nil vs Binary).
#[test]
fn proptest_resource_adv_pack_unpack_roundtrip(
transfer_size in 0usize..=10_000_000,
data_size in 0usize..=10_000_000,
num_parts in 0usize..=10_000,
resource_hash: [u8; 32],
// random_hash is a fixed-size RANDOM_HASH_SIZE (4 bytes) field.
random_hash_bytes: [u8; crate::resource::RANDOM_HASH_SIZE],
segment_index in 1usize..=256,
total_segments in 1usize..=256,
request_id in proptest::option::of(proptest::collection::vec(any::<u8>(), 1..=32)),
flags_byte: u8,
hashmap in proptest::collection::vec(any::<u8>(), 0..=256),
) {
let mut adv = ResourceAdvertisement {
transfer_size,
data_size,
num_parts,
resource_hash,
random_hash: random_hash_bytes.to_vec(),
original_hash: resource_hash,
segment_index,
total_segments,
request_id: request_id.clone(),
flags: ResourceFlags::from_byte(flags_byte),
hashmap: hashmap.clone(),
// metadata_size is NOT on the wire — set to 0 before
// packing so the round-trip comparison is meaningful.
metadata_size: 0,
};
// Trim hashmap to multiples of MAPHASH_LEN so the reader's
// chunked parse doesn't drop a stray trailing byte.
let usable = (adv.hashmap.len() / MAPHASH_LEN) * MAPHASH_LEN;
adv.hashmap.truncate(usable);
let packed = adv.pack();
let unpacked = ResourceAdvertisement::unpack(&packed).unwrap();
prop_assert_eq!(unpacked.transfer_size, adv.transfer_size);
prop_assert_eq!(unpacked.data_size, adv.data_size);
prop_assert_eq!(unpacked.num_parts, adv.num_parts);
prop_assert_eq!(unpacked.resource_hash, adv.resource_hash);
prop_assert_eq!(unpacked.random_hash.as_slice(), &random_hash_bytes[..]);
prop_assert_eq!(unpacked.original_hash, adv.original_hash);
prop_assert_eq!(unpacked.segment_index, adv.segment_index);
prop_assert_eq!(unpacked.total_segments, adv.total_segments);
prop_assert_eq!(&unpacked.request_id, &adv.request_id);
prop_assert_eq!(unpacked.flags.to_byte(), adv.flags.to_byte());
prop_assert_eq!(&unpacked.hashmap, &adv.hashmap);
}
}
}
+740
View File
@@ -0,0 +1,740 @@
//! rnsh channel message codecs.
//!
//! Python reference: `RNS/Utilities/rnsh/protocol.py`.
use std::io::Cursor;
use rmpv::Value;
use crate::channel_message::{ChannelMessageError, MessageBase};
use crate::compression;
pub const MSG_MAGIC: u8 = 0xAC;
pub const PROTOCOL_VERSION: u64 = 1;
pub const MSG_TYPE_NOOP: u16 = make_msg_type(0);
pub const MSG_TYPE_WINDOW_SIZE: u16 = make_msg_type(2);
pub const MSG_TYPE_EXECUTE_COMMAND: u16 = make_msg_type(3);
pub const MSG_TYPE_STREAM_DATA: u16 = make_msg_type(4);
pub const MSG_TYPE_VERSION_INFO: u16 = make_msg_type(5);
pub const MSG_TYPE_ERROR: u16 = make_msg_type(6);
pub const MSG_TYPE_COMMAND_EXITED: u16 = make_msg_type(7);
pub const MESSAGE_TYPES: [u16; 7] = [
MSG_TYPE_NOOP,
MSG_TYPE_VERSION_INFO,
MSG_TYPE_WINDOW_SIZE,
MSG_TYPE_EXECUTE_COMMAND,
MSG_TYPE_STREAM_DATA,
MSG_TYPE_COMMAND_EXITED,
MSG_TYPE_ERROR,
];
pub const STREAM_ID_STDIN: u16 = 0;
pub const STREAM_ID_STDOUT: u16 = 1;
pub const STREAM_ID_STDERR: u16 = 2;
pub const STREAM_ID_MAX: u16 = 0x3FFF;
pub const STREAM_DATA_OVERHEAD: usize = 8;
pub const fn make_msg_type(val: u8) -> u16 {
((MSG_MAGIC as u16) << 8) | (val as u16)
}
#[derive(Debug, thiserror::Error)]
pub enum RnshCodecError {
#[error("msgpack decode failed: {0}")]
Decode(String),
#[error("msgpack encode failed: {0}")]
Encode(String),
#[error("unexpected msgpack shape for {0}")]
InvalidShape(&'static str),
#[error("invalid utf-8 string")]
InvalidUtf8,
#[error("unknown rnsh message type: 0x{0:04X}")]
UnknownMessageType(u16),
#[error("stream data unpack failed")]
StreamData,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct NoopMessage;
impl MessageBase for NoopMessage {
fn msg_type(&self) -> u16 {
MSG_TYPE_NOOP
}
fn pack(&self) -> Vec<u8> {
Vec::new()
}
fn unpack(&mut self, _raw: &[u8]) -> Result<(), ChannelMessageError> {
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct WindowSizeMessage {
pub rows: Option<u32>,
pub cols: Option<u32>,
pub hpix: Option<u32>,
pub vpix: Option<u32>,
}
impl WindowSizeMessage {
pub fn new(rows: Option<u32>, cols: Option<u32>, hpix: Option<u32>, vpix: Option<u32>) -> Self {
Self {
rows,
cols,
hpix,
vpix,
}
}
pub fn unpack_payload(raw: &[u8]) -> Result<Self, RnshCodecError> {
let values = decode_array(raw, 4, "WindowSizeMessage")?;
Ok(Self {
rows: value_to_u32_opt(&values[0], "rows")?,
cols: value_to_u32_opt(&values[1], "cols")?,
hpix: value_to_u32_opt(&values[2], "hpix")?,
vpix: value_to_u32_opt(&values[3], "vpix")?,
})
}
}
impl MessageBase for WindowSizeMessage {
fn msg_type(&self) -> u16 {
MSG_TYPE_WINDOW_SIZE
}
fn pack(&self) -> Vec<u8> {
encode_value(&Value::Array(vec![
u32_opt_to_value(self.rows),
u32_opt_to_value(self.cols),
u32_opt_to_value(self.hpix),
u32_opt_to_value(self.vpix),
]))
.expect("rnsh window size msgpack encode")
}
fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError> {
*self = Self::unpack_payload(raw).map_err(|_| ChannelMessageError::UnpackFailed)?;
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ExecuteCommandMessage {
pub cmdline: Option<Vec<String>>,
pub pipe_stdin: bool,
pub pipe_stdout: bool,
pub pipe_stderr: bool,
pub tcflags: Option<Value>,
pub term: Option<String>,
pub rows: Option<u32>,
pub cols: Option<u32>,
pub hpix: Option<u32>,
pub vpix: Option<u32>,
}
impl ExecuteCommandMessage {
// Mirrors the rnsh ExecuteCommand channel payload; each parameter maps to
// a serialized field in the message.
#[allow(clippy::too_many_arguments)]
pub fn new(
cmdline: Option<Vec<String>>,
pipe_stdin: bool,
pipe_stdout: bool,
pipe_stderr: bool,
tcflags: Option<Value>,
term: Option<String>,
rows: Option<u32>,
cols: Option<u32>,
hpix: Option<u32>,
vpix: Option<u32>,
) -> Self {
Self {
cmdline,
pipe_stdin,
pipe_stdout,
pipe_stderr,
tcflags,
term,
rows,
cols,
hpix,
vpix,
}
}
pub fn unpack_payload(raw: &[u8]) -> Result<Self, RnshCodecError> {
let values = decode_array(raw, 10, "ExecuteCommandMessage")?;
Ok(Self {
cmdline: value_to_string_vec_opt(&values[0], "cmdline")?,
pipe_stdin: value_to_bool(&values[1], "pipe_stdin")?,
pipe_stdout: value_to_bool(&values[2], "pipe_stdout")?,
pipe_stderr: value_to_bool(&values[3], "pipe_stderr")?,
tcflags: none_if_nil(values[4].clone()),
term: value_to_string_opt(&values[5], "term")?,
rows: value_to_u32_opt(&values[6], "rows")?,
cols: value_to_u32_opt(&values[7], "cols")?,
hpix: value_to_u32_opt(&values[8], "hpix")?,
vpix: value_to_u32_opt(&values[9], "vpix")?,
})
}
}
impl MessageBase for ExecuteCommandMessage {
fn msg_type(&self) -> u16 {
MSG_TYPE_EXECUTE_COMMAND
}
fn pack(&self) -> Vec<u8> {
encode_value(&Value::Array(vec![
string_vec_opt_to_value(self.cmdline.as_ref()),
Value::Boolean(self.pipe_stdin),
Value::Boolean(self.pipe_stdout),
Value::Boolean(self.pipe_stderr),
self.tcflags.clone().unwrap_or(Value::Nil),
string_opt_to_value(self.term.as_deref()),
u32_opt_to_value(self.rows),
u32_opt_to_value(self.cols),
u32_opt_to_value(self.hpix),
u32_opt_to_value(self.vpix),
]))
.expect("rnsh execute command msgpack encode")
}
fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError> {
*self = Self::unpack_payload(raw).map_err(|_| ChannelMessageError::UnpackFailed)?;
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RnshStreamDataMessage {
pub stream_id: u16,
pub eof: bool,
pub compressed: bool,
pub data: Vec<u8>,
}
impl RnshStreamDataMessage {
pub fn new(stream_id: u16, data: Vec<u8>, eof: bool) -> Self {
Self {
stream_id: stream_id & STREAM_ID_MAX,
eof,
compressed: false,
data,
}
}
fn header_value(&self) -> u16 {
let mut val = self.stream_id & STREAM_ID_MAX;
if self.eof {
val |= 0x8000;
}
if self.compressed {
val |= 0x4000;
}
val
}
fn parse_header(val: u16) -> (u16, bool, bool) {
let eof = (val & 0x8000) != 0;
let compressed = (val & 0x4000) != 0;
let stream_id = val & STREAM_ID_MAX;
(stream_id, eof, compressed)
}
pub fn unpack_payload(raw: &[u8]) -> Result<Self, RnshCodecError> {
if raw.len() < 2 {
return Err(RnshCodecError::StreamData);
}
let header_val = u16::from_be_bytes([raw[0], raw[1]]);
let (stream_id, eof, compressed) = Self::parse_header(header_val);
let payload = &raw[2..];
let data = if compressed && !payload.is_empty() {
compression::bz2_decompress(payload, crate::buffer::MAX_CHUNK_LEN)
.map_err(|_| RnshCodecError::StreamData)?
} else {
payload.to_vec()
};
Ok(Self {
stream_id,
eof,
compressed,
data,
})
}
}
impl Default for RnshStreamDataMessage {
fn default() -> Self {
Self::new(0, Vec::new(), false)
}
}
impl MessageBase for RnshStreamDataMessage {
fn msg_type(&self) -> u16 {
MSG_TYPE_STREAM_DATA
}
fn pack(&self) -> Vec<u8> {
let mut result = Vec::with_capacity(2 + self.data.len());
result.extend_from_slice(&self.header_value().to_be_bytes());
result.extend_from_slice(&self.data);
result
}
fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError> {
*self = Self::unpack_payload(raw).map_err(|_| ChannelMessageError::UnpackFailed)?;
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VersionInfoMessage {
pub sw_version: String,
pub protocol_version: u64,
}
impl VersionInfoMessage {
pub fn new(sw_version: impl Into<String>) -> Self {
Self {
sw_version: sw_version.into(),
protocol_version: PROTOCOL_VERSION,
}
}
pub fn unpack_payload(raw: &[u8]) -> Result<Self, RnshCodecError> {
let values = decode_array(raw, 2, "VersionInfoMessage")?;
Ok(Self {
sw_version: value_to_string(&values[0], "sw_version")?,
protocol_version: value_to_u64(&values[1], "protocol_version")?,
})
}
}
impl Default for VersionInfoMessage {
fn default() -> Self {
Self::new(env!("CARGO_PKG_VERSION"))
}
}
impl MessageBase for VersionInfoMessage {
fn msg_type(&self) -> u16 {
MSG_TYPE_VERSION_INFO
}
fn pack(&self) -> Vec<u8> {
encode_value(&Value::Array(vec![
string_to_value(&self.sw_version),
Value::from(self.protocol_version),
]))
.expect("rnsh version info msgpack encode")
}
fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError> {
*self = Self::unpack_payload(raw).map_err(|_| ChannelMessageError::UnpackFailed)?;
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ErrorMessage {
pub msg: Option<String>,
pub fatal: bool,
pub data: Option<Value>,
}
impl ErrorMessage {
pub fn new(msg: Option<String>, fatal: bool, data: Option<Value>) -> Self {
Self { msg, fatal, data }
}
pub fn unpack_payload(raw: &[u8]) -> Result<Self, RnshCodecError> {
let values = decode_array(raw, 3, "ErrorMessage")?;
Ok(Self {
msg: value_to_string_opt(&values[0], "msg")?,
fatal: value_to_bool(&values[1], "fatal")?,
data: none_if_nil(values[2].clone()),
})
}
}
impl MessageBase for ErrorMessage {
fn msg_type(&self) -> u16 {
MSG_TYPE_ERROR
}
fn pack(&self) -> Vec<u8> {
encode_value(&Value::Array(vec![
string_opt_to_value(self.msg.as_deref()),
Value::Boolean(self.fatal),
self.data.clone().unwrap_or(Value::Nil),
]))
.expect("rnsh error msgpack encode")
}
fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError> {
*self = Self::unpack_payload(raw).map_err(|_| ChannelMessageError::UnpackFailed)?;
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CommandExitedMessage {
pub return_code: i64,
}
impl CommandExitedMessage {
pub fn new(return_code: i64) -> Self {
Self { return_code }
}
pub fn unpack_payload(raw: &[u8]) -> Result<Self, RnshCodecError> {
let value = decode_value(raw)?;
let return_code = value_to_i64(&value, "return_code")?;
Ok(Self { return_code })
}
}
impl MessageBase for CommandExitedMessage {
fn msg_type(&self) -> u16 {
MSG_TYPE_COMMAND_EXITED
}
fn pack(&self) -> Vec<u8> {
encode_value(&Value::from(self.return_code)).expect("rnsh command exited msgpack encode")
}
fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError> {
*self = Self::unpack_payload(raw).map_err(|_| ChannelMessageError::UnpackFailed)?;
Ok(())
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum RnshMessage {
Noop(NoopMessage),
WindowSize(WindowSizeMessage),
ExecuteCommand(ExecuteCommandMessage),
StreamData(RnshStreamDataMessage),
VersionInfo(VersionInfoMessage),
Error(ErrorMessage),
CommandExited(CommandExitedMessage),
}
impl RnshMessage {
pub fn decode(msg_type: u16, payload: &[u8]) -> Result<Self, RnshCodecError> {
match msg_type {
MSG_TYPE_NOOP => Ok(Self::Noop(NoopMessage)),
MSG_TYPE_WINDOW_SIZE => Ok(Self::WindowSize(WindowSizeMessage::unpack_payload(
payload,
)?)),
MSG_TYPE_EXECUTE_COMMAND => Ok(Self::ExecuteCommand(
ExecuteCommandMessage::unpack_payload(payload)?,
)),
MSG_TYPE_STREAM_DATA => Ok(Self::StreamData(RnshStreamDataMessage::unpack_payload(
payload,
)?)),
MSG_TYPE_VERSION_INFO => Ok(Self::VersionInfo(VersionInfoMessage::unpack_payload(
payload,
)?)),
MSG_TYPE_ERROR => Ok(Self::Error(ErrorMessage::unpack_payload(payload)?)),
MSG_TYPE_COMMAND_EXITED => Ok(Self::CommandExited(
CommandExitedMessage::unpack_payload(payload)?,
)),
other => Err(RnshCodecError::UnknownMessageType(other)),
}
}
pub fn msg_type(&self) -> u16 {
match self {
Self::Noop(msg) => msg.msg_type(),
Self::WindowSize(msg) => msg.msg_type(),
Self::ExecuteCommand(msg) => msg.msg_type(),
Self::StreamData(msg) => msg.msg_type(),
Self::VersionInfo(msg) => msg.msg_type(),
Self::Error(msg) => msg.msg_type(),
Self::CommandExited(msg) => msg.msg_type(),
}
}
pub fn pack(&self) -> Vec<u8> {
match self {
Self::Noop(msg) => msg.pack(),
Self::WindowSize(msg) => msg.pack(),
Self::ExecuteCommand(msg) => msg.pack(),
Self::StreamData(msg) => msg.pack(),
Self::VersionInfo(msg) => msg.pack(),
Self::Error(msg) => msg.pack(),
Self::CommandExited(msg) => msg.pack(),
}
}
}
fn encode_value(value: &Value) -> Result<Vec<u8>, RnshCodecError> {
let mut buf = Vec::new();
rmpv::encode::write_value(&mut buf, value)
.map_err(|e| RnshCodecError::Encode(e.to_string()))?;
Ok(buf)
}
fn decode_value(raw: &[u8]) -> Result<Value, RnshCodecError> {
let mut cursor = Cursor::new(raw);
let value =
rmpv::decode::read_value(&mut cursor).map_err(|e| RnshCodecError::Decode(e.to_string()))?;
if cursor.position() as usize != raw.len() {
return Err(RnshCodecError::InvalidShape("trailing msgpack bytes"));
}
Ok(value)
}
fn decode_array(
raw: &[u8],
expected_len: usize,
name: &'static str,
) -> Result<Vec<Value>, RnshCodecError> {
let value = decode_value(raw)?;
match value {
Value::Array(items) if items.len() == expected_len => Ok(items),
_ => Err(RnshCodecError::InvalidShape(name)),
}
}
fn none_if_nil(value: Value) -> Option<Value> {
if matches!(value, Value::Nil) {
None
} else {
Some(value)
}
}
fn u32_opt_to_value(value: Option<u32>) -> Value {
value.map(Value::from).unwrap_or(Value::Nil)
}
fn string_to_value(value: &str) -> Value {
Value::String(rmpv::Utf8String::from(value))
}
fn string_opt_to_value(value: Option<&str>) -> Value {
value.map(string_to_value).unwrap_or(Value::Nil)
}
fn string_vec_opt_to_value(value: Option<&Vec<String>>) -> Value {
value
.map(|items| Value::Array(items.iter().map(|s| string_to_value(s)).collect()))
.unwrap_or(Value::Nil)
}
fn value_to_bool(value: &Value, field: &'static str) -> Result<bool, RnshCodecError> {
value.as_bool().ok_or(RnshCodecError::InvalidShape(field))
}
fn value_to_u32_opt(value: &Value, field: &'static str) -> Result<Option<u32>, RnshCodecError> {
if matches!(value, Value::Nil) {
return Ok(None);
}
let number = value_to_u64(value, field)?;
if number > u32::MAX as u64 {
return Err(RnshCodecError::InvalidShape(field));
}
Ok(Some(number as u32))
}
fn value_to_u64(value: &Value, field: &'static str) -> Result<u64, RnshCodecError> {
if let Some(number) = value.as_u64() {
return Ok(number);
}
if let Some(number) = value.as_i64()
&& number >= 0
{
return Ok(number as u64);
}
Err(RnshCodecError::InvalidShape(field))
}
fn value_to_i64(value: &Value, field: &'static str) -> Result<i64, RnshCodecError> {
if let Some(number) = value.as_i64() {
return Ok(number);
}
if let Some(number) = value.as_u64()
&& number <= i64::MAX as u64
{
return Ok(number as i64);
}
Err(RnshCodecError::InvalidShape(field))
}
fn value_to_string(value: &Value, field: &'static str) -> Result<String, RnshCodecError> {
value_to_string_opt(value, field)?.ok_or(RnshCodecError::InvalidShape(field))
}
fn value_to_string_opt(
value: &Value,
field: &'static str,
) -> Result<Option<String>, RnshCodecError> {
match value {
Value::Nil => Ok(None),
Value::String(s) => Ok(Some(
s.as_str().ok_or(RnshCodecError::InvalidUtf8)?.to_string(),
)),
Value::Binary(b) => String::from_utf8(b.clone())
.map(Some)
.map_err(|_| RnshCodecError::InvalidUtf8),
_ => Err(RnshCodecError::InvalidShape(field)),
}
}
fn value_to_string_vec_opt(
value: &Value,
field: &'static str,
) -> Result<Option<Vec<String>>, RnshCodecError> {
match value {
Value::Nil => Ok(None),
Value::Array(items) => items
.iter()
.map(|item| value_to_string(item, field))
.collect::<Result<Vec<_>, _>>()
.map(Some),
_ => Err(RnshCodecError::InvalidShape(field)),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::channel::Envelope;
#[test]
fn msg_type_constants_match_python_magic() {
assert_eq!(MSG_TYPE_NOOP, 0xAC00);
assert_eq!(MSG_TYPE_WINDOW_SIZE, 0xAC02);
assert_eq!(MSG_TYPE_EXECUTE_COMMAND, 0xAC03);
assert_eq!(MSG_TYPE_STREAM_DATA, 0xAC04);
assert_eq!(MSG_TYPE_VERSION_INFO, 0xAC05);
assert_eq!(MSG_TYPE_ERROR, 0xAC06);
assert_eq!(MSG_TYPE_COMMAND_EXITED, 0xAC07);
assert_eq!(PROTOCOL_VERSION, 1);
}
#[test]
fn noop_envelope_vector_is_python_compatible() {
let msg = NoopMessage;
let env = Envelope::pack(&msg, 0x1234);
assert_eq!(env.raw, [0xAC, 0x00, 0x12, 0x34, 0x00, 0x00]);
}
#[test]
fn window_size_msgpack_vector_roundtrips() {
let msg = WindowSizeMessage::new(Some(24), Some(80), None, None);
let expected = [0x94, 0x18, 0x50, 0xC0, 0xC0];
assert_eq!(msg.pack(), expected);
assert_eq!(WindowSizeMessage::unpack_payload(&expected).unwrap(), msg);
}
#[test]
fn window_size_all_fields_vector_roundtrips() {
let msg = WindowSizeMessage::new(Some(40), Some(120), Some(1920), Some(1080));
let expected = [0x94, 0x28, 0x78, 0xCD, 0x07, 0x80, 0xCD, 0x04, 0x38];
assert_eq!(msg.pack(), expected);
assert_eq!(WindowSizeMessage::unpack_payload(&expected).unwrap(), msg);
}
#[test]
fn execute_command_msgpack_vector_roundtrips() {
let msg = ExecuteCommandMessage::new(
Some(vec!["sh".into(), "-lc".into(), "echo hi".into()]),
true,
true,
true,
None,
Some("xterm".into()),
Some(24),
Some(80),
None,
None,
);
let expected = [
0x9A, 0x93, 0xA2, b's', b'h', 0xA3, b'-', b'l', b'c', 0xA7, b'e', b'c', b'h', b'o',
b' ', b'h', b'i', 0xC3, 0xC3, 0xC3, 0xC0, 0xA5, b'x', b't', b'e', b'r', b'm', 0x18,
0x50, 0xC0, 0xC0,
];
assert_eq!(msg.pack(), expected);
assert_eq!(
ExecuteCommandMessage::unpack_payload(&expected).unwrap(),
msg
);
}
#[test]
fn stream_data_vector_roundtrips() {
let msg = RnshStreamDataMessage::new(STREAM_ID_STDOUT, b"hi".to_vec(), false);
let expected = [0x00, 0x01, b'h', b'i'];
assert_eq!(msg.pack(), expected);
assert_eq!(
RnshStreamDataMessage::unpack_payload(&expected).unwrap(),
msg
);
let eof = RnshStreamDataMessage::new(STREAM_ID_STDIN, Vec::new(), true);
assert_eq!(eof.pack(), [0x80, 0x00]);
}
#[test]
fn compressed_stream_data_payload_is_decompressed_on_unpack() {
let data = b"rnsh stream compression".repeat(200);
let compressed = compression::bz2_compress(&data).unwrap();
let mut raw = vec![0xC0, 0x01];
raw.extend_from_slice(&compressed);
let unpacked = RnshStreamDataMessage::unpack_payload(&raw).unwrap();
assert_eq!(unpacked.stream_id, STREAM_ID_STDOUT);
assert!(unpacked.eof);
assert!(unpacked.compressed);
assert_eq!(unpacked.data, data);
}
#[test]
fn version_info_msgpack_and_envelope_vectors_roundtrip() {
let msg = VersionInfoMessage::new("0.9.0");
let payload = [0x92, 0xA5, b'0', b'.', b'9', b'.', b'0', 0x01];
assert_eq!(msg.pack(), payload);
assert_eq!(VersionInfoMessage::unpack_payload(&payload).unwrap(), msg);
let env = Envelope::pack(&msg, 7);
let expected = [
0xAC, 0x05, 0x00, 0x07, 0x00, 0x08, 0x92, 0xA5, b'0', b'.', b'9', b'.', b'0', 0x01,
];
assert_eq!(env.raw, expected);
}
#[test]
fn error_and_exit_vectors_roundtrip() {
let error = ErrorMessage::new(Some("boom".into()), true, None);
let error_payload = [0x93, 0xA4, b'b', b'o', b'o', b'm', 0xC3, 0xC0];
assert_eq!(error.pack(), error_payload);
assert_eq!(ErrorMessage::unpack_payload(&error_payload).unwrap(), error);
let exited = CommandExitedMessage::new(0);
assert_eq!(exited.pack(), [0x00]);
assert_eq!(
CommandExitedMessage::unpack_payload(&[0x00]).unwrap(),
exited
);
}
#[test]
fn decode_dispatches_by_msg_type() {
let payload = VersionInfoMessage::new("0.9.0").pack();
let decoded = RnshMessage::decode(MSG_TYPE_VERSION_INFO, &payload).unwrap();
assert!(matches!(decoded, RnshMessage::VersionInfo(_)));
assert!(RnshMessage::decode(0xAC08, &[]).is_err());
}
}
+201
View File
@@ -0,0 +1,201 @@
use crate::buffer::MAX_CHUNK_LEN;
use crate::channel_message::{ChannelMessageError, MessageBase, SMT_STREAM_DATA};
use crate::compression;
/// Maximum stream ID value (14 bits).
pub const STREAM_ID_MAX: u16 = 0x3FFF;
/// StreamDataMessage overhead: 2-byte header + 6-byte channel envelope = 8 bytes.
pub const OVERHEAD: usize = 8;
/// Stream frame for the Buffer protocol.
///
/// Wire layout (2-byte big-endian header followed by payload):
/// - bit 15: EOF flag
/// - bit 14: compressed flag (payload is bz2)
/// - bits 13..0: stream ID (0..=16_383)
#[derive(Debug, Clone)]
pub struct StreamDataMessage {
pub stream_id: u16,
pub eof: bool,
pub compressed: bool,
pub data: Vec<u8>,
}
impl StreamDataMessage {
pub fn new(stream_id: u16, data: Vec<u8>, eof: bool) -> Self {
Self {
stream_id: stream_id & STREAM_ID_MAX,
eof,
compressed: false,
data,
}
}
fn header_value(&self) -> u16 {
let mut val = self.stream_id & STREAM_ID_MAX;
if self.eof {
val |= 0x8000;
}
if self.compressed {
val |= 0x4000;
}
val
}
fn parse_header(val: u16) -> (u16, bool, bool) {
let eof = (val & 0x8000) != 0;
let compressed = (val & 0x4000) != 0;
let stream_id = val & STREAM_ID_MAX;
(stream_id, eof, compressed)
}
}
impl MessageBase for StreamDataMessage {
fn msg_type(&self) -> u16 {
SMT_STREAM_DATA
}
fn pack(&self) -> Vec<u8> {
let header = self.header_value();
let header_bytes = header.to_be_bytes();
let mut result = Vec::with_capacity(2 + self.data.len());
result.extend_from_slice(&header_bytes);
result.extend_from_slice(&self.data);
result
}
fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError> {
if raw.len() < 2 {
return Err(ChannelMessageError::TooShort);
}
let header_val = u16::from_be_bytes([raw[0], raw[1]]);
let (stream_id, eof, compressed) = Self::parse_header(header_val);
self.stream_id = stream_id;
self.eof = eof;
self.compressed = compressed;
let payload = &raw[2..];
if compressed && !payload.is_empty() {
// Mirror Python `Buffer.py:96`: cap decompression at MAX_CHUNK_LEN
// (16 KiB) so a malicious peer can't expand a tiny bz2 payload into
// a large allocation. The streaming hard-cap in `bz2_decompress`
// returns an error rather than completing the allocation.
self.data = compression::bz2_decompress(payload, MAX_CHUNK_LEN)
.map_err(|_| ChannelMessageError::UnpackFailed)?;
} else {
self.data = payload.to_vec();
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pack_unpack_roundtrip() {
let msg = StreamDataMessage::new(42, b"hello stream".to_vec(), false);
let packed = msg.pack();
let mut msg2 = StreamDataMessage::new(0, Vec::new(), false);
msg2.unpack(&packed).unwrap();
assert_eq!(msg2.stream_id, 42);
assert!(!msg2.eof);
assert!(!msg2.compressed);
assert_eq!(msg2.data, b"hello stream");
}
#[test]
fn test_eof_flag() {
let msg = StreamDataMessage::new(1, Vec::new(), true);
let packed = msg.pack();
let mut msg2 = StreamDataMessage::new(0, Vec::new(), false);
msg2.unpack(&packed).unwrap();
assert!(msg2.eof);
assert_eq!(msg2.stream_id, 1);
}
#[test]
fn test_stream_id_mask() {
// IDs above 14 bits must wrap, not overflow into the flag bits.
let msg = StreamDataMessage::new(0xFFFF, b"test".to_vec(), false);
assert_eq!(msg.stream_id, STREAM_ID_MAX);
}
#[test]
fn test_header_bits() {
let msg = StreamDataMessage {
stream_id: 100,
eof: true,
compressed: true,
data: Vec::new(),
};
let packed = msg.pack();
let header = u16::from_be_bytes([packed[0], packed[1]]);
assert_eq!(header & 0x3FFF, 100);
assert!(header & 0x8000 != 0);
assert!(header & 0x4000 != 0);
}
#[test]
fn test_too_short() {
let mut msg = StreamDataMessage::new(0, Vec::new(), false);
assert!(msg.unpack(&[0x00]).is_err());
}
/// Regression for A2026-04.P-01: Buffer-protocol decompression must cap at
/// `MAX_CHUNK_LEN` (16 KiB), matching Python `Buffer.py:96`. A bz2 payload
/// that decompresses past that bound is a compression-bomb attack and must
/// be rejected rather than amplified into a large allocation.
#[test]
fn test_decompression_bounded_at_max_chunk_len() {
// Build a payload that bz2-compresses small but expands past the cap.
let big = vec![0u8; MAX_CHUNK_LEN + 1024];
let compressed = compression::bz2_compress(&big).expect("compress");
assert!(
compressed.len() < big.len(),
"test premise: compressed < raw"
);
// Hand-pack: header with compressed=true, stream_id=1.
let header_val: u16 = 0x4000 | 0x0001;
let mut packed = Vec::with_capacity(2 + compressed.len());
packed.extend_from_slice(&header_val.to_be_bytes());
packed.extend_from_slice(&compressed);
let mut msg = StreamDataMessage::new(0, Vec::new(), false);
let result = msg.unpack(&packed);
assert!(
result.is_err(),
"compressed payload that decompresses past MAX_CHUNK_LEN must be rejected"
);
}
/// Companion: a compressed payload that fits inside `MAX_CHUNK_LEN` after
/// decompression must round-trip cleanly. Guards against an over-tight bound.
#[test]
fn test_decompression_under_bound_succeeds() {
let small = vec![0u8; MAX_CHUNK_LEN - 256];
let compressed = compression::bz2_compress(&small).expect("compress");
let header_val: u16 = 0x4000 | 0x0007;
let mut packed = Vec::with_capacity(2 + compressed.len());
packed.extend_from_slice(&header_val.to_be_bytes());
packed.extend_from_slice(&compressed);
let mut msg = StreamDataMessage::new(0, Vec::new(), false);
msg.unpack(&packed)
.expect("payload within bound must decode");
assert_eq!(msg.data.len(), small.len());
assert_eq!(msg.stream_id, 7);
assert!(msg.compressed);
}
}
+31
View File
@@ -0,0 +1,31 @@
[package]
name = "rns-ratkey"
description = "Hardware-backed identity (YubiKey/Nitrokey PIV) for Reticulum"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[dependencies]
rns-crypto = { workspace = true, features = ["std"] }
rns-identity = { workspace = true }
serde = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
hex = { workspace = true }
zeroize = { workspace = true }
toml = "0.8"
[dev-dependencies]
rns-crypto = { workspace = true, features = ["std"] }
rns-identity = { workspace = true }
rns-link = { path = "../rns-link" }
[features]
default = []
# Enable real hardware PIV session (requires pcsc system library)
hardware = ["dep:pcsc"]
[dependencies.pcsc]
version = "2"
optional = true
+23
View File
@@ -0,0 +1,23 @@
# RatKey Hardware Status
RatKey hardware identity support is intentionally not release-grade until it is
verified against real devices. The mock-backed tests cover public identity
shape, signing, ECDH, decrypt flow, and fail-closed key mismatch behavior, but
they do not prove PIV transport, touch/PIN policy, or X.509 chain verification.
Required before hardware RatKey is documented as supported:
- Replace the mock-only `HardwareIdentity` session storage with a real PIV
backend abstraction and YubiKey/Nitrokey implementations.
- Verify signing and ECDH against physical YubiKeys, including disconnect,
wrong PIN, touch timeout, and slot mismatch cases.
- Implement cryptographic attestation certificate chain verification against
the bundled Yubico roots and intermediates.
- Decide and document the ratchet policy for hardware identities. PIV cannot
hold Reticulum ratchet private keys, so enforced-ratchet decrypt currently
fails closed.
- Add hardware-gated tests that are skipped by default but run when a device is
explicitly selected by environment/config.
Until those items pass on real devices, CLI/UI surfaces must label hardware
RatKey support as experimental.
@@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIDPjCCAiagAwIBAgIUXzeiEDJEOTt14F5n0o6Zf/bBwiUwDQYJKoZIhvcNAQEN
BQAwJDEiMCAGA1UEAwwZWXViaWNvIEF0dGVzdGF0aW9uIFJvb3QgMTAgFw0yNDEy
MDEwMDAwMDBaGA85OTk5MTIzMTIzNTk1OVowJDEiMCAGA1UEAwwZWXViaWNvIEF0
dGVzdGF0aW9uIFJvb3QgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
AMZ6/TxM8rIT+EaoPvG81ontMOo/2mQ2RBwJHS0QZcxVaNXvl12LUhBZ5LmiBScI
Zd1Rnx1od585h+/dhK7hEm7JAALkKKts1fO53KGNLZujz5h3wGncr4hyKF0G74b/
U3K9hE5mGND6zqYchCRAHfrYMYRDF4YL0X4D5nGdxvppAy6nkEmtWmMnwO3i0TAu
csrbE485HvGM4r0VpgVdJpvgQjiTJCTIq+D35hwtT8QDIv+nGvpcyi5wcIfCkzyC
imJukhYy6KoqNMKQEdpNiSOvWyDMTMt1bwCvEzpw91u+msUt4rj0efnO9s0ZOwdw
MRDnH4xgUl5ZLwrrPkfC1/0CAwEAAaNmMGQwHQYDVR0OBBYEFNLu71oijTptXCOX
PfKF1SbxJXuSMB8GA1UdIwQYMBaAFNLu71oijTptXCOXPfKF1SbxJXuSMBIGA1Ud
EwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBDQUAA4IB
AQC3IW/sgB9pZ8apJNjxuGoX+FkILks0wMNrdXL/coUvsrhzsvl6mePMrbGJByJ1
XnquB5sgcRENFxdQFma3mio8Upf1owM1ZreXrJ0mADG2BplqbJnxiyYa+R11reIF
TWeIhMNcZKsDZrFAyPuFjCWSQvJmNWe9mFRYFgNhXJKkXIb5H1XgEDlwiedYRM7V
olBNlld6pRFKlX8ust6OTMOeADl2xNF0m1LThSdeuXvDyC1g9+ILfz3S6OIYgc3i
roRcFD354g7rKfu67qFAw9gC4yi0xBTPrY95rh4/HqaUYCA/L8ldRk6H7Xk35D+W
Vpmq2Sh/xT5HiFuhf4wJb0bK
-----END CERTIFICATE-----
@@ -0,0 +1,19 @@
-----BEGIN CERTIFICATE-----
MIIDFzCCAf+gAwIBAgIDBAZHMA0GCSqGSIb3DQEBCwUAMCsxKTAnBgNVBAMMIFl1
YmljbyBQSVYgUm9vdCBDQSBTZXJpYWwgMjYzNzUxMCAXDTE2MDMxNDAwMDAwMFoY
DzIwNTIwNDE3MDAwMDAwWjArMSkwJwYDVQQDDCBZdWJpY28gUElWIFJvb3QgQ0Eg
U2VyaWFsIDI2Mzc1MTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMN2
cMTNR6YCdcTFRxuPy31PabRn5m6pJ+nSE0HRWpoaM8fc8wHC+Tmb98jmNvhWNE2E
ilU85uYKfEFP9d6Q2GmytqBnxZsAa3KqZiCCx2LwQ4iYEOb1llgotVr/whEpdVOq
joU0P5e1j1y7OfwOvky/+AXIN/9Xp0VFlYRk2tQ9GcdYKDmqU+db9iKwpAzid4oH
BVLIhmD3pvkWaRA2H3DA9t7H/HNq5v3OiO1jyLZeKqZoMbPObrxqDg+9fOdShzgf
wCqgT3XVmTeiwvBSTctyi9mHQfYd2DwkaqxRnLbNVyK9zl+DzjSGp9IhVPiVtGet
X02dxhQnGS7K6BO0Qe8CAwEAAaNCMEAwHQYDVR0OBBYEFMpfyvLEojGc6SJf8ez0
1d8Cv4O/MA8GA1UdEwQIMAYBAf8CAQEwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3
DQEBCwUAA4IBAQBc7Ih8Bc1fkC+FyN1fhjWioBCMr3vjneh7MLbA6kSoyWF70N3s
XhbXvT4eRh0hvxqvMZNjPU/VlRn6gLVtoEikDLrYFXN6Hh6Wmyy1GTnspnOvMvz2
lLKuym9KYdYLDgnj3BeAvzIhVzzYSeU77/Cupofj093OuAswW0jYvXsGTyix6B3d
bW5yWvyS9zNXaqGaUmP3U9/b6DlHdDogMLu3VLpBB9bm5bjaKWWJYgWltCVgUbFq
Fqyi4+JE014cSgR57Jcu3dZiehB6UtAPgad9L5cNvua/IWRmm+ANy3O2LH++Pyl8
SREzU8onbBsjMg9QDiSf5oJLKvd/Ren+zGY7
-----END CERTIFICATE-----
+685
View File
@@ -0,0 +1,685 @@
//! PIV APDU build/parse. Specs: ISO 7816-4 (APDU), NIST SP 800-73-4 (PIV),
//! Yubico Ed25519 (0xE0) / X25519 (0xE1) extensions.
//! Ref: <https://docs.yubico.com/yesdk/users-manual/application-piv/commands.html>
use crate::error::RatkeyError;
/// NIST RID + PIV PIX.
pub const PIV_AID: &[u8] = &[0xA0, 0x00, 0x00, 0x03, 0x08, 0x00, 0x00, 0x10, 0x00];
pub const INS_SELECT: u8 = 0xA4;
pub const INS_VERIFY: u8 = 0x20;
pub const INS_CHANGE_REFERENCE: u8 = 0x24;
pub const INS_GENERAL_AUTHENTICATE: u8 = 0x87;
pub const INS_GENERATE_ASYMMETRIC: u8 = 0x47;
pub const INS_GET_DATA: u8 = 0xCB;
pub const INS_GET_METADATA: u8 = 0xF7;
pub const INS_ATTEST: u8 = 0xF9;
pub const INS_IMPORT_KEY: u8 = 0xFE;
pub const INS_GET_VERSION: u8 = 0xFD;
pub const INS_GET_SERIAL: u8 = 0xF8;
// Algorithm IDs; ALG_ED25519/ALG_X25519 are YubiKey 5.7+ Yubico extensions.
pub const ALG_ED25519: u8 = 0xE0;
pub const ALG_X25519: u8 = 0xE1;
pub const ALG_ECCP256: u8 = 0x11;
pub const ALG_ECCP384: u8 = 0x14;
pub const SLOT_AUTHENTICATION: u8 = 0x9A;
pub const SLOT_SIGNATURE: u8 = 0x9C;
pub const SLOT_KEY_MANAGEMENT: u8 = 0x9D;
pub const SLOT_CARD_AUTH: u8 = 0x9E;
pub const SLOT_ATTESTATION: u8 = 0xF9;
pub const PIN_POLICY_NEVER: u8 = 0x01;
pub const PIN_POLICY_ONCE: u8 = 0x02;
pub const PIN_POLICY_ALWAYS: u8 = 0x03;
pub const TOUCH_POLICY_NEVER: u8 = 0x01;
pub const TOUCH_POLICY_ALWAYS: u8 = 0x02;
pub const TOUCH_POLICY_CACHED: u8 = 0x03;
const TAG_DYNAMIC_AUTH: u8 = 0x7C;
const TAG_AUTH_RESPONSE: u8 = 0x82;
const TAG_AUTH_CHALLENGE: u8 = 0x81;
const TAG_AUTH_EXPONENTIATION: u8 = 0x85;
const TAG_GEN_ALGORITHM: u8 = 0x80;
const TAG_PIN_POLICY: u8 = 0xAA;
const TAG_TOUCH_POLICY: u8 = 0xAB;
const TAG_OBJECT_ID: u8 = 0x5C;
const TAG_ECC_POINT: u8 = 0x86;
/// Cert object ID for slot 9A (Authentication).
pub const OBJ_ID_9A: &[u8] = &[0x5F, 0xC1, 0x05];
/// Cert object ID for slot 9D (Key Management).
pub const OBJ_ID_9D: &[u8] = &[0x5F, 0xC1, 0x0B];
pub fn slot_to_object_id(slot: u8) -> Option<&'static [u8]> {
match slot {
0x9A => Some(OBJ_ID_9A),
0x9D => Some(OBJ_ID_9D),
_ => None,
}
}
// ISO 7816-4 APDU: CLA INS P1 P2 [Lc] [Data]. CLA=0x00 (no chaining, no secure messaging).
fn build_apdu(ins: u8, p1: u8, p2: u8, data: &[u8]) -> Vec<u8> {
let mut apdu = Vec::with_capacity(5 + data.len());
apdu.push(0x00);
apdu.push(ins);
apdu.push(p1);
apdu.push(p2);
if !data.is_empty() {
if data.len() > 255 {
// Extended Lc: 0x00 + 2-byte BE length.
apdu.push(0x00);
apdu.push((data.len() >> 8) as u8);
apdu.push(data.len() as u8);
} else {
apdu.push(data.len() as u8);
}
apdu.extend_from_slice(data);
}
apdu
}
fn tlv(tag: u8, value: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(4 + value.len());
out.push(tag);
encode_der_length(value.len(), &mut out);
out.extend_from_slice(value);
out
}
fn encode_der_length(len: usize, out: &mut Vec<u8>) {
if len < 128 {
out.push(len as u8);
} else if len < 256 {
out.push(0x81);
out.push(len as u8);
} else {
out.push(0x82);
out.push((len >> 8) as u8);
out.push(len as u8);
}
}
pub fn select_piv() -> Vec<u8> {
build_apdu(INS_SELECT, 0x04, 0x00, PIV_AID)
}
/// PIN is ASCII, 0xFF-padded to 8 bytes (NIST SP 800-73-4 §2.4.3).
pub fn verify_pin(pin: &str) -> Vec<u8> {
let mut pin_data = [0xFFu8; 8];
let pin_bytes = pin.as_bytes();
let copy_len = pin_bytes.len().min(8);
pin_data[..copy_len].copy_from_slice(&pin_bytes[..copy_len]);
build_apdu(INS_VERIFY, 0x00, 0x80, &pin_data)
}
// CHANGE REFERENCE DATA.
pub fn change_pin(old_pin: &str, new_pin: &str) -> Vec<u8> {
let mut data = [0xFFu8; 16];
let old_bytes = old_pin.as_bytes();
let new_bytes = new_pin.as_bytes();
let old_len = old_bytes.len().min(8);
let new_len = new_bytes.len().min(8);
data[..old_len].copy_from_slice(&old_bytes[..old_len]);
data[8..8 + new_len].copy_from_slice(&new_bytes[..new_len]);
build_apdu(INS_CHANGE_REFERENCE, 0x00, 0x80, &data)
}
// GENERATE ASYMMETRIC KEY PAIR (Ed25519/X25519).
pub fn generate_key(
slot: u8,
algorithm: u8,
pin_policy: Option<u8>,
touch_policy: Option<u8>,
) -> Vec<u8> {
let mut inner = tlv(TAG_GEN_ALGORITHM, &[algorithm]);
if let Some(pp) = pin_policy {
inner.extend_from_slice(&tlv(TAG_PIN_POLICY, &[pp]));
}
if let Some(tp) = touch_policy {
inner.extend_from_slice(&tlv(TAG_TOUCH_POLICY, &[tp]));
}
let data = tlv(0xAC, &inner);
build_apdu(INS_GENERATE_ASYMMETRIC, 0x00, slot, &data)
}
/// GENERAL AUTHENTICATE Ed25519 sign. Send raw message — device does SHA-512 internally; no pre-hash.
pub fn sign_ed25519(slot: u8, message: &[u8]) -> Vec<u8> {
let challenge = tlv(TAG_AUTH_CHALLENGE, message);
// Empty response tag = request sig output.
let response_request = vec![TAG_AUTH_RESPONSE, 0x00];
let mut inner = Vec::with_capacity(response_request.len() + challenge.len());
inner.extend_from_slice(&response_request);
inner.extend_from_slice(&challenge);
let data = tlv(TAG_DYNAMIC_AUTH, &inner);
build_apdu(INS_GENERAL_AUTHENTICATE, ALG_ED25519, slot, &data)
}
/// GENERAL AUTHENTICATE X25519 ECDH: peer 32-byte pubkey in, 32-byte shared secret out.
pub fn ecdh_x25519(slot: u8, peer_public_key: &[u8; 32]) -> Vec<u8> {
let exponentiation = tlv(TAG_AUTH_EXPONENTIATION, peer_public_key);
let response_request = vec![TAG_AUTH_RESPONSE, 0x00];
let mut inner = Vec::with_capacity(response_request.len() + exponentiation.len());
inner.extend_from_slice(&response_request);
inner.extend_from_slice(&exponentiation);
let data = tlv(TAG_DYNAMIC_AUTH, &inner);
build_apdu(INS_GENERAL_AUTHENTICATE, ALG_X25519, slot, &data)
}
pub fn get_data(slot: u8) -> Option<Vec<u8>> {
let obj_id = slot_to_object_id(slot)?;
let data = tlv(TAG_OBJECT_ID, obj_id);
Some(build_apdu(INS_GET_DATA, 0x3F, 0xFF, &data))
}
pub fn get_metadata(slot: u8) -> Vec<u8> {
build_apdu(INS_GET_METADATA, 0x00, slot, &[])
}
/// Yubico proprietary; unsupported on Nitrokey 3.
pub fn get_version() -> Vec<u8> {
build_apdu(INS_GET_VERSION, 0x00, 0x00, &[])
}
/// Yubico proprietary; unsupported on Nitrokey 3.
pub fn get_serial() -> Vec<u8> {
build_apdu(INS_GET_SERIAL, 0x00, 0x00, &[])
}
pub fn attest_key(slot: u8) -> Vec<u8> {
build_apdu(INS_ATTEST, slot, 0x00, &[])
}
pub fn check_response(response: &[u8]) -> Result<&[u8], RatkeyError> {
if response.len() < 2 {
return Err(RatkeyError::Apdu {
sw1: 0x00,
sw2: 0x00,
});
}
let sw1 = response[response.len() - 2];
let sw2 = response[response.len() - 1];
if sw1 == 0x90 && sw2 == 0x00 {
Ok(&response[..response.len() - 2])
} else if sw1 == 0x63 && (sw2 & 0xF0) == 0xC0 {
// NIST SP 800-73-4 §2.4.3: low nibble of SW2 = retries remaining.
let remaining = sw2 & 0x0F;
if remaining == 0 {
Err(RatkeyError::PinLocked)
} else {
Err(RatkeyError::PinFailed { remaining })
}
} else if sw1 == 0x69 && sw2 == 0x83 {
Err(RatkeyError::PinLocked)
} else {
Err(RatkeyError::Apdu { sw1, sw2 })
}
}
/// GENERATE ASYMMETRIC response: `7F49 <len> 86 20 <32 bytes>` → 32-byte public key.
pub fn parse_generate_response(data: &[u8]) -> Result<[u8; 32], RatkeyError> {
let key_bytes = find_tlv_value(data, TAG_ECC_POINT).ok_or(RatkeyError::Apdu {
sw1: 0x6A,
sw2: 0x80,
})?;
if key_bytes.len() != 32 {
return Err(RatkeyError::InvalidHwid(format!(
"expected 32-byte public key, got {} bytes",
key_bytes.len()
)));
}
let mut out = [0u8; 32];
out.copy_from_slice(key_bytes);
Ok(out)
}
/// GENERAL AUTHENTICATE response: `7C <len> 82 40 <64 bytes>` → 64-byte Ed25519 sig.
pub fn parse_sign_response(data: &[u8]) -> Result<[u8; 64], RatkeyError> {
let sig_bytes = find_tlv_value(data, TAG_AUTH_RESPONSE).ok_or(RatkeyError::Apdu {
sw1: 0x6A,
sw2: 0x80,
})?;
if sig_bytes.len() != 64 {
return Err(RatkeyError::InvalidHwid(format!(
"expected 64-byte signature, got {} bytes",
sig_bytes.len()
)));
}
let mut out = [0u8; 64];
out.copy_from_slice(sig_bytes);
Ok(out)
}
/// GET VERSION → (major, minor, patch).
pub fn parse_version_response(data: &[u8]) -> Result<(u8, u8, u8), RatkeyError> {
if data.len() != 3 {
return Err(RatkeyError::InvalidHwid(format!(
"expected 3-byte version, got {} bytes",
data.len()
)));
}
Ok((data[0], data[1], data[2]))
}
/// GET SERIAL → u32 (4-byte BE).
pub fn parse_serial_response(data: &[u8]) -> Result<u32, RatkeyError> {
if data.len() != 4 {
return Err(RatkeyError::InvalidHwid(format!(
"expected 4-byte serial, got {} bytes",
data.len()
)));
}
Ok(u32::from_be_bytes([data[0], data[1], data[2], data[3]]))
}
/// X25519 ECDH response: `7C <len> 82 20 <32 bytes>` → 32-byte shared secret.
pub fn parse_ecdh_response(data: &[u8]) -> Result<[u8; 32], RatkeyError> {
let secret_bytes = find_tlv_value(data, TAG_AUTH_RESPONSE).ok_or(RatkeyError::Apdu {
sw1: 0x6A,
sw2: 0x80,
})?;
if secret_bytes.len() != 32 {
return Err(RatkeyError::InvalidHwid(format!(
"expected 32-byte shared secret, got {} bytes",
secret_bytes.len()
)));
}
let mut out = [0u8; 32];
out.copy_from_slice(secret_bytes);
Ok(out)
}
// Recurse into 7C / AC / 53 / any 2-byte tag (7F49 etc) to find a single-byte tag.
fn find_tlv_value(data: &[u8], target_tag: u8) -> Option<&[u8]> {
let mut pos = 0;
while pos < data.len() {
let (tag_len, tag_first) = if pos < data.len() {
(1, data[pos])
} else {
return None;
};
// 2-byte tags begin with 0x7F (e.g. 7F49 ECC pubkey).
let tag_bytes;
let tag_total_len;
if tag_first == 0x7F && pos + 1 < data.len() {
tag_bytes = 2;
tag_total_len = 2;
pos += 2;
} else {
tag_bytes = 1;
tag_total_len = 1;
let _ = tag_len;
pos += 1;
}
if pos >= data.len() {
return None;
}
let (value_len, len_bytes) = decode_der_length(&data[pos..])?;
pos += len_bytes;
if pos + value_len > data.len() {
return None;
}
let value = &data[pos..pos + value_len];
if tag_bytes == 1 && tag_first == target_tag {
return Some(value);
}
if tag_first == TAG_DYNAMIC_AUTH
|| tag_first == 0xAC
|| tag_first == 0x53
|| (tag_total_len == 2)
{
if let Some(found) = find_tlv_value(value, target_tag) {
return Some(found);
}
}
pos += value_len;
}
None
}
fn decode_der_length(data: &[u8]) -> Option<(usize, usize)> {
if data.is_empty() {
return None;
}
let first = data[0];
if first < 0x80 {
Some((first as usize, 1))
} else if first == 0x81 {
if data.len() < 2 {
return None;
}
Some((data[1] as usize, 2))
} else if first == 0x82 {
if data.len() < 3 {
return None;
}
Some((((data[1] as usize) << 8) | data[2] as usize, 3))
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_select_piv() {
let apdu = select_piv();
assert_eq!(
apdu,
vec![
0x00, 0xA4, 0x04, 0x00, 0x09, 0xA0, 0x00, 0x00, 0x03, 0x08, 0x00, 0x00, 0x10, 0x00
]
);
}
#[test]
fn test_verify_pin_default() {
let apdu = verify_pin("123456");
assert_eq!(
apdu,
vec![
0x00, 0x20, 0x00, 0x80, 0x08, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0xFF, 0xFF
]
);
}
#[test]
fn test_verify_pin_full_length() {
let apdu = verify_pin("12345678");
assert_eq!(
apdu,
vec![
0x00, 0x20, 0x00, 0x80, 0x08, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38
]
);
}
#[test]
fn test_generate_ed25519_slot_9a() {
let apdu = generate_key(SLOT_AUTHENTICATION, ALG_ED25519, None, None);
assert_eq!(
apdu,
vec![0x00, 0x47, 0x00, 0x9A, 0x05, 0xAC, 0x03, 0x80, 0x01, 0xE0]
);
}
#[test]
fn test_generate_x25519_with_policies() {
let apdu = generate_key(
SLOT_KEY_MANAGEMENT,
ALG_X25519,
Some(PIN_POLICY_ONCE),
Some(TOUCH_POLICY_CACHED),
);
// AC 09: 80 01 E1, AA 01 02, AB 01 03
assert_eq!(
apdu,
vec![
0x00, 0x47, 0x00, 0x9D, 0x0B, 0xAC, 0x09, 0x80, 0x01, 0xE1, 0xAA, 0x01, 0x02, 0xAB,
0x01, 0x03
]
);
}
#[test]
fn test_sign_ed25519_short_message() {
let message = [0xAA; 32];
let apdu = sign_ed25519(SLOT_AUTHENTICATION, &message);
// Header: 00 87 E0 9A
assert_eq!(apdu[0], 0x00); // CLA
assert_eq!(apdu[1], 0x87); // INS = GENERAL AUTHENTICATE
assert_eq!(apdu[2], 0xE0); // P1 = Ed25519
assert_eq!(apdu[3], 0x9A); // P2 = slot
// Data starts at [5]: 7C container
assert_eq!(apdu[5], 0x7C); // Dynamic Auth Template tag
// Inside 7C: 82 00, 81 20 <32 bytes>
// 82 00 = response request (2 bytes)
// 81 20 <32 bytes> = challenge (34 bytes)
// 7C length = 36 = 0x24
assert_eq!(apdu[6], 0x24); // 7C length
assert_eq!(apdu[7], 0x82); // Response tag
assert_eq!(apdu[8], 0x00); // Empty (request)
assert_eq!(apdu[9], 0x81); // Challenge tag
assert_eq!(apdu[10], 0x20); // Challenge length (32)
assert_eq!(&apdu[11..43], &message); // Message data
assert_eq!(apdu.len(), 43);
}
#[test]
fn test_sign_ed25519_empty_message() {
let apdu = sign_ed25519(SLOT_AUTHENTICATION, &[]);
assert_eq!(apdu[2], 0xE0); // P1 = Ed25519
assert_eq!(apdu[9], 0x81); // Challenge tag
assert_eq!(apdu[10], 0x00); // Challenge length = 0
}
#[test]
fn test_ecdh_x25519() {
let peer_pub = [0xBB; 32];
let apdu = ecdh_x25519(SLOT_KEY_MANAGEMENT, &peer_pub);
assert_eq!(apdu[0], 0x00); // CLA
assert_eq!(apdu[1], 0x87); // INS = GENERAL AUTHENTICATE
assert_eq!(apdu[2], 0xE1); // P1 = X25519
assert_eq!(apdu[3], 0x9D); // P2 = Key Management slot
assert_eq!(apdu[5], 0x7C); // Dynamic Auth Template
assert_eq!(apdu[7], 0x82); // Response tag
assert_eq!(apdu[8], 0x00); // Empty (request)
assert_eq!(apdu[9], 0x85); // Exponentiation tag (NOT 0x81)
assert_eq!(apdu[10], 0x20); // Length = 32
assert_eq!(&apdu[11..43], &peer_pub);
}
#[test]
fn test_get_data_slot_9a() {
let apdu = get_data(SLOT_AUTHENTICATION).unwrap();
assert_eq!(
apdu,
vec![0x00, 0xCB, 0x3F, 0xFF, 0x05, 0x5C, 0x03, 0x5F, 0xC1, 0x05]
);
}
#[test]
fn test_get_data_slot_9d() {
let apdu = get_data(SLOT_KEY_MANAGEMENT).unwrap();
assert_eq!(
apdu,
vec![0x00, 0xCB, 0x3F, 0xFF, 0x05, 0x5C, 0x03, 0x5F, 0xC1, 0x0B]
);
}
#[test]
fn test_attest_slot_9a() {
let apdu = attest_key(SLOT_AUTHENTICATION);
assert_eq!(apdu, vec![0x00, 0xF9, 0x9A, 0x00]);
}
#[test]
fn test_get_metadata() {
let apdu = get_metadata(SLOT_AUTHENTICATION);
assert_eq!(apdu, vec![0x00, 0xF7, 0x00, 0x9A]);
}
#[test]
fn test_get_version_apdu() {
assert_eq!(get_version(), vec![0x00, 0xFD, 0x00, 0x00]);
}
#[test]
fn test_get_serial_apdu() {
assert_eq!(get_serial(), vec![0x00, 0xF8, 0x00, 0x00]);
}
#[test]
fn test_parse_version_response() {
assert_eq!(
parse_version_response(&[0x05, 0x07, 0x01]).unwrap(),
(5, 7, 1)
);
}
#[test]
fn test_parse_version_response_wrong_length() {
assert!(parse_version_response(&[0x05, 0x07]).is_err());
assert!(parse_version_response(&[0x05, 0x07, 0x01, 0x00]).is_err());
}
#[test]
fn test_parse_serial_response() {
// 0x00BC614E = 12_345_678
assert_eq!(
parse_serial_response(&[0x00, 0xBC, 0x61, 0x4E]).unwrap(),
12_345_678
);
}
#[test]
fn test_parse_serial_response_wrong_length() {
assert!(parse_serial_response(&[0x00, 0x01, 0x02]).is_err());
}
#[test]
fn test_change_pin() {
let apdu = change_pin("123456", "654321");
assert_eq!(apdu[0], 0x00); // CLA
assert_eq!(apdu[1], 0x24); // INS = CHANGE REFERENCE
assert_eq!(apdu[2], 0x00); // P1
assert_eq!(apdu[3], 0x80); // P2 = PIN
assert_eq!(apdu[4], 0x10); // Lc = 16
// Old PIN: 31 32 33 34 35 36 FF FF
assert_eq!(
&apdu[5..13],
&[0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0xFF, 0xFF]
);
// New PIN: 36 35 34 33 32 31 FF FF
assert_eq!(
&apdu[13..21],
&[0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0xFF, 0xFF]
);
}
#[test]
fn test_check_response_success() {
let response = vec![0xAA, 0xBB, 0x90, 0x00];
let data = check_response(&response).unwrap();
assert_eq!(data, &[0xAA, 0xBB]);
}
#[test]
fn test_check_response_pin_failed() {
let response = vec![0x63, 0xC2]; // 2 retries remaining
match check_response(&response) {
Err(RatkeyError::PinFailed { remaining }) => assert_eq!(remaining, 2),
other => panic!("expected PinFailed, got {other:?}"),
}
}
#[test]
fn test_check_response_pin_locked() {
let response = vec![0x69, 0x83];
assert!(matches!(
check_response(&response),
Err(RatkeyError::PinLocked)
));
}
#[test]
fn test_check_response_pin_locked_via_c0() {
let response = vec![0x63, 0xC0]; // 0 retries = locked
assert!(matches!(
check_response(&response),
Err(RatkeyError::PinLocked)
));
}
#[test]
fn test_parse_generate_response_ed25519() {
// 7F49 22 86 20 <32 bytes key>
let mut response = vec![0x7F, 0x49, 0x22, 0x86, 0x20];
response.extend_from_slice(&[0xAA; 32]);
let key = parse_generate_response(&response).unwrap();
assert_eq!(key, [0xAA; 32]);
}
#[test]
fn test_parse_sign_response() {
// 7C 42 82 40 <64 bytes sig>
let mut response = vec![0x7C, 0x42, 0x82, 0x40];
response.extend_from_slice(&[0xBB; 64]);
let sig = parse_sign_response(&response).unwrap();
assert_eq!(sig, [0xBB; 64]);
}
#[test]
fn test_parse_ecdh_response() {
// 7C 22 82 20 <32 bytes secret>
let mut response = vec![0x7C, 0x22, 0x82, 0x20];
response.extend_from_slice(&[0xCC; 32]);
let secret = parse_ecdh_response(&response).unwrap();
assert_eq!(secret, [0xCC; 32]);
}
#[test]
fn test_parse_generate_response_wrong_size() {
let mut response = vec![0x7F, 0x49, 0x12, 0x86, 0x10];
response.extend_from_slice(&[0xAA; 16]);
assert!(parse_generate_response(&response).is_err());
}
#[test]
fn test_der_length_short() {
let mut buf = Vec::new();
encode_der_length(32, &mut buf);
assert_eq!(buf, vec![0x20]);
}
#[test]
fn test_der_length_medium() {
let mut buf = Vec::new();
encode_der_length(200, &mut buf);
assert_eq!(buf, vec![0x81, 0xC8]);
}
#[test]
fn test_der_length_long() {
let mut buf = Vec::new();
encode_der_length(500, &mut buf);
assert_eq!(buf, vec![0x82, 0x01, 0xF4]);
}
#[test]
fn test_decode_der_length() {
assert_eq!(decode_der_length(&[0x20]), Some((32, 1)));
assert_eq!(decode_der_length(&[0x81, 0xC8]), Some((200, 2)));
assert_eq!(decode_der_length(&[0x82, 0x01, 0xF4]), Some((500, 3)));
}
#[test]
fn test_sign_large_message_der_length() {
// >127 bytes: DER extended length (0x81 prefix).
let message = vec![0xAA; 200];
let apdu = sign_ed25519(SLOT_AUTHENTICATION, &message);
let response_request_pos = apdu.iter().position(|&b| b == TAG_AUTH_RESPONSE).unwrap();
let challenge_tag_pos = response_request_pos + 2;
assert_eq!(apdu[challenge_tag_pos], TAG_AUTH_CHALLENGE);
assert_eq!(apdu[challenge_tag_pos + 1], 0x81);
assert_eq!(apdu[challenge_tag_pos + 2], 200);
assert_eq!(
&apdu[challenge_tag_pos + 3..challenge_tag_pos + 3 + 200],
&message[..]
);
}
}
+445
View File
@@ -0,0 +1,445 @@
//! YubiKey PIV attestation verification. Bundled root CAs — never fetched.
//!
//! Legacy chain (firmware < 5.7.4):
//! Yubico PIV Root CA Serial 263751 → device intermediate (slot F9) → per-key attestation cert.
//!
//! New chain (firmware >= 5.7.4):
//! Yubico Attestation Root 1 → Intermediate A/B 1 → PIV Attestation A/B 1
//! → device intermediate (slot F9) → per-key attestation cert.
//!
//! Nitrokey 3 does not support PIV attestation (firmware 1.8) — verification skipped.
//!
//! Chain verification status: structural + OID extraction only. The
//! `verified` flag remains false until X.509 path validation is exercised
//! against real devices. See crates/rns-ratkey/HARDWARE_STATUS.md.
use crate::error::RatkeyError;
/// Yubico PIV Root CA (legacy, firmware < 5.7.4). Subject: "Yubico PIV Root CA Serial 263751".
pub const YUBICO_PIV_ROOT_CA_LEGACY_PEM: &str =
include_str!("../certs/yubico-piv-root-ca-legacy.pem");
/// Yubico Attestation Root 1 (firmware >= 5.7.4). Subject: "Yubico Attestation Root 1".
pub const YUBICO_ATTESTATION_ROOT_1_PEM: &str =
include_str!("../certs/yubico-attestation-root-1.pem");
/// SHA-256 fingerprint of the legacy Yubico PIV Root CA (belt-and-suspenders vs PEM swap).
pub const YUBICO_LEGACY_ROOT_SHA256: &str =
"63ece914e54dd87915f34033c85af4c0696ba1512f8add66ced73833120785b546";
/// SHA-256 fingerprint of the new Yubico Attestation Root 1 (belt-and-suspenders vs PEM swap).
pub const YUBICO_NEW_ROOT_SHA256: &str =
"62760c6a6ef91679f454c8902b80fd009825b3f25da90f1fbace2ec6586cd5a8";
// Yubico PIV attestation OIDs. Yubico PEN: 1.3.6.1.4.1.41482; PIV attestation subtree: .3.
/// Firmware version (3 bytes: major.minor.patch).
pub const OID_FIRMWARE_VERSION: &[u8] =
&[0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xC4, 0x0A, 0x03, 0x03];
/// Serial number (INTEGER).
pub const OID_SERIAL_NUMBER: &[u8] = &[0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xC4, 0x0A, 0x03, 0x07];
/// Usage policy (2 bytes: pin_policy, touch_policy).
pub const OID_USAGE_POLICY: &[u8] = &[0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xC4, 0x0A, 0x03, 0x08];
/// Form factor (1 byte).
pub const OID_FORM_FACTOR: &[u8] = &[0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xC4, 0x0A, 0x03, 0x09];
#[derive(Debug, Clone)]
pub struct AttestationInfo {
pub firmware_version: Option<(u8, u8, u8)>,
pub serial_number: Option<u32>,
pub pin_policy: Option<u8>,
pub touch_policy: Option<u8>,
pub form_factor: Option<u8>,
pub attestation_cert_der: Vec<u8>,
/// Device intermediate (slot F9) DER.
pub device_cert_der: Vec<u8>,
}
#[derive(Debug, Clone)]
pub struct AttestationVerification {
/// True only when the attestation certificate chain has been
/// cryptographically verified to a bundled trusted root.
pub verified: bool,
/// True when Yubico attestation metadata could be extracted from the cert.
pub metadata_extracted: bool,
/// Explicit chain-verification label for UI/CLI surfaces.
pub chain_verified: bool,
pub info: AttestationInfo,
/// "legacy" or "new".
pub root_ca: String,
pub description: String,
}
/// Verify chain: attestation cert (from ATTEST) + device intermediate (slot F9).
/// Currently structural + OID extraction only.
pub fn verify_attestation(
attestation_cert_der: &[u8],
device_cert_der: &[u8],
) -> Result<AttestationVerification, RatkeyError> {
let info = extract_attestation_info(attestation_cert_der, device_cert_der)?;
let metadata_extracted = info.firmware_version.is_some();
let chain_verified = false;
let root_ca = if let Some((major, minor, patch)) = info.firmware_version {
if major > 5 || (major == 5 && minor >= 7 && patch >= 4) {
"new".to_string()
} else {
"legacy".to_string()
}
} else {
"unknown".to_string()
};
let description = if metadata_extracted {
let (maj, min, pat) = info.firmware_version.unwrap_or((0, 0, 0));
format!(
"YubiKey firmware {maj}.{min}.{pat}{}; attestation chain not cryptographically verified",
info.serial_number
.map(|s| format!(", serial {s}"))
.unwrap_or_default()
)
} else {
"could not extract YubiKey attestation metadata".to_string()
};
Ok(AttestationVerification {
verified: chain_verified,
metadata_extracted,
chain_verified,
info,
root_ca,
description,
})
}
/// YubiKey 5 (firmware >= 4.3.0) only. Nitrokey 3 has no PIV attestation.
pub fn supports_attestation(device_type: &str) -> bool {
device_type == "yubikey5"
}
fn extract_attestation_info(
attestation_cert_der: &[u8],
device_cert_der: &[u8],
) -> Result<AttestationInfo, RatkeyError> {
let firmware = find_oid_value(attestation_cert_der, OID_FIRMWARE_VERSION).and_then(|v| {
if v.len() >= 3 {
Some((v[0], v[1], v[2]))
} else {
None
}
});
let serial = find_oid_value(attestation_cert_der, OID_SERIAL_NUMBER)
.and_then(|v| parse_asn1_integer(&v));
let (pin_policy, touch_policy) = find_oid_value(attestation_cert_der, OID_USAGE_POLICY)
.map(|v| {
let pp = v.first().copied();
let tp = v.get(1).copied();
(pp, tp)
})
.unwrap_or((None, None));
let form_factor =
find_oid_value(attestation_cert_der, OID_FORM_FACTOR).and_then(|v| v.first().copied());
Ok(AttestationInfo {
firmware_version: firmware,
serial_number: serial,
pin_policy,
touch_policy,
form_factor,
attestation_cert_der: attestation_cert_der.to_vec(),
device_cert_der: device_cert_der.to_vec(),
})
}
// Byte-scan DER for OID pattern, return TLV value after it. Avoids full ASN.1 parser dependency.
fn find_oid_value(der: &[u8], oid_bytes: &[u8]) -> Option<Vec<u8>> {
let oid_with_tag = {
let mut v = Vec::with_capacity(2 + oid_bytes.len());
v.push(0x06); // OID tag
v.push(oid_bytes.len() as u8);
v.extend_from_slice(oid_bytes);
v
};
let pos = der
.windows(oid_with_tag.len())
.position(|w| w == oid_with_tag.as_slice())?;
let after_oid = pos + oid_with_tag.len();
if after_oid >= der.len() {
return None;
}
let tag = der[after_oid];
if after_oid + 1 >= der.len() {
return None;
}
let (value_len, len_bytes) = decode_der_length(&der[after_oid + 1..])?;
let value_start = after_oid + 1 + len_bytes;
let value_end = value_start + value_len;
if value_end > der.len() {
return None;
}
let value = &der[value_start..value_end];
// Unwrap one level if OCTET STRING wraps another OCTET STRING or INTEGER.
if tag == 0x04 && value.len() >= 2 {
let inner_tag = value[0];
if inner_tag == 0x04 || inner_tag == 0x02 {
if let Some((inner_len, inner_len_bytes)) = decode_der_length(&value[1..]) {
let inner_start = 1 + inner_len_bytes;
if inner_start + inner_len <= value.len() {
return Some(value[inner_start..inner_start + inner_len].to_vec());
}
}
}
return Some(value.to_vec());
}
Some(value.to_vec())
}
fn parse_asn1_integer(bytes: &[u8]) -> Option<u32> {
if bytes.is_empty() || bytes.len() > 4 {
return None;
}
let mut result: u32 = 0;
for &b in bytes {
result = result.checked_shl(8)?.checked_add(b as u32)?;
}
Some(result)
}
fn decode_der_length(data: &[u8]) -> Option<(usize, usize)> {
if data.is_empty() {
return None;
}
let first = data[0];
if first < 0x80 {
Some((first as usize, 1))
} else if first == 0x81 {
data.get(1).map(|&b| (b as usize, 2))
} else if first == 0x82 {
if data.len() < 3 {
return None;
}
Some((((data[1] as usize) << 8) | data[2] as usize, 3))
} else {
None
}
}
pub fn pem_to_der(pem: &str) -> Option<Vec<u8>> {
let lines: Vec<&str> = pem.lines().filter(|l| !l.starts_with("-----")).collect();
let b64: String = lines.join("");
base64_decode(&b64)
}
// Standard alphabet, padding optional.
fn base64_decode(input: &str) -> Option<Vec<u8>> {
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
fn val(c: u8) -> Option<u8> {
TABLE.iter().position(|&b| b == c).map(|p| p as u8)
}
let bytes: Vec<u8> = input
.bytes()
.filter(|&b| b != b'=' && b != b'\n' && b != b'\r' && b != b' ')
.collect();
let mut out = Vec::with_capacity(bytes.len() * 3 / 4);
let mut i = 0;
while i + 3 < bytes.len() {
let a = val(bytes[i])?;
let b = val(bytes[i + 1])?;
let c = val(bytes[i + 2])?;
let d = val(bytes[i + 3])?;
out.push((a << 2) | (b >> 4));
out.push((b << 4) | (c >> 2));
out.push((c << 6) | d);
i += 4;
}
let remaining = bytes.len() - i;
if remaining >= 2 {
let a = val(bytes[i])?;
let b = val(bytes[i + 1])?;
out.push((a << 2) | (b >> 4));
if remaining >= 3 {
let c = val(bytes[i + 2])?;
out.push((b << 4) | (c >> 2));
}
}
Some(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_legacy_root_ca_loads() {
let der = pem_to_der(YUBICO_PIV_ROOT_CA_LEGACY_PEM);
assert!(der.is_some(), "legacy root CA PEM should decode");
let der = der.unwrap();
assert!(der.len() > 500, "DER should be substantial");
// DER starts with SEQUENCE tag (0x30)
assert_eq!(der[0], 0x30, "DER must start with SEQUENCE tag");
}
#[test]
fn test_new_root_ca_loads() {
let der = pem_to_der(YUBICO_ATTESTATION_ROOT_1_PEM);
assert!(der.is_some(), "new root CA PEM should decode");
let der = der.unwrap();
assert!(der.len() > 500);
assert_eq!(der[0], 0x30);
}
#[test]
fn test_pem_to_der_roundtrip() {
let pem = "-----BEGIN CERTIFICATE-----\nTUlJ\n-----END CERTIFICATE-----\n";
let der = pem_to_der(pem);
assert!(der.is_some());
}
#[test]
fn test_supports_attestation() {
assert!(supports_attestation("yubikey5"));
assert!(!supports_attestation("nitrokey3"));
assert!(!supports_attestation("unknown"));
}
#[test]
fn test_parse_asn1_integer() {
assert_eq!(parse_asn1_integer(&[0x01]), Some(1));
assert_eq!(parse_asn1_integer(&[0x00, 0xFF]), Some(255));
assert_eq!(parse_asn1_integer(&[0x01, 0x00, 0x00]), Some(65536));
assert_eq!(parse_asn1_integer(&[]), None);
assert_eq!(parse_asn1_integer(&[0x01, 0x02, 0x03, 0x04, 0x05]), None); // > 4 bytes
}
#[test]
fn test_find_oid_in_synthetic_der() {
// Build a minimal DER structure containing a Yubico firmware OID
// SEQUENCE { OID(firmware) OCTET_STRING(3 bytes: 05 07 01) }
let mut der = Vec::new();
// Outer SEQUENCE
let mut inner = Vec::new();
// OID tag + length + firmware OID bytes
inner.push(0x06); // OID tag
inner.push(OID_FIRMWARE_VERSION.len() as u8);
inner.extend_from_slice(OID_FIRMWARE_VERSION);
// OCTET STRING with firmware version 5.7.1
inner.push(0x04); // OCTET STRING tag
inner.push(0x03); // length = 3
inner.push(0x05); // major = 5
inner.push(0x07); // minor = 7
inner.push(0x01); // patch = 1
der.push(0x30); // SEQUENCE tag
der.push(inner.len() as u8);
der.extend_from_slice(&inner);
let value = find_oid_value(&der, OID_FIRMWARE_VERSION);
assert!(value.is_some(), "should find firmware OID");
let v = value.unwrap();
assert_eq!(v, vec![0x05, 0x07, 0x01], "firmware should be 5.7.1");
}
#[test]
fn test_find_oid_serial_number() {
// Build DER with serial number OID
let mut der = Vec::new();
let mut inner = Vec::new();
inner.push(0x06);
inner.push(OID_SERIAL_NUMBER.len() as u8);
inner.extend_from_slice(OID_SERIAL_NUMBER);
// INTEGER with serial 12345678 = 0x00BC614E
inner.push(0x02); // INTEGER tag
inner.push(0x04); // length = 4
inner.extend_from_slice(&[0x00, 0xBC, 0x61, 0x4E]);
der.push(0x30);
der.push(inner.len() as u8);
der.extend_from_slice(&inner);
let value = find_oid_value(&der, OID_SERIAL_NUMBER);
assert!(value.is_some());
let serial = parse_asn1_integer(&value.unwrap());
assert_eq!(serial, Some(12345678));
}
#[test]
fn test_verify_attestation_synthetic() {
// Build a minimal attestation cert with firmware OID
let mut attest_der = Vec::new();
let mut inner = Vec::new();
inner.push(0x06);
inner.push(OID_FIRMWARE_VERSION.len() as u8);
inner.extend_from_slice(OID_FIRMWARE_VERSION);
inner.push(0x04);
inner.push(0x03);
inner.extend_from_slice(&[0x05, 0x07, 0x01]); // 5.7.1
attest_der.push(0x30);
attest_der.push(inner.len() as u8);
attest_der.extend_from_slice(&inner);
// Minimal device cert (just a SEQUENCE)
let device_der = vec![0x30, 0x00];
let result = verify_attestation(&attest_der, &device_der).unwrap();
assert!(result.metadata_extracted);
assert!(!result.verified);
assert!(!result.chain_verified);
assert_eq!(result.root_ca, "legacy"); // 5.7.1 < 5.7.4
assert!(result.description.contains("5.7.1"));
assert!(
result
.description
.contains("not cryptographically verified")
);
}
#[test]
fn test_verify_attestation_new_firmware_metadata_only() {
let mut attest_der = Vec::new();
let mut inner = Vec::new();
inner.push(0x06);
inner.push(OID_FIRMWARE_VERSION.len() as u8);
inner.extend_from_slice(OID_FIRMWARE_VERSION);
inner.push(0x04);
inner.push(0x03);
inner.extend_from_slice(&[0x05, 0x07, 0x04]); // 5.7.4
attest_der.push(0x30);
attest_der.push(inner.len() as u8);
attest_der.extend_from_slice(&inner);
let device_der = vec![0x30, 0x00];
let result = verify_attestation(&attest_der, &device_der).unwrap();
assert!(result.metadata_extracted);
assert!(!result.verified);
assert!(!result.chain_verified);
assert_eq!(result.root_ca, "new"); // 5.7.4 → new root CA
}
#[test]
fn test_verify_attestation_empty_cert() {
let result = verify_attestation(&[], &[]).unwrap();
assert!(!result.verified);
assert!(!result.metadata_extracted);
assert!(!result.chain_verified);
assert_eq!(result.root_ca, "unknown");
}
}
+176
View File
@@ -0,0 +1,176 @@
//! PC/SC reader enumeration; filters to YubiKey 5 / Nitrokey 3 by reader name.
use pcsc::{Card, Context, Protocols, Scope, ShareMode};
use tracing::{debug, info, warn};
use crate::error::RatkeyError;
#[derive(Debug, Clone)]
pub struct DeviceInfo {
/// "yubikey5" or "nitrokey3".
pub device_type: String,
pub reader_name: String,
pub serial: Option<u32>,
pub firmware: Option<String>,
/// Slot 9A occupied.
pub has_signing_key: bool,
/// Slot 9D occupied.
pub has_encryption_key: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeviceType {
YubiKey5,
Nitrokey3,
Unknown,
}
impl DeviceType {
pub fn as_str(&self) -> &'static str {
match self {
DeviceType::YubiKey5 => "yubikey5",
DeviceType::Nitrokey3 => "nitrokey3",
DeviceType::Unknown => "unknown",
}
}
}
/// YubiKey readers contain "Yubico" / "YubiKey"; Nitrokey 3 contains "Nitrokey".
pub fn detect_device_type(reader_name: &str) -> DeviceType {
let lower = reader_name.to_lowercase();
if lower.contains("yubico") || lower.contains("yubikey") {
DeviceType::YubiKey5
} else if lower.contains("nitrokey") {
DeviceType::Nitrokey3
} else {
DeviceType::Unknown
}
}
pub fn list_readers() -> Result<Vec<String>, RatkeyError> {
let ctx = Context::establish(Scope::User)?;
let mut reader_buf = vec![0u8; 4096];
let readers = match ctx.list_readers(&mut reader_buf) {
Ok(readers) => readers,
Err(pcsc::Error::NoReadersAvailable) => {
return Ok(Vec::new());
}
Err(e) => return Err(e.into()),
};
let names: Vec<String> = readers.map(|r| r.to_string_lossy().to_string()).collect();
Ok(names)
}
pub fn detect_devices() -> Result<Vec<DeviceInfo>, RatkeyError> {
let readers = list_readers()?;
let mut devices = Vec::new();
for reader_name in &readers {
let device_type = detect_device_type(reader_name);
if device_type == DeviceType::Unknown {
debug!("skipping non-RATKEY reader: {}", reader_name);
continue;
}
info!(
"found potential device: {} ({})",
reader_name,
device_type.as_str()
);
match try_connect_piv(reader_name) {
Ok(info) => {
devices.push(DeviceInfo {
device_type: device_type.as_str().to_string(),
reader_name: reader_name.clone(),
serial: info.serial,
firmware: info.firmware,
has_signing_key: info.has_signing_key,
has_encryption_key: info.has_encryption_key,
});
}
Err(e) => {
warn!("failed to connect to {}: {}", reader_name, e);
}
}
}
Ok(devices)
}
fn try_connect_piv(reader_name: &str) -> Result<DeviceInfo, RatkeyError> {
use crate::apdu;
let ctx = Context::establish(Scope::User)?;
let reader = std::ffi::CString::new(reader_name)
.map_err(|_| RatkeyError::UnsupportedDevice(reader_name.to_string()))?;
let card = ctx.connect(&reader, ShareMode::Shared, Protocols::ANY)?;
let select_cmd = apdu::select_piv();
let mut response_buf = vec![0u8; 256];
let response = card.transmit(&select_cmd, &mut response_buf)?;
apdu::check_response(response)?;
debug!("PIV applet selected on {}", reader_name);
let device_type = detect_device_type(reader_name);
// GET METADATA success = slot occupied. Errors treated as empty so partially
// provisioned tokens still detect.
let meta_9a_cmd = apdu::get_metadata(apdu::SLOT_AUTHENTICATION);
let mut meta_buf = vec![0u8; 256];
let has_signing = match card.transmit(&meta_9a_cmd, &mut meta_buf) {
Ok(resp) => apdu::check_response(resp).is_ok(),
Err(_) => false,
};
let meta_9d_cmd = apdu::get_metadata(apdu::SLOT_KEY_MANAGEMENT);
let mut meta_buf2 = vec![0u8; 256];
let has_encryption = match card.transmit(&meta_9d_cmd, &mut meta_buf2) {
Ok(resp) => apdu::check_response(resp).is_ok(),
Err(_) => false,
};
let (serial, firmware) = read_identity(&card, device_type);
Ok(DeviceInfo {
device_type: device_type.as_str().to_string(),
reader_name: reader_name.to_string(),
serial,
firmware,
has_signing_key: has_signing,
has_encryption_key: has_encryption,
})
}
/// Best-effort serial/firmware read. Yubico proprietary INS — Nitrokey 3 returns (None, None).
/// APDU errors are tolerated; never fails a connection.
pub(crate) fn read_identity(card: &Card, device_type: DeviceType) -> (Option<u32>, Option<String>) {
use crate::apdu;
if device_type != DeviceType::YubiKey5 {
return (None, None);
}
let mut buf = vec![0u8; 256];
let serial = card
.transmit(&apdu::get_serial(), &mut buf)
.ok()
.and_then(|resp| apdu::check_response(resp).ok().map(<[u8]>::to_vec))
.and_then(|data| apdu::parse_serial_response(&data).ok());
let firmware = card
.transmit(&apdu::get_version(), &mut buf)
.ok()
.and_then(|resp| apdu::check_response(resp).ok().map(<[u8]>::to_vec))
.and_then(|data| apdu::parse_version_response(&data).ok())
.map(|(maj, min, patch)| format!("{maj}.{min}.{patch}"));
(serial, firmware)
}
+58
View File
@@ -0,0 +1,58 @@
use thiserror::Error;
#[derive(Debug, Error)]
pub enum RatkeyError {
#[error("no hardware token found")]
NoDevice,
#[error("hardware token disconnected")]
Disconnected,
#[error("PIN verification failed ({remaining} attempts remaining)")]
PinFailed { remaining: u8 },
/// PIN locked (retry counter exhausted); PUK required to unlock.
#[error("PIN locked — device requires PUK to unlock")]
PinLocked,
#[error("PIN required — call verify_pin() first")]
PinRequired,
#[error("touch required on hardware token")]
TouchRequired,
#[error("PIV slot 0x{slot:02X} has no key")]
EmptySlot { slot: u8 },
#[error("PIV slot 0x{slot:02X} already contains a key")]
SlotOccupied { slot: u8 },
#[error("unsupported device: {0}")]
UnsupportedDevice(String),
#[error("firmware version {found} does not meet minimum {required}")]
FirmwareVersion { required: String, found: String },
#[error("key mismatch: hardware public key does not match .hwid file")]
KeyMismatch,
#[cfg(feature = "hardware")]
#[error("PC/SC error: {0}")]
Pcsc(#[from] pcsc::Error),
/// ISO 7816-4 status word (SW1/SW2) returned by the card.
#[error("APDU error: SW={sw1:02X}{sw2:02X}")]
Apdu { sw1: u8, sw2: u8 },
#[error("invalid .hwid file: {0}")]
InvalidHwid(String),
#[error("signing failed: {0}")]
SigningFailed(String),
#[error("ECDH failed: {0}")]
EcdhFailed(String),
#[error("io error: {0}")]
Io(#[from] std::io::Error),
}
+369
View File
@@ -0,0 +1,369 @@
//! `HardwareIdentity`: public-key-only `Identity` + PIV session for private ops.
//! Wire-compatible with software identities.
use std::path::Path;
use rns_crypto::hkdf::derive_key_64;
use rns_crypto::token;
use rns_identity::identity::Identity;
use crate::error::RatkeyError;
use crate::hwid::HwidConfig;
use crate::mock::{MockPivSession, SLOT_9A, SLOT_9D};
pub struct HardwareIdentity {
pub identity: Identity,
pub config: HwidConfig,
ed25519_pub: [u8; 32],
x25519_pub: [u8; 32],
// Mock session storage keeps the current API testable until the real PIV
// backend is wired. See crates/rns-ratkey/HARDWARE_STATUS.md.
mock_session: Option<MockPivSession>,
}
impl HardwareIdentity {
pub fn from_hwid_mock(
config: HwidConfig,
session: MockPivSession,
) -> Result<Self, RatkeyError> {
let ed25519_pub = config.ed25519_pub_bytes()?;
let x25519_pub = config.x25519_pub_bytes()?;
// Fail closed: published identity hash must map to keys actually on the device.
let session_ed = session.read_ed25519_public(SLOT_9A)?;
let session_x = session.read_x25519_public(SLOT_9D)?;
if session_ed != ed25519_pub || session_x != x25519_pub {
return Err(RatkeyError::KeyMismatch);
}
let mut pub_key_bytes = [0u8; 64];
pub_key_bytes[..32].copy_from_slice(&x25519_pub);
pub_key_bytes[32..].copy_from_slice(&ed25519_pub);
let identity = Identity::from_public_key(&pub_key_bytes)
.map_err(|e| RatkeyError::InvalidHwid(format!("cannot create identity: {e}")))?;
Ok(Self {
identity,
config,
ed25519_pub,
x25519_pub,
mock_session: Some(session),
})
}
pub fn from_file_mock(path: &Path, session: MockPivSession) -> Result<Self, RatkeyError> {
let config = HwidConfig::from_file(path)?;
Self::from_hwid_mock(config, session)
}
/// Test-only: build without `.hwid`; skips key-mismatch guard.
pub fn from_keys_mock(
ed25519_pub: [u8; 32],
x25519_pub: [u8; 32],
session: MockPivSession,
) -> Result<Self, RatkeyError> {
let config = HwidConfig {
identity: crate::hwid::HwidIdentity {
hash: String::new(),
nickname: "test".to_string(),
created_at: 0,
},
device: crate::hwid::HwidDevice {
device_type: session.device_type.clone(),
serial: session.serial,
firmware: session.firmware.clone(),
},
keys: crate::hwid::HwidKeys {
ed25519_pub: hex::encode(ed25519_pub),
x25519_pub: hex::encode(x25519_pub),
},
slots: crate::hwid::HwidSlots {
signing: "9A".to_string(),
encryption: "9D".to_string(),
},
policy: crate::hwid::HwidPolicy {
pin_cache_timeout: 300,
touch_signing: "never".to_string(),
touch_encryption: "never".to_string(),
},
attestation: Default::default(),
app: Default::default(),
backup: Default::default(),
};
let mut pub_key_bytes = [0u8; 64];
pub_key_bytes[..32].copy_from_slice(&x25519_pub);
pub_key_bytes[32..].copy_from_slice(&ed25519_pub);
let identity = Identity::from_public_key(&pub_key_bytes)
.map_err(|e| RatkeyError::InvalidHwid(format!("cannot create identity: {e}")))?;
let mut config = config;
// Hash is derived from the Identity so the .hwid stays consistent.
config.identity.hash = hex::encode(identity.hash);
Ok(Self {
identity,
config,
ed25519_pub,
x25519_pub,
mock_session: Some(session),
})
}
pub fn hash(&self) -> &[u8; 16] {
&self.identity.hash
}
pub fn hash_hex(&self) -> String {
hex::encode(self.identity.hash)
}
/// 64-byte public key (X25519_pub || Ed25519_pub).
pub fn get_public_key(&self) -> [u8; 64] {
self.identity.get_public_key()
}
pub fn ed25519_public(&self) -> &[u8; 32] {
&self.ed25519_pub
}
pub fn x25519_public(&self) -> &[u8; 32] {
&self.x25519_pub
}
pub fn as_identity(&self) -> &Identity {
&self.identity
}
pub fn sign(&mut self, message: &[u8]) -> Result<[u8; 64], RatkeyError> {
let session = self.mock_session.as_mut().ok_or(RatkeyError::NoDevice)?;
session.sign_ed25519(SLOT_9A, message)
}
pub fn ecdh(&mut self, peer_pub_bytes: &[u8; 32]) -> Result<[u8; 32], RatkeyError> {
let session = self.mock_session.as_mut().ok_or(RatkeyError::NoDevice)?;
session.ecdh_x25519(SLOT_9D, peer_pub_bytes)
}
/// Ciphertext = ephemeral_pub(32) || AES-256-CBC token. Mirrors `Identity::decrypt`
/// but does the ECDH on-device.
pub fn decrypt(
&mut self,
ciphertext: &[u8],
ratchets: Option<&[&[u8; 32]]>,
enforce_ratchets: bool,
) -> Result<Vec<u8>, RatkeyError> {
if ciphertext.len() <= 32 {
return Err(RatkeyError::EcdhFailed("ciphertext too short".to_string()));
}
let ephemeral_pub_bytes: [u8; 32] = ciphertext[..32]
.try_into()
.map_err(|_| RatkeyError::EcdhFailed("invalid ephemeral key".to_string()))?;
let encrypted_token = &ciphertext[32..];
// PIV cannot store Reticulum ratchet private keys. This backend skips
// ratchet keys and falls back to identity ECDH; enforced ratchets fail
// closed.
if let Some(ratchet_keys) = ratchets {
for _ratchet_pub in ratchet_keys {}
if enforce_ratchets {
return Err(RatkeyError::EcdhFailed(
"no valid ratchet key found and ratchets enforced".to_string(),
));
}
}
let shared_secret = self.ecdh(&ephemeral_pub_bytes)?;
// HKDF-SHA256, salt = identity hash. Matches Identity::decrypt.
let derived = derive_key_64(&shared_secret, &self.identity.hash)
.map_err(|_| RatkeyError::EcdhFailed("HKDF derivation failed".to_string()))?;
token::decrypt(encrypted_token, &derived)
.map_err(|_| RatkeyError::EcdhFailed("decryption failed".to_string()))
}
/// Verification is a public-key op; no hardware call.
pub fn verify(&self, message: &[u8], signature: &[u8; 64]) -> bool {
self.identity.verify(message, signature)
}
pub fn is_connected(&self) -> bool {
self.mock_session.as_ref().is_some_and(|s| s.is_connected())
}
}
#[cfg(test)]
mod tests {
use super::*;
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
use rns_identity::identity::Identity;
#[test]
fn test_from_keys_mock() {
let session = MockPivSession::with_keys();
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
assert_eq!(hw.ed25519_public(), &ed_pub);
assert_eq!(hw.x25519_public(), &x_pub);
assert!(!hw.hash_hex().is_empty());
}
#[test]
fn test_sign_and_verify() {
let session = MockPivSession::with_keys();
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
let message = b"ratkey hardware identity test";
let sig = hw.sign(message).unwrap();
assert!(hw.verify(message, &sig));
}
#[test]
fn test_sign_matches_software_identity() {
// Load-bearing: Ed25519 is deterministic, hardware and software paths
// MUST be byte-identical for shared key material.
let ed_seed = [0x42u8; 32];
let x_secret = [0x43u8; 32];
let session = MockPivSession::with_key_bytes(&ed_seed, &x_secret);
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
let mut prv_bytes = [0u8; 64];
prv_bytes[..32].copy_from_slice(&x_secret);
prv_bytes[32..].copy_from_slice(&ed_seed);
let sw_identity = Identity::from_private_key(&prv_bytes).unwrap();
let message = b"cross-validation test";
let hw_sig = hw.sign(message).unwrap();
let sw_sig = sw_identity.sign(message).unwrap();
assert_eq!(
hw_sig, sw_sig,
"hardware and software signatures must match"
);
assert_eq!(hw.identity.hash, sw_identity.hash);
assert_eq!(hw.get_public_key(), sw_identity.get_public_key());
}
#[test]
fn test_ecdh_with_software_peer() {
let session = MockPivSession::with_keys();
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
let peer_prv = X25519PrivateKey::generate();
let peer_pub = peer_prv.public_key();
let peer_pub_bytes = peer_pub.to_bytes();
let hw_shared = hw.ecdh(&peer_pub_bytes).unwrap();
let hw_pub = X25519PublicKey::from_bytes(&x_pub);
let sw_shared = peer_prv.exchange(&hw_pub);
assert_eq!(hw_shared, sw_shared, "ECDH must be symmetric");
}
#[test]
fn test_encrypt_decrypt_round_trip() {
let ed_seed = [0x42u8; 32];
let x_secret = [0x43u8; 32];
let session = MockPivSession::with_key_bytes(&ed_seed, &x_secret);
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
let mut prv_bytes = [0u8; 64];
prv_bytes[..32].copy_from_slice(&x_secret);
prv_bytes[32..].copy_from_slice(&ed_seed);
let sw_identity = Identity::from_private_key(&prv_bytes).unwrap();
let plaintext = b"secret message for hardware identity";
let ciphertext = sw_identity.encrypt(plaintext, None).unwrap();
let decrypted = hw.decrypt(&ciphertext, None, false).unwrap();
assert_eq!(decrypted, plaintext);
}
#[test]
fn test_encrypt_from_other_identity() {
let session = MockPivSession::with_keys();
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
let _sender = Identity::new();
let ciphertext = hw.identity.encrypt(b"hello from sender", None).unwrap();
let decrypted = hw.decrypt(&ciphertext, None, false).unwrap();
assert_eq!(decrypted, b"hello from sender");
}
#[test]
fn test_disconnect_fails_operations() {
let session = MockPivSession::with_keys();
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
assert!(hw.is_connected());
hw.mock_session.as_mut().unwrap().disconnect();
assert!(!hw.is_connected());
assert!(matches!(hw.sign(b"test"), Err(RatkeyError::Disconnected)));
}
#[test]
fn test_key_mismatch_rejected() {
// from_keys_mock does not cross-check; the .hwid path does (test_hwid_key_mismatch).
let session = MockPivSession::with_keys();
let wrong_ed = [0xFFu8; 32];
let wrong_x = [0xFFu8; 32];
let _result = HardwareIdentity::from_keys_mock(wrong_ed, wrong_x, session);
}
#[test]
fn test_hwid_key_mismatch() {
let session = MockPivSession::with_keys();
let config = HwidConfig {
identity: crate::hwid::HwidIdentity {
hash: "test".to_string(),
nickname: "test".to_string(),
created_at: 0,
},
device: crate::hwid::HwidDevice {
device_type: "yubikey5".to_string(),
serial: 99999999,
firmware: "5.7.1".to_string(),
},
keys: crate::hwid::HwidKeys {
ed25519_pub: "ff".repeat(32),
x25519_pub: "ff".repeat(32),
},
slots: crate::hwid::HwidSlots {
signing: "9A".to_string(),
encryption: "9D".to_string(),
},
policy: crate::hwid::HwidPolicy {
pin_cache_timeout: 300,
touch_signing: "never".to_string(),
touch_encryption: "never".to_string(),
},
attestation: Default::default(),
app: Default::default(),
backup: Default::default(),
};
let result = HardwareIdentity::from_hwid_mock(config, session);
assert!(matches!(result, Err(RatkeyError::KeyMismatch)));
}
}
+332
View File
@@ -0,0 +1,332 @@
//! `.hwid` TOML: public metadata for a hardware identity. No private key material ever.
//! Location: `<reticulum-config-dir>/identities/{hash_hex}/identity.hwid`.
use std::path::Path;
use std::str::FromStr;
use serde::{Deserialize, Serialize};
use crate::error::RatkeyError;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HwidConfig {
pub identity: HwidIdentity,
pub device: HwidDevice,
pub keys: HwidKeys,
pub slots: HwidSlots,
pub policy: HwidPolicy,
#[serde(default)]
pub attestation: HwidAttestation,
#[serde(default)]
pub app: HwidApp,
#[serde(default)]
pub backup: HwidBackup,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HwidIdentity {
/// 16-byte hash (32 hex chars).
pub hash: String,
#[serde(default)]
pub nickname: String,
pub created_at: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HwidDevice {
/// "yubikey5" or "nitrokey3".
#[serde(rename = "type")]
pub device_type: String,
pub serial: u32,
pub firmware: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HwidKeys {
/// 32-byte hex.
pub ed25519_pub: String,
/// 32-byte hex.
pub x25519_pub: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HwidSlots {
/// PIV slot hex (e.g. "9A").
pub signing: String,
/// PIV slot hex (e.g. "9D").
pub encryption: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HwidPolicy {
/// Seconds; 0 = never cache.
#[serde(default = "default_pin_cache_timeout")]
pub pin_cache_timeout: u64,
/// "always" | "cached" | "never".
#[serde(default = "default_touch_signing")]
pub touch_signing: String,
/// "always" | "cached" | "never".
#[serde(default = "default_touch_encryption")]
pub touch_encryption: String,
}
fn default_pin_cache_timeout() -> u64 {
300
}
fn default_touch_signing() -> String {
"always".to_string()
}
fn default_touch_encryption() -> String {
"cached".to_string()
}
/// Attestation certificates (base64-encoded DER).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HwidAttestation {
#[serde(default)]
pub ed25519_cert: String,
#[serde(default)]
pub x25519_cert: String,
/// Cryptographic attestation-chain verification status. Metadata
/// extraction alone must not set this true.
#[serde(default)]
pub verified: bool,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HwidApp {
/// Pre-computed app destination hash (hex).
#[serde(default)]
pub app_hash: String,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HwidBackup {
/// 0=none, 1=device-clone, 2=encrypted-offline.
#[serde(default)]
pub tier: u8,
/// Tier 1 only.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub backup_serial: Option<u32>,
/// Tier 2 only: SHA-256 of encrypted backup.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub encrypted_backup_hash: Option<String>,
}
impl HwidConfig {
pub fn from_file(path: &Path) -> Result<Self, RatkeyError> {
let content = std::fs::read_to_string(path)
.map_err(|e| RatkeyError::InvalidHwid(format!("cannot read file: {e}")))?;
content.parse()
}
pub fn to_file(&self, path: &Path) -> Result<(), RatkeyError> {
let content = self.to_string()?;
// Atomic: write tmp, then rename.
let tmp_path = path.with_extension("hwid.tmp");
std::fs::write(&tmp_path, content)?;
std::fs::rename(&tmp_path, path)?;
Ok(())
}
pub fn to_string(&self) -> Result<String, RatkeyError> {
let header = "# RATKEY Hardware Identity \u{2014} DO NOT EDIT MANUALLY\n\
# Private keys exist ONLY on the hardware device.\n\n";
let body =
toml::to_string_pretty(self).map_err(|e| RatkeyError::InvalidHwid(e.to_string()))?;
Ok(format!("{header}{body}"))
}
pub fn ed25519_pub_bytes(&self) -> Result<[u8; 32], RatkeyError> {
decode_hex_32(&self.keys.ed25519_pub, "ed25519_pub")
}
pub fn x25519_pub_bytes(&self) -> Result<[u8; 32], RatkeyError> {
decode_hex_32(&self.keys.x25519_pub, "x25519_pub")
}
pub fn signing_slot(&self) -> Result<u8, RatkeyError> {
parse_slot(&self.slots.signing)
}
pub fn encryption_slot(&self) -> Result<u8, RatkeyError> {
parse_slot(&self.slots.encryption)
}
}
impl FromStr for HwidConfig {
type Err = RatkeyError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
toml::from_str(s).map_err(|e| RatkeyError::InvalidHwid(e.to_string()))
}
}
fn decode_hex_32(hex_str: &str, field: &str) -> Result<[u8; 32], RatkeyError> {
let bytes =
hex::decode(hex_str).map_err(|e| RatkeyError::InvalidHwid(format!("{field}: {e}")))?;
if bytes.len() != 32 {
return Err(RatkeyError::InvalidHwid(format!(
"{field}: expected 32 bytes, got {}",
bytes.len()
)));
}
let mut arr = [0u8; 32];
arr.copy_from_slice(&bytes);
Ok(arr)
}
fn parse_slot(s: &str) -> Result<u8, RatkeyError> {
u8::from_str_radix(s.trim_start_matches("0x").trim_start_matches("0X"), 16)
.map_err(|e| RatkeyError::InvalidHwid(format!("invalid slot '{s}': {e}")))
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_config() -> HwidConfig {
HwidConfig {
identity: HwidIdentity {
hash: "a1b2c3d4e5f6a7b8a1b2c3d4e5f6a7b8".to_string(),
nickname: "Test YubiKey".to_string(),
created_at: 1711580400,
},
device: HwidDevice {
device_type: "yubikey5".to_string(),
serial: 12345678,
firmware: "5.7.1".to_string(),
},
keys: HwidKeys {
ed25519_pub: "aa".repeat(32),
x25519_pub: "bb".repeat(32),
},
slots: HwidSlots {
signing: "9A".to_string(),
encryption: "9D".to_string(),
},
policy: HwidPolicy {
pin_cache_timeout: 300,
touch_signing: "always".to_string(),
touch_encryption: "cached".to_string(),
},
attestation: HwidAttestation::default(),
app: HwidApp::default(),
backup: HwidBackup::default(),
}
}
#[test]
fn test_round_trip() {
let config = sample_config();
let toml_str = config.to_string().unwrap();
let parsed = toml_str.parse::<HwidConfig>().unwrap();
assert_eq!(parsed.identity.hash, config.identity.hash);
assert_eq!(parsed.identity.nickname, config.identity.nickname);
assert_eq!(parsed.device.device_type, config.device.device_type);
assert_eq!(parsed.device.serial, config.device.serial);
assert_eq!(parsed.keys.ed25519_pub, config.keys.ed25519_pub);
assert_eq!(parsed.keys.x25519_pub, config.keys.x25519_pub);
assert_eq!(parsed.slots.signing, config.slots.signing);
assert_eq!(parsed.slots.encryption, config.slots.encryption);
assert_eq!(
parsed.policy.pin_cache_timeout,
config.policy.pin_cache_timeout
);
assert_eq!(parsed.policy.touch_signing, config.policy.touch_signing);
assert_eq!(parsed.backup.tier, 0);
}
#[test]
fn test_decode_public_keys() {
let config = sample_config();
let ed_bytes = config.ed25519_pub_bytes().unwrap();
assert_eq!(ed_bytes, [0xAA; 32]);
let x_bytes = config.x25519_pub_bytes().unwrap();
assert_eq!(x_bytes, [0xBB; 32]);
}
#[test]
fn test_parse_slots() {
let config = sample_config();
assert_eq!(config.signing_slot().unwrap(), 0x9A);
assert_eq!(config.encryption_slot().unwrap(), 0x9D);
}
#[test]
fn test_invalid_hex() {
let mut config = sample_config();
config.keys.ed25519_pub = "not_hex".to_string();
assert!(config.ed25519_pub_bytes().is_err());
}
#[test]
fn test_wrong_key_length() {
let mut config = sample_config();
config.keys.ed25519_pub = "aa".repeat(16); // 16 bytes instead of 32
assert!(config.ed25519_pub_bytes().is_err());
}
#[test]
fn test_invalid_slot() {
let mut config = sample_config();
config.slots.signing = "ZZ".to_string();
assert!(config.signing_slot().is_err());
}
#[test]
fn test_toml_contains_header() {
let config = sample_config();
let toml_str = config.to_string().unwrap();
assert!(toml_str.contains("RATKEY Hardware Identity"));
assert!(toml_str.contains("DO NOT EDIT MANUALLY"));
}
#[test]
fn test_file_round_trip() {
let config = sample_config();
let dir = std::env::temp_dir().join("ratkey_test_hwid");
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("test.hwid");
config.to_file(&path).unwrap();
let loaded = HwidConfig::from_file(&path).unwrap();
assert_eq!(loaded.identity.hash, config.identity.hash);
assert_eq!(loaded.device.serial, config.device.serial);
assert_eq!(loaded.keys.ed25519_pub, config.keys.ed25519_pub);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn test_defaults_applied() {
let minimal = r#"
[identity]
hash = "aabb"
created_at = 1000
[device]
type = "yubikey5"
serial = 1
firmware = "5.7.0"
[keys]
ed25519_pub = "aa"
x25519_pub = "bb"
[slots]
signing = "9A"
encryption = "9D"
[policy]
"#;
let config = minimal.parse::<HwidConfig>().unwrap();
assert_eq!(config.policy.pin_cache_timeout, 300);
assert_eq!(config.policy.touch_signing, "always");
assert_eq!(config.policy.touch_encryption, "cached");
assert_eq!(config.backup.tier, 0);
assert!(config.attestation.ed25519_cert.is_empty());
}
}
+24
View File
@@ -0,0 +1,24 @@
//! Hardware-backed identity (YubiKey 5, Nitrokey 3) via PIV. Ed25519 sign + X25519
//! ECDH keys live on-device; only public keys and results leave the token.
//! Wire-compatible with software identities. `hardware` feature enables real PIV via `pcsc`.
pub mod apdu;
pub mod attestation;
pub mod error;
pub mod hardware;
pub mod hwid;
pub mod mock;
pub mod pin;
pub mod provision;
#[cfg(feature = "hardware")]
pub mod detect;
#[cfg(feature = "hardware")]
pub mod session;
pub use error::RatkeyError;
pub use hardware::HardwareIdentity;
pub use hwid::HwidConfig;
pub use mock::MockPivSession;
pub use pin::PinCache;
pub use provision::{ProvisionConfig, ProvisionResult};
+628
View File
@@ -0,0 +1,628 @@
//! In-memory PIV mock with real Ed25519/X25519 crypto; signatures/ECDH are bit-identical
//! to software results for test vector reuse. Simulates PIN retry/lockout, touch policy,
//! disconnect, slot state. Primary dev/validation env until hardware lands.
use std::collections::HashMap;
use rns_crypto::ed25519::{Ed25519PrivateKey, Ed25519PublicKey};
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
use zeroize::Zeroize;
use crate::error::RatkeyError;
/// Slot 9A: PIV Authentication — Ed25519 signing.
pub const SLOT_9A: u8 = 0x9A;
/// Slot 9D: PIV Key Management — X25519 ECDH.
pub const SLOT_9D: u8 = 0x9D;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TouchPolicy {
Never,
Always,
/// YubiKey ~15s cache.
Cached,
}
struct SlotState {
ed25519_prv: Option<Ed25519PrivateKey>,
ed25519_pub: Option<Ed25519PublicKey>,
x25519_prv: Option<X25519PrivateKey>,
x25519_pub: Option<X25519PublicKey>,
touch_policy: TouchPolicy,
}
impl SlotState {
fn empty() -> Self {
Self {
ed25519_prv: None,
ed25519_pub: None,
x25519_prv: None,
x25519_pub: None,
touch_policy: TouchPolicy::Never,
}
}
}
#[derive(Debug, Clone)]
pub enum MockOperation {
PinVerify { success: bool },
GenerateEd25519 { slot: u8 },
GenerateX25519 { slot: u8 },
SignEd25519 { slot: u8, data_len: usize },
EcdhX25519 { slot: u8 },
ReadPublicKey { slot: u8 },
}
pub struct MockPivSession {
slots: HashMap<u8, SlotState>,
pin: String,
pin_verified: bool,
pin_retries: u8,
max_retries: u8,
connected: bool,
/// True: `TouchPolicy::Always` slots reject ops. `simulate_touch()` clears.
touch_required: bool,
pub device_type: String,
pub serial: u32,
pub firmware: String,
pub operations: Vec<MockOperation>,
}
impl MockPivSession {
pub fn new() -> Self {
let mut slots = HashMap::new();
slots.insert(SLOT_9A, SlotState::empty());
slots.insert(SLOT_9D, SlotState::empty());
Self {
slots,
pin: "123456".to_string(),
pin_verified: false,
pin_retries: 3,
max_retries: 3,
connected: true,
touch_required: true,
device_type: "yubikey5".to_string(),
serial: 99999999,
firmware: "5.7.1".to_string(),
operations: Vec::new(),
}
}
/// Pre-populated slots 9A/9D; skips provision step for sign/ECDH tests.
pub fn with_keys() -> Self {
let mut session = Self::new();
session.pin_verified = true;
session.touch_required = false;
let ed_prv = Ed25519PrivateKey::generate();
let ed_pub = ed_prv.public_key();
let slot_9a = session.slots.get_mut(&SLOT_9A).unwrap();
slot_9a.ed25519_prv = Some(ed_prv);
slot_9a.ed25519_pub = Some(ed_pub);
let x_prv = X25519PrivateKey::generate();
let x_pub = x_prv.public_key();
let slot_9d = session.slots.get_mut(&SLOT_9D).unwrap();
slot_9d.x25519_prv = Some(x_prv);
slot_9d.x25519_pub = Some(x_pub);
session
}
/// Deterministic key material for test vectors.
pub fn with_key_bytes(ed25519_seed: &[u8; 32], x25519_secret: &[u8; 32]) -> Self {
let mut session = Self::new();
session.pin_verified = true;
session.touch_required = false;
let ed_prv = Ed25519PrivateKey::from_bytes(ed25519_seed);
let ed_pub = ed_prv.public_key();
let slot_9a = session.slots.get_mut(&SLOT_9A).unwrap();
slot_9a.ed25519_prv = Some(ed_prv);
slot_9a.ed25519_pub = Some(ed_pub);
let x_prv = X25519PrivateKey::from_bytes(x25519_secret);
let x_pub = x_prv.public_key();
let slot_9d = session.slots.get_mut(&SLOT_9D).unwrap();
slot_9d.x25519_prv = Some(x_prv);
slot_9d.x25519_pub = Some(x_pub);
session
}
pub fn set_pin(&mut self, pin: &str) {
self.pin = pin.to_string();
self.pin_verified = false;
}
pub fn disconnect(&mut self) {
self.connected = false;
}
pub fn reconnect(&mut self) {
self.connected = true;
self.pin_verified = false;
}
pub fn simulate_touch(&mut self) {
self.touch_required = false;
}
pub fn require_touch(&mut self) {
self.touch_required = true;
}
fn check_connected(&self) -> Result<(), RatkeyError> {
if !self.connected {
Err(RatkeyError::Disconnected)
} else {
Ok(())
}
}
fn check_pin(&self) -> Result<(), RatkeyError> {
if !self.pin_verified {
Err(RatkeyError::PinRequired)
} else {
Ok(())
}
}
fn check_touch(&self, slot: u8) -> Result<(), RatkeyError> {
if let Some(slot_state) = self.slots.get(&slot) {
if slot_state.touch_policy == TouchPolicy::Always && self.touch_required {
return Err(RatkeyError::TouchRequired);
}
}
Ok(())
}
pub fn is_connected(&self) -> bool {
self.connected
}
pub fn verify_pin(&mut self, pin: &str) -> Result<(), RatkeyError> {
self.check_connected()?;
if self.pin_retries == 0 {
self.operations
.push(MockOperation::PinVerify { success: false });
return Err(RatkeyError::PinLocked);
}
if pin == self.pin {
self.pin_verified = true;
self.pin_retries = self.max_retries;
self.operations
.push(MockOperation::PinVerify { success: true });
Ok(())
} else {
self.pin_retries -= 1;
self.operations
.push(MockOperation::PinVerify { success: false });
if self.pin_retries == 0 {
Err(RatkeyError::PinLocked)
} else {
Err(RatkeyError::PinFailed {
remaining: self.pin_retries,
})
}
}
}
pub fn generate_ed25519(
&mut self,
slot: u8,
touch_policy: TouchPolicy,
) -> Result<[u8; 32], RatkeyError> {
self.check_connected()?;
self.check_pin()?;
let slot_state = self
.slots
.get_mut(&slot)
.ok_or(RatkeyError::InvalidHwid(format!(
"unknown slot 0x{slot:02X}"
)))?;
if slot_state.ed25519_prv.is_some() {
return Err(RatkeyError::SlotOccupied { slot });
}
let prv = Ed25519PrivateKey::generate();
let pub_key = prv.public_key();
let pub_bytes = pub_key.to_bytes();
slot_state.ed25519_prv = Some(prv);
slot_state.ed25519_pub = Some(pub_key);
slot_state.touch_policy = touch_policy;
self.operations
.push(MockOperation::GenerateEd25519 { slot });
Ok(pub_bytes)
}
pub fn generate_x25519(
&mut self,
slot: u8,
touch_policy: TouchPolicy,
) -> Result<[u8; 32], RatkeyError> {
self.check_connected()?;
self.check_pin()?;
let slot_state = self
.slots
.get_mut(&slot)
.ok_or(RatkeyError::InvalidHwid(format!(
"unknown slot 0x{slot:02X}"
)))?;
if slot_state.x25519_prv.is_some() {
return Err(RatkeyError::SlotOccupied { slot });
}
let prv = X25519PrivateKey::generate();
let pub_key = prv.public_key();
let pub_bytes = pub_key.to_bytes();
slot_state.x25519_prv = Some(prv);
slot_state.x25519_pub = Some(pub_key);
slot_state.touch_policy = touch_policy;
self.operations.push(MockOperation::GenerateX25519 { slot });
Ok(pub_bytes)
}
pub fn sign_ed25519(&mut self, slot: u8, data: &[u8]) -> Result<[u8; 64], RatkeyError> {
self.check_connected()?;
self.check_pin()?;
self.check_touch(slot)?;
let slot_state = self
.slots
.get(&slot)
.ok_or(RatkeyError::InvalidHwid(format!(
"unknown slot 0x{slot:02X}"
)))?;
let prv = slot_state
.ed25519_prv
.as_ref()
.ok_or(RatkeyError::EmptySlot { slot })?;
let sig = prv.sign(data);
self.operations.push(MockOperation::SignEd25519 {
slot,
data_len: data.len(),
});
Ok(sig)
}
pub fn ecdh_x25519(
&mut self,
slot: u8,
peer_pub_bytes: &[u8; 32],
) -> Result<[u8; 32], RatkeyError> {
self.check_connected()?;
self.check_pin()?;
self.check_touch(slot)?;
let slot_state = self
.slots
.get(&slot)
.ok_or(RatkeyError::InvalidHwid(format!(
"unknown slot 0x{slot:02X}"
)))?;
let prv = slot_state
.x25519_prv
.as_ref()
.ok_or(RatkeyError::EmptySlot { slot })?;
let peer_pub = X25519PublicKey::from_bytes(peer_pub_bytes);
let shared = prv.exchange(&peer_pub);
self.operations.push(MockOperation::EcdhX25519 { slot });
Ok(shared)
}
pub fn read_ed25519_public(&self, slot: u8) -> Result<[u8; 32], RatkeyError> {
self.check_connected()?;
let slot_state = self
.slots
.get(&slot)
.ok_or(RatkeyError::InvalidHwid(format!(
"unknown slot 0x{slot:02X}"
)))?;
let pub_key = slot_state
.ed25519_pub
.as_ref()
.ok_or(RatkeyError::EmptySlot { slot })?;
Ok(pub_key.to_bytes())
}
pub fn read_x25519_public(&self, slot: u8) -> Result<[u8; 32], RatkeyError> {
self.check_connected()?;
let slot_state = self
.slots
.get(&slot)
.ok_or(RatkeyError::InvalidHwid(format!(
"unknown slot 0x{slot:02X}"
)))?;
let pub_key = slot_state
.x25519_pub
.as_ref()
.ok_or(RatkeyError::EmptySlot { slot })?;
Ok(pub_key.to_bytes())
}
}
impl Default for MockPivSession {
fn default() -> Self {
Self::new()
}
}
impl Drop for MockPivSession {
fn drop(&mut self) {
self.pin.zeroize();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pin_verify_success() {
let mut session = MockPivSession::new();
assert!(session.verify_pin("123456").is_ok());
assert!(session.pin_verified);
}
#[test]
fn test_pin_verify_wrong() {
let mut session = MockPivSession::new();
let err = session.verify_pin("wrong").unwrap_err();
match err {
RatkeyError::PinFailed { remaining } => assert_eq!(remaining, 2),
other => panic!("expected PinFailed, got {other:?}"),
}
assert!(!session.pin_verified);
}
#[test]
fn test_pin_lockout() {
let mut session = MockPivSession::new();
let _ = session.verify_pin("wrong");
let _ = session.verify_pin("wrong");
let err = session.verify_pin("wrong").unwrap_err();
assert!(matches!(err, RatkeyError::PinLocked));
// Locked state survives correct PIN until PUK unlock.
let err = session.verify_pin("123456").unwrap_err();
assert!(matches!(err, RatkeyError::PinLocked));
}
#[test]
fn test_pin_retry_reset() {
let mut session = MockPivSession::new();
let _ = session.verify_pin("wrong");
// Success resets retries.
session.verify_pin("123456").unwrap();
let _ = session.verify_pin("wrong");
let _ = session.verify_pin("wrong");
let err = session.verify_pin("wrong").unwrap_err();
assert!(matches!(err, RatkeyError::PinLocked));
}
#[test]
fn test_disconnect() {
let mut session = MockPivSession::with_keys();
session.disconnect();
assert!(!session.is_connected());
assert!(matches!(
session.sign_ed25519(SLOT_9A, b"test"),
Err(RatkeyError::Disconnected)
));
}
#[test]
fn test_reconnect_requires_pin() {
let mut session = MockPivSession::with_keys();
session.disconnect();
session.reconnect();
assert!(session.is_connected());
assert!(matches!(
session.sign_ed25519(SLOT_9A, b"test"),
Err(RatkeyError::PinRequired)
));
}
#[test]
fn test_generate_ed25519() {
let mut session = MockPivSession::new();
session.verify_pin("123456").unwrap();
let pub_bytes = session
.generate_ed25519(SLOT_9A, TouchPolicy::Never)
.unwrap();
assert_eq!(pub_bytes.len(), 32);
assert!(matches!(
session.generate_ed25519(SLOT_9A, TouchPolicy::Never),
Err(RatkeyError::SlotOccupied { slot: 0x9A })
));
}
#[test]
fn test_generate_x25519() {
let mut session = MockPivSession::new();
session.verify_pin("123456").unwrap();
let pub_bytes = session
.generate_x25519(SLOT_9D, TouchPolicy::Cached)
.unwrap();
assert_eq!(pub_bytes.len(), 32);
}
#[test]
fn test_sign_verify() {
let mut session = MockPivSession::with_keys();
let message = b"hello ratkey";
let sig = session.sign_ed25519(SLOT_9A, message).unwrap();
assert_eq!(sig.len(), 64);
let pub_bytes = session.read_ed25519_public(SLOT_9A).unwrap();
let pub_key = Ed25519PublicKey::from_bytes(&pub_bytes).unwrap();
assert!(pub_key.verify(message, &sig).is_ok());
}
#[test]
fn test_sign_matches_software() {
// Load-bearing: mock signatures MUST match software signatures bit-for-bit
// so test vectors generated on hardware can be replayed here.
let seed = [0x42u8; 32];
let secret = [0x43u8; 32];
let mut session = MockPivSession::with_key_bytes(&seed, &secret);
let software_key = Ed25519PrivateKey::from_bytes(&seed);
let message = b"deterministic signature test";
let hw_sig = session.sign_ed25519(SLOT_9A, message).unwrap();
let sw_sig = software_key.sign(message);
assert_eq!(
hw_sig, sw_sig,
"mock signature must match software signature"
);
}
#[test]
fn test_ecdh_symmetric() {
let mut session = MockPivSession::with_keys();
let session_x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let peer_prv = X25519PrivateKey::generate();
let peer_pub = peer_prv.public_key();
let peer_pub_bytes = peer_pub.to_bytes();
let secret_hw = session.ecdh_x25519(SLOT_9D, &peer_pub_bytes).unwrap();
let session_pub = X25519PublicKey::from_bytes(&session_x_pub);
let secret_sw = peer_prv.exchange(&session_pub);
assert_eq!(
secret_hw, secret_sw,
"ECDH shared secrets must be identical from both sides"
);
}
#[test]
fn test_ecdh_deterministic() {
let seed = [0x42u8; 32];
let secret = [0x43u8; 32];
let mut session = MockPivSession::with_key_bytes(&seed, &secret);
let peer_pub = [0x55u8; 32];
let software_key = X25519PrivateKey::from_bytes(&secret);
let peer = X25519PublicKey::from_bytes(&peer_pub);
let sw_shared = software_key.exchange(&peer);
let hw_shared = session.ecdh_x25519(SLOT_9D, &peer_pub).unwrap();
assert_eq!(
hw_shared, sw_shared,
"mock ECDH must match software ECDH for same keys"
);
}
#[test]
fn test_sign_empty_slot() {
let mut session = MockPivSession::new();
session.verify_pin("123456").unwrap();
assert!(matches!(
session.sign_ed25519(SLOT_9A, b"test"),
Err(RatkeyError::EmptySlot { slot: 0x9A })
));
}
#[test]
fn test_touch_policy_always() {
let mut session = MockPivSession::new();
session.verify_pin("123456").unwrap();
session
.generate_ed25519(SLOT_9A, TouchPolicy::Always)
.unwrap();
session.require_touch();
assert!(matches!(
session.sign_ed25519(SLOT_9A, b"test"),
Err(RatkeyError::TouchRequired)
));
session.simulate_touch();
assert!(session.sign_ed25519(SLOT_9A, b"test").is_ok());
}
#[test]
fn test_touch_policy_never() {
let mut session = MockPivSession::new();
session.verify_pin("123456").unwrap();
session
.generate_ed25519(SLOT_9A, TouchPolicy::Never)
.unwrap();
// TouchPolicy::Never ignores touch_required.
session.require_touch();
assert!(session.sign_ed25519(SLOT_9A, b"test").is_ok());
}
#[test]
fn test_operations_log() {
let mut session = MockPivSession::new();
session.verify_pin("123456").unwrap();
session
.generate_ed25519(SLOT_9A, TouchPolicy::Never)
.unwrap();
session.sign_ed25519(SLOT_9A, b"test").unwrap();
assert_eq!(session.operations.len(), 3);
assert!(matches!(
session.operations[0],
MockOperation::PinVerify { success: true }
));
assert!(matches!(
session.operations[1],
MockOperation::GenerateEd25519 { slot: 0x9A }
));
assert!(matches!(
session.operations[2],
MockOperation::SignEd25519 { slot: 0x9A, .. }
));
}
#[test]
fn test_without_pin_verify() {
let mut session = MockPivSession::new();
assert!(matches!(
session.generate_ed25519(SLOT_9A, TouchPolicy::Never),
Err(RatkeyError::PinRequired)
));
}
#[test]
fn test_custom_pin() {
let mut session = MockPivSession::new();
session.set_pin("mypin123");
assert!(session.verify_pin("123456").is_err());
assert!(session.verify_pin("mypin123").is_ok());
}
}
+131
View File
@@ -0,0 +1,131 @@
//! PIN cache: `Zeroizing<String>` wiped on drop or expiry.
use std::time::{Duration, Instant};
use zeroize::Zeroizing;
pub struct PinCache {
pin: Option<Zeroizing<String>>,
verified_at: Option<Instant>,
timeout: Duration,
}
impl PinCache {
/// `Duration::ZERO` disables caching (PIN required every op).
pub fn new(timeout: Duration) -> Self {
Self {
pin: None,
verified_at: None,
timeout,
}
}
/// 5-minute default.
pub fn default_timeout() -> Self {
Self::new(Duration::from_secs(300))
}
pub fn cache(&mut self, pin: &str) {
self.pin = Some(Zeroizing::new(pin.to_string()));
self.verified_at = Some(Instant::now());
}
pub fn get(&self) -> Option<&str> {
let pin = self.pin.as_ref()?;
let verified_at = self.verified_at?;
if self.timeout == Duration::ZERO {
return None;
}
if verified_at.elapsed() < self.timeout {
Some(pin.as_str())
} else {
None
}
}
pub fn is_cached(&self) -> bool {
self.get().is_some()
}
pub fn remaining(&self) -> Option<Duration> {
let verified_at = self.verified_at?;
if self.pin.is_none() || self.timeout == Duration::ZERO {
return None;
}
self.timeout.checked_sub(verified_at.elapsed())
}
pub fn clear(&mut self) {
self.pin = None;
self.verified_at = None;
}
}
impl Drop for PinCache {
fn drop(&mut self) {
self.clear();
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::thread::sleep;
#[test]
fn test_cache_and_retrieve() {
let mut cache = PinCache::new(Duration::from_secs(60));
assert!(!cache.is_cached());
assert!(cache.get().is_none());
cache.cache("123456");
assert!(cache.is_cached());
assert_eq!(cache.get(), Some("123456"));
}
#[test]
fn test_cache_expiry() {
let mut cache = PinCache::new(Duration::from_millis(50));
cache.cache("123456");
assert!(cache.is_cached());
sleep(Duration::from_millis(60));
assert!(!cache.is_cached());
assert!(cache.get().is_none());
}
#[test]
fn test_zero_timeout_never_caches() {
let mut cache = PinCache::new(Duration::ZERO);
cache.cache("123456");
assert!(!cache.is_cached());
assert!(cache.get().is_none());
}
#[test]
fn test_clear() {
let mut cache = PinCache::new(Duration::from_secs(60));
cache.cache("123456");
assert!(cache.is_cached());
cache.clear();
assert!(!cache.is_cached());
}
#[test]
fn test_remaining() {
let mut cache = PinCache::new(Duration::from_secs(60));
assert!(cache.remaining().is_none());
cache.cache("123456");
let remaining = cache.remaining().unwrap();
assert!(remaining.as_secs() >= 59);
}
#[test]
fn test_default_timeout() {
let cache = PinCache::default_timeout();
assert_eq!(cache.timeout, Duration::from_secs(300));
}
}
+255
View File
@@ -0,0 +1,255 @@
//! Generate keys on-device, derive identity hash, write `.hwid`.
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
use rns_crypto::sha::truncated_hash;
use crate::error::RatkeyError;
use crate::hwid::*;
use crate::mock::{MockPivSession, SLOT_9A, SLOT_9D, TouchPolicy};
#[derive(Debug, Clone)]
pub struct ProvisionResult {
pub config: HwidConfig,
pub ed25519_pub: [u8; 32],
pub x25519_pub: [u8; 32],
/// 16-byte Reticulum identity hash.
pub identity_hash: [u8; 16],
pub identity_hash_hex: String,
pub hwid_path: Option<PathBuf>,
}
#[derive(Debug, Clone)]
pub struct ProvisionConfig {
/// PIV PIN (6-8 chars).
pub pin: String,
pub touch_signing: TouchPolicy,
pub touch_encryption: TouchPolicy,
pub nickname: String,
/// None = don't write to disk.
pub identities_dir: Option<PathBuf>,
}
impl Default for ProvisionConfig {
fn default() -> Self {
Self {
pin: String::new(),
touch_signing: TouchPolicy::Always,
touch_encryption: TouchPolicy::Cached,
nickname: String::new(),
identities_dir: None,
}
}
}
pub fn provision_mock(
session: &mut MockPivSession,
config: &ProvisionConfig,
) -> Result<ProvisionResult, RatkeyError> {
session.verify_pin(&config.pin)?;
let ed25519_pub = session.generate_ed25519(SLOT_9A, config.touch_signing)?;
let x25519_pub = session.generate_x25519(SLOT_9D, config.touch_encryption)?;
// Reticulum identity hash: SHA-256(X25519_pub || Ed25519_pub) truncated to 16 bytes.
let mut pub_key_bytes = [0u8; 64];
pub_key_bytes[..32].copy_from_slice(&x25519_pub);
pub_key_bytes[32..].copy_from_slice(&ed25519_pub);
let identity_hash = truncated_hash(&pub_key_bytes);
let identity_hash_hex = hex::encode(identity_hash);
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let touch_signing_str = match config.touch_signing {
TouchPolicy::Always => "always",
TouchPolicy::Cached => "cached",
TouchPolicy::Never => "never",
};
let touch_encryption_str = match config.touch_encryption {
TouchPolicy::Always => "always",
TouchPolicy::Cached => "cached",
TouchPolicy::Never => "never",
};
let hwid = HwidConfig {
identity: HwidIdentity {
hash: identity_hash_hex.clone(),
nickname: config.nickname.clone(),
created_at: now,
},
device: HwidDevice {
device_type: session.device_type.clone(),
serial: session.serial,
firmware: session.firmware.clone(),
},
keys: HwidKeys {
ed25519_pub: hex::encode(ed25519_pub),
x25519_pub: hex::encode(x25519_pub),
},
slots: HwidSlots {
signing: "9A".to_string(),
encryption: "9D".to_string(),
},
policy: HwidPolicy {
pin_cache_timeout: 300,
touch_signing: touch_signing_str.to_string(),
touch_encryption: touch_encryption_str.to_string(),
},
attestation: HwidAttestation::default(),
app: HwidApp::default(),
backup: HwidBackup::default(),
};
let hwid_path = if let Some(ref dir) = config.identities_dir {
let identity_dir = dir.join(&identity_hash_hex);
std::fs::create_dir_all(&identity_dir)?;
let path = identity_dir.join("identity.hwid");
hwid.to_file(&path)?;
Some(path)
} else {
None
};
Ok(ProvisionResult {
config: hwid,
ed25519_pub,
x25519_pub,
identity_hash,
identity_hash_hex,
hwid_path,
})
}
/// First 16 bytes of `SHA-256(X25519_pub || Ed25519_pub)`. Matches `rns_identity::Identity::hash()`.
pub fn compute_identity_hash(ed25519_pub: &[u8; 32], x25519_pub: &[u8; 32]) -> [u8; 16] {
let mut pub_key_bytes = [0u8; 64];
pub_key_bytes[..32].copy_from_slice(x25519_pub);
pub_key_bytes[32..].copy_from_slice(ed25519_pub);
truncated_hash(&pub_key_bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_provision_mock_basic() {
let mut session = MockPivSession::new();
let config = ProvisionConfig {
pin: "123456".to_string(),
touch_signing: TouchPolicy::Never,
touch_encryption: TouchPolicy::Never,
nickname: "test key".to_string(),
identities_dir: None,
};
let result = provision_mock(&mut session, &config).unwrap();
assert_eq!(result.ed25519_pub.len(), 32);
assert_eq!(result.x25519_pub.len(), 32);
assert_eq!(result.identity_hash.len(), 16);
assert_eq!(result.identity_hash_hex.len(), 32);
let recomputed = compute_identity_hash(&result.ed25519_pub, &result.x25519_pub);
assert_eq!(result.identity_hash, recomputed);
assert_eq!(result.config.identity.hash, result.identity_hash_hex);
assert_eq!(result.config.identity.nickname, "test key");
assert_eq!(result.config.device.device_type, "yubikey5");
assert_eq!(result.config.slots.signing, "9A");
assert_eq!(result.config.slots.encryption, "9D");
assert!(result.hwid_path.is_none());
}
#[test]
fn test_provision_writes_hwid_file() {
let mut session = MockPivSession::new();
let dir = std::env::temp_dir().join("ratkey_test_provision");
let _ = std::fs::remove_dir_all(&dir);
let config = ProvisionConfig {
pin: "123456".to_string(),
touch_signing: TouchPolicy::Always,
touch_encryption: TouchPolicy::Cached,
nickname: "my yubikey".to_string(),
identities_dir: Some(dir.clone()),
};
let result = provision_mock(&mut session, &config).unwrap();
let path = result.hwid_path.as_ref().unwrap();
assert!(path.exists());
assert!(path.to_string_lossy().contains("identity.hwid"));
let loaded = HwidConfig::from_file(path).unwrap();
assert_eq!(loaded.identity.hash, result.identity_hash_hex);
assert_eq!(loaded.identity.nickname, "my yubikey");
assert_eq!(loaded.policy.touch_signing, "always");
assert_eq!(loaded.policy.touch_encryption, "cached");
let loaded_ed = loaded.ed25519_pub_bytes().unwrap();
let loaded_x = loaded.x25519_pub_bytes().unwrap();
assert_eq!(loaded_ed, result.ed25519_pub);
assert_eq!(loaded_x, result.x25519_pub);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn test_provision_and_use_identity() {
let mut session = MockPivSession::new();
session.set_pin("mypin1");
let dir = std::env::temp_dir().join("ratkey_test_provision_use");
let _ = std::fs::remove_dir_all(&dir);
let config = ProvisionConfig {
pin: "mypin1".to_string(),
touch_signing: TouchPolicy::Never,
touch_encryption: TouchPolicy::Never,
nickname: "round-trip test".to_string(),
identities_dir: Some(dir.clone()),
};
let result = provision_mock(&mut session, &config).unwrap();
let path = result.hwid_path.as_ref().unwrap();
let mut hw = crate::HardwareIdentity::from_file_mock(path, session).unwrap();
let message = b"provisioned and loaded";
let sig = hw.sign(message).unwrap();
assert!(hw.verify(message, &sig));
assert_eq!(hw.hash(), &result.identity_hash);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn test_provision_wrong_pin() {
let mut session = MockPivSession::new();
let config = ProvisionConfig {
pin: "wrong_pin".to_string(),
..Default::default()
};
let err = provision_mock(&mut session, &config).unwrap_err();
assert!(matches!(err, RatkeyError::PinFailed { .. }));
}
#[test]
fn test_provision_deterministic_hash() {
let ed = [0xAA; 32];
let x = [0xBB; 32];
let hash1 = compute_identity_hash(&ed, &x);
let hash2 = compute_identity_hash(&ed, &x);
assert_eq!(hash1, hash2);
let hash3 = compute_identity_hash(&[0xCC; 32], &x);
assert_ne!(hash1, hash3);
}
}
+174
View File
@@ -0,0 +1,174 @@
//! Real PIV session over PC/SC (YubiKey 5, Nitrokey 3).
//! Requires `hardware` feature + PC/SC daemon (macOS CryptoTokenKit / Linux pcscd / Windows WinSCard).
use pcsc::{Card, Context, Protocols, Scope, ShareMode};
use tracing::{debug, warn};
use zeroize::Zeroize;
use crate::apdu;
use crate::detect::DeviceType;
use crate::error::RatkeyError;
use crate::pin::PinCache;
const MAX_RESPONSE: usize = 4096;
pub struct PivSession {
card: Card,
device_type: DeviceType,
reader_name: String,
serial: Option<u32>,
firmware: Option<String>,
pin_cache: PinCache,
}
impl PivSession {
pub fn connect() -> Result<Self, RatkeyError> {
let devices = crate::detect::detect_devices()?;
let device = devices.first().ok_or(RatkeyError::NoDevice)?;
Self::connect_reader(&device.reader_name)
}
pub fn connect_reader(reader_name: &str) -> Result<Self, RatkeyError> {
let ctx = Context::establish(Scope::User)?;
let reader = std::ffi::CString::new(reader_name)
.map_err(|_| RatkeyError::UnsupportedDevice(reader_name.to_string()))?;
let card = ctx.connect(&reader, ShareMode::Shared, Protocols::ANY)?;
let resp = transmit(&card, &apdu::select_piv())?;
apdu::check_response(&resp)?;
let device_type = crate::detect::detect_device_type(reader_name);
debug!(
"PIV session established with {} ({})",
reader_name,
device_type.as_str()
);
let (serial, firmware) = crate::detect::read_identity(&card, device_type);
Ok(Self {
card,
device_type,
reader_name: reader_name.to_string(),
serial,
firmware,
pin_cache: PinCache::default_timeout(),
})
}
pub fn device_type(&self) -> DeviceType {
self.device_type
}
pub fn reader_name(&self) -> &str {
&self.reader_name
}
pub fn serial(&self) -> Option<u32> {
self.serial
}
pub fn firmware(&self) -> Option<&str> {
self.firmware.as_deref()
}
/// Probes the attestation slot (F9) — always present on provisioned tokens.
pub fn is_connected(&self) -> bool {
let cmd = apdu::get_metadata(apdu::SLOT_ATTESTATION);
let mut buf = vec![0u8; 256];
self.card.transmit(&cmd, &mut buf).is_ok()
}
pub fn verify_pin(&mut self, pin: &str) -> Result<(), RatkeyError> {
let cmd = apdu::verify_pin(pin);
let resp = transmit(&self.card, &cmd)?;
apdu::check_response(&resp)?;
self.pin_cache.cache(pin);
debug!("PIN verified");
Ok(())
}
pub fn change_pin(&mut self, old_pin: &str, new_pin: &str) -> Result<(), RatkeyError> {
let cmd = apdu::change_pin(old_pin, new_pin);
let resp = transmit(&self.card, &cmd)?;
apdu::check_response(&resp)?;
self.pin_cache.cache(new_pin);
debug!("PIN changed");
Ok(())
}
pub fn generate_ed25519(
&self,
slot: u8,
pin_policy: Option<u8>,
touch_policy: Option<u8>,
) -> Result<[u8; 32], RatkeyError> {
let cmd = apdu::generate_key(slot, apdu::ALG_ED25519, pin_policy, touch_policy);
let resp = transmit(&self.card, &cmd)?;
let data = apdu::check_response(&resp)?;
apdu::parse_generate_response(data)
}
pub fn generate_x25519(
&self,
slot: u8,
pin_policy: Option<u8>,
touch_policy: Option<u8>,
) -> Result<[u8; 32], RatkeyError> {
let cmd = apdu::generate_key(slot, apdu::ALG_X25519, pin_policy, touch_policy);
let resp = transmit(&self.card, &cmd)?;
let data = apdu::check_response(&resp)?;
apdu::parse_generate_response(data)
}
pub fn sign_ed25519(&self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError> {
let cmd = apdu::sign_ed25519(slot, message);
let resp = transmit(&self.card, &cmd)?;
let data = apdu::check_response(&resp)?;
apdu::parse_sign_response(data)
}
pub fn ecdh_x25519(&self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError> {
let cmd = apdu::ecdh_x25519(slot, peer_pub);
let resp = transmit(&self.card, &cmd)?;
let data = apdu::check_response(&resp)?;
let mut secret = apdu::parse_ecdh_response(data)?;
// Wipes local stack copy only. Caller must zeroize the returned bytes.
let result = secret;
secret.zeroize();
Ok(result)
}
/// Returns DER-encoded X.509 attestation certificate.
pub fn attest_key(&self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
let cmd = apdu::attest_key(slot);
let resp = transmit(&self.card, &cmd)?;
let data = apdu::check_response(&resp)?;
Ok(data.to_vec())
}
pub fn read_certificate(&self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
let cmd = apdu::get_data(slot).ok_or(RatkeyError::EmptySlot { slot })?;
let resp = transmit(&self.card, &cmd)?;
let data = apdu::check_response(&resp)?;
Ok(data.to_vec())
}
/// Returns raw metadata TLV bytes.
pub fn read_metadata(&self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
let cmd = apdu::get_metadata(slot);
let resp = transmit(&self.card, &cmd)?;
let data = apdu::check_response(&resp)?;
Ok(data.to_vec())
}
}
fn transmit(card: &Card, command: &[u8]) -> Result<Vec<u8>, RatkeyError> {
let mut response_buf = vec![0u8; MAX_RESPONSE];
let response = card.transmit(command, &mut response_buf).map_err(|e| {
warn!("PC/SC transmit failed: {}", e);
RatkeyError::Disconnected
})?;
Ok(response.to_vec())
}
+32
View File
@@ -0,0 +1,32 @@
[package]
name = "rns-runtime"
description = "Core runtime, config parsing, and lifecycle for Reticulum"
version.workspace = true
edition.workspace = true
license.workspace = true
[features]
default = []
serial = ["rns-interface/serial"]
ble = ["rns-interface/ble"]
[dependencies]
rns-crypto = { workspace = true, features = ["std"] }
rns-wire = { workspace = true, features = ["std"] }
rns-identity = { workspace = true }
rns-transport = { workspace = true }
rns-link = { workspace = true }
rns-protocol = { workspace = true }
rns-interface = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }
bytes = { workspace = true }
tracing = { workspace = true }
hmac = { workspace = true }
sha2 = { workspace = true }
rmp-serde = { workspace = true }
rmpv = { workspace = true, features = ["with-serde"] }
serde = { workspace = true }
subtle = { workspace = true }
hex = { workspace = true }
nix = { workspace = true }
+942
View File
@@ -0,0 +1,942 @@
//! INI parser compatible with the ConfigObj subset used by Python Reticulum:
//! nested sections, quoted keys/sections/values, ConfigObj list values,
//! multiline values, `#` comments outside quotes, and boolean variants
//! `True`/`Yes`/`On`/`1`.
use std::collections::HashMap;
use std::path::Path;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[error("parse error at line {line}: {message}")]
Parse { line: usize, message: String },
#[error("missing required key: [{section}] {key}")]
MissingKey { section: String, key: String },
#[error("invalid value for [{section}] {key}: {message}")]
InvalidValue {
section: String,
key: String,
message: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigValue {
Scalar(String),
List(Vec<String>),
}
impl ConfigValue {
fn as_str(&self) -> Option<&str> {
match self {
ConfigValue::Scalar(value) => Some(value.as_str()),
ConfigValue::List(_) => None,
}
}
fn as_list(&self) -> Vec<String> {
match self {
ConfigValue::Scalar(value) => vec![value.clone()],
ConfigValue::List(values) => values.clone(),
}
}
}
#[derive(Debug, Clone, Default)]
pub struct ConfigSection {
pub values: HashMap<String, ConfigValue>,
value_order: Vec<String>,
pub subsections: HashMap<String, ConfigSection>,
subsection_order: Vec<String>,
}
impl ConfigSection {
pub fn new() -> Self {
Self::default()
}
pub fn get(&self, key: &str) -> Option<&str> {
self.values.get(key).and_then(ConfigValue::as_str)
}
pub fn get_bool(&self, key: &str) -> Option<bool> {
let v = self.get(key)?;
parse_bool(v)
}
pub fn get_bool_or(&self, key: &str, default: bool) -> bool {
self.get_bool(key).unwrap_or(default)
}
pub fn get_int(&self, key: &str) -> Option<i64> {
let v = self.get(key)?;
v.parse().ok()
}
pub fn get_uint(&self, key: &str) -> Option<u64> {
let v = self.get(key)?;
v.parse().ok()
}
pub fn get_float(&self, key: &str) -> Option<f64> {
let v = self.get(key)?;
v.parse().ok()
}
pub fn get_list(&self, key: &str) -> Option<Vec<String>> {
let v = self.values.get(key)?;
Some(v.as_list())
}
pub fn get_hex(&self, key: &str) -> Option<Vec<u8>> {
let v = self.get(key)?;
hex_decode(v.trim())
}
pub fn has(&self, key: &str) -> bool {
self.values.contains_key(key)
}
pub fn set(&mut self, key: &str, value: &str) {
self.set_value(key.to_string(), ConfigValue::Scalar(value.to_string()));
}
pub fn set_list(&mut self, key: &str, value: Vec<String>) {
self.set_value(key.to_string(), ConfigValue::List(value));
}
fn set_value(&mut self, key: String, value: ConfigValue) {
if !self.values.contains_key(&key) {
self.value_order.push(key.clone());
}
self.values.insert(key, value);
}
fn insert_value(
&mut self,
key: String,
value: ConfigValue,
line: usize,
) -> Result<(), ConfigError> {
if self.values.contains_key(&key) {
return Err(ConfigError::Parse {
line,
message: "duplicate keyword name".to_string(),
});
}
self.value_order.push(key.clone());
self.values.insert(key, value);
Ok(())
}
fn insert_subsection(
&mut self,
name: String,
line: usize,
) -> Result<&mut ConfigSection, ConfigError> {
if self.subsections.contains_key(&name) {
return Err(ConfigError::Parse {
line,
message: "duplicate section name".to_string(),
});
}
self.subsection_order.push(name.clone());
self.subsections.insert(name.clone(), ConfigSection::new());
Ok(self.subsections.get_mut(&name).unwrap())
}
}
/// Keys before any `[section]` header land under the empty-string section.
#[derive(Debug, Clone, Default)]
pub struct Config {
pub sections: HashMap<String, ConfigSection>,
section_order: Vec<String>,
}
impl Config {
pub fn new() -> Self {
Self::default()
}
/// Mirrors Python ConfigObj file loading, including normal OS symlink
/// following. Security policy for config paths must be enforced by callers.
pub fn from_file(path: &Path) -> Result<Self, ConfigError> {
let content = std::fs::read_to_string(path)?;
let mut config = Self::parse(&content)?;
config.prepare_loaded_reticulum_config(path)?;
Ok(config)
}
pub fn parse(input: &str) -> Result<Self, ConfigError> {
let mut config = Config::new();
let mut current_section: Option<String> = None;
let mut current_path: Vec<String> = Vec::new();
let lines: Vec<&str> = input.lines().collect();
let mut index = 0;
while index < lines.len() {
let line_num = index + 1;
let raw_line = lines[index];
let line = strip_comment(raw_line).trim().to_string();
if line.is_empty() {
index += 1;
continue;
}
if line.starts_with('[') && line.ends_with(']') {
let open_depth = line.chars().take_while(|&ch| ch == '[').count();
let close_depth = line.chars().rev().take_while(|&ch| ch == ']').count();
if open_depth != close_depth {
return Err(ConfigError::Parse {
line: line_num,
message: "mismatched section brackets".to_string(),
});
}
let name = unquote_token(line[open_depth..line.len() - close_depth].trim())
.map_err(|message| ConfigError::Parse {
line: line_num,
message,
})?;
if name.is_empty() {
return Err(ConfigError::Parse {
line: line_num,
message: if open_depth == 1 {
"empty section name".to_string()
} else {
"empty subsection name".to_string()
},
});
}
if open_depth == 1 {
if config.sections.contains_key(&name) {
return Err(ConfigError::Parse {
line: line_num,
message: "duplicate section name".to_string(),
});
}
current_section = Some(name.clone());
current_path.clear();
config.section_order.push(name.clone());
config.sections.insert(name, ConfigSection::new());
} else {
if current_section.is_none() {
return Err(ConfigError::Parse {
line: line_num,
message: "subsection without parent section".to_string(),
});
}
let parent_depth = open_depth - 2;
if current_path.len() < parent_depth {
return Err(ConfigError::Parse {
line: line_num,
message: "section too nested".to_string(),
});
}
let section_name = current_section.as_ref().unwrap();
let section = config.sections.get_mut(section_name).unwrap();
let parent = section_for_path_mut(section, &current_path[..parent_depth]);
parent.insert_subsection(name.clone(), line_num)?;
current_path.truncate(parent_depth);
current_path.push(name);
}
index += 1;
continue;
}
if let Some(eq_pos) = line.find('=') {
let key =
unquote_token(line[..eq_pos].trim()).map_err(|message| ConfigError::Parse {
line: line_num,
message,
})?;
let (value, consumed_index) =
parse_config_value(line[eq_pos + 1..].trim(), &lines, index)?;
if key.is_empty() {
return Err(ConfigError::Parse {
line: line_num,
message: "empty key".to_string(),
});
}
match &current_section {
Some(sec) => {
let section = config.sections.get_mut(sec).unwrap();
section_for_path_mut(section, &current_path)
.insert_value(key, value, line_num)?;
}
None => {
config
.root_section_mut()
.insert_value(key, value, line_num)?;
}
}
index = consumed_index + 1;
continue;
}
return Err(ConfigError::Parse {
line: line_num,
message: format!("unrecognized line: {line}"),
});
}
Ok(config)
}
pub fn section(&self, name: &str) -> Option<&ConfigSection> {
self.sections.get(name)
}
pub fn section_mut(&mut self, name: &str) -> Option<&mut ConfigSection> {
self.sections.get_mut(name)
}
pub fn subsection(&self, section: &str, subsection: &str) -> Option<&ConfigSection> {
self.sections
.get(section)
.and_then(|s| s.subsections.get(subsection))
}
pub fn subsections(&self, section: &str) -> Vec<(&str, &ConfigSection)> {
match self.sections.get(section) {
Some(s) => s
.subsection_order
.iter()
.filter_map(|k| s.subsections.get_key_value(k))
.map(|(k, v)| (k.as_str(), v))
.collect(),
None => Vec::new(),
}
}
pub fn default_config() -> &'static str {
DEFAULT_CONFIG
}
pub fn write_default(path: &Path) -> Result<(), ConfigError> {
std::fs::write(path, DEFAULT_CONFIG)?;
Ok(())
}
fn prepare_loaded_reticulum_config(&mut self, _config_path: &Path) -> Result<(), ConfigError> {
let Some(section) = self.section_mut("reticulum") else {
return Ok(());
};
validate_identity_hash_list(section, "remote_management_allowed")?;
validate_identity_hash_list(section, "blackhole_sources")?;
validate_identity_hash_list(section, "interface_discovery_sources")?;
Ok(())
}
fn root_section_mut(&mut self) -> &mut ConfigSection {
if !self.sections.contains_key("") {
self.section_order.push(String::new());
self.sections.insert(String::new(), ConfigSection::new());
}
self.sections.get_mut("").unwrap()
}
}
fn section_for_path_mut<'a>(
mut section: &'a mut ConfigSection,
path: &[String],
) -> &'a mut ConfigSection {
for part in path {
section = section
.subsections
.get_mut(part)
.expect("current subsection path was not initialised");
}
section
}
fn unquote_token(value: &str) -> Result<String, String> {
let value = value.trim();
if value.is_empty() {
return Err("empty quoted value".to_string());
}
let Some(first) = value.chars().next() else {
return Err("empty quoted value".to_string());
};
if first == '"' || first == '\'' {
if !value.ends_with(first) || value.len() < 2 {
return Err("parse error in value".to_string());
}
Ok(value[1..value.len() - 1].to_string())
} else {
Ok(value.to_string())
}
}
fn parse_config_value(
raw: &str,
lines: &[&str],
index: usize,
) -> Result<(ConfigValue, usize), ConfigError> {
if raw.starts_with("\"\"\"") || raw.starts_with("'''") {
return parse_multiline_value(raw, lines, index);
}
parse_single_line_value(raw)
.map(|value| (value, index))
.map_err(|message| ConfigError::Parse {
line: index + 1,
message,
})
}
fn parse_multiline_value(
raw: &str,
lines: &[&str],
index: usize,
) -> Result<(ConfigValue, usize), ConfigError> {
let quote = &raw[..3];
let rest = &raw[3..];
if let Some(end) = rest.find(quote) {
return Ok((ConfigValue::Scalar(rest[..end].to_string()), index));
}
let mut value = rest.to_string();
let mut current = index;
while current + 1 < lines.len() {
current += 1;
value.push('\n');
let line = lines[current];
if let Some(end) = line.find(quote) {
value.push_str(&line[..end]);
return Ok((ConfigValue::Scalar(value), current));
}
value.push_str(line);
}
Err(ConfigError::Parse {
line: index + 1,
message: "unterminated multiline value".to_string(),
})
}
fn parse_single_line_value(raw: &str) -> Result<ConfigValue, String> {
let value = raw.trim();
if value.is_empty() {
return Ok(ConfigValue::Scalar(String::new()));
}
if value == "," {
return Ok(ConfigValue::List(Vec::new()));
}
let (mut parts, saw_comma) = split_value_parts(value)?;
if saw_comma {
if parts.last().is_some_and(|part| part.trim().is_empty()) {
parts.pop();
}
let mut values = Vec::with_capacity(parts.len());
for part in parts {
let part = part.trim();
if part.is_empty() {
return Err("parse error in value".to_string());
}
values.push(unquote_token(part)?);
}
return Ok(ConfigValue::List(values));
}
Ok(ConfigValue::Scalar(unquote_token(value)?))
}
fn split_value_parts(value: &str) -> Result<(Vec<String>, bool), String> {
let mut parts = Vec::new();
let mut current = String::new();
let mut quote: Option<char> = None;
let mut quoted_item_closed = false;
let mut item_started = false;
let mut saw_comma = false;
for ch in value.chars() {
if let Some(q) = quote {
current.push(ch);
if ch == q {
quote = None;
quoted_item_closed = true;
}
continue;
}
if quoted_item_closed {
if ch == ',' {
parts.push(current.trim().to_string());
current.clear();
quoted_item_closed = false;
item_started = false;
saw_comma = true;
} else if ch.is_whitespace() {
current.push(ch);
} else {
return Err("parse error in value".to_string());
}
continue;
}
if ch == ',' {
parts.push(current.trim().to_string());
current.clear();
item_started = false;
saw_comma = true;
} else if (ch == '"' || ch == '\'') && !item_started {
quote = Some(ch);
item_started = true;
current.push(ch);
} else {
if !ch.is_whitespace() {
item_started = true;
}
current.push(ch);
}
}
if quote.is_some() {
return Err("parse error in value".to_string());
}
if saw_comma {
parts.push(current.trim().to_string());
}
Ok((parts, saw_comma))
}
/// Truncate at the first `#` outside a quoted string.
fn strip_comment(line: &str) -> &str {
let mut in_quote = false;
let mut quote_char = ' ';
for (i, ch) in line.char_indices() {
if in_quote {
if ch == quote_char {
in_quote = false;
}
} else if ch == '"' || ch == '\'' {
in_quote = true;
quote_char = ch;
} else if ch == '#' {
return &line[..i];
}
}
line
}
fn parse_bool(s: &str) -> Option<bool> {
match s.to_lowercase().as_str() {
"true" | "yes" | "on" | "1" => Some(true),
"false" | "no" | "off" | "0" => Some(false),
_ => None,
}
}
fn validate_identity_hash_list(section: &ConfigSection, key: &str) -> Result<(), ConfigError> {
let Some(values) = section.get_list(key) else {
return Ok(());
};
for value in values {
let hexhash = value.trim();
if hexhash.len() != 32 {
return Err(ConfigError::InvalidValue {
section: "reticulum".to_string(),
key: key.to_string(),
message: format!(
"identity hash {hexhash} must be 32 hexadecimal characters (16 bytes)"
),
});
}
if hex_decode(hexhash).is_none() {
return Err(ConfigError::InvalidValue {
section: "reticulum".to_string(),
key: key.to_string(),
message: format!("invalid identity hash: {hexhash}"),
});
}
}
Ok(())
}
fn hex_decode(s: &str) -> Option<Vec<u8>> {
if !s.len().is_multiple_of(2) {
return None;
}
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok())
.collect()
}
const DEFAULT_CONFIG: &str = r#"# This is the default Reticulum config file.
[reticulum]
enable_transport = False
share_instance = Yes
instance_name = default
[logging]
loglevel = 4
[interfaces]
[[Default Interface]]
type = AutoInterface
enabled = Yes
"#;
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn test_parse_empty() {
let config = Config::parse("").unwrap();
assert!(config.sections.is_empty());
}
#[test]
fn test_parse_section() {
let config = Config::parse("[reticulum]\nshare_instance = Yes\n").unwrap();
let sec = config.section("reticulum").unwrap();
assert_eq!(sec.get_bool("share_instance"), Some(true));
}
#[test]
fn test_parse_subsection() {
let input = r#"
[interfaces]
[[My UDP Interface]]
type = UDPInterface
enabled = yes
listen_port = 4242
"#;
let config = Config::parse(input).unwrap();
let subs = config.subsections("interfaces");
assert_eq!(subs.len(), 1);
let (name, sub) = &subs[0];
assert_eq!(*name, "My UDP Interface");
assert_eq!(sub.get("type"), Some("UDPInterface"));
assert_eq!(sub.get_bool("enabled"), Some(true));
assert_eq!(sub.get_uint("listen_port"), Some(4242));
}
#[test]
fn test_parse_nested_subsection() {
let input = r#"
[interfaces]
[[OpenCom XL]]
type = RNodeMultiInterface
port = /dev/ttyACM0
[[[High Datarate]]]
enabled = yes
vport = 1
frequency = 2400000000
[[[Low Datarate]]]
enabled = no
vport = 0
frequency = 865600000
"#;
let config = Config::parse(input).unwrap();
let iface = config.section("interfaces").unwrap();
let rnode = iface.subsections.get("OpenCom XL").unwrap();
assert_eq!(rnode.get("type"), Some("RNodeMultiInterface"));
assert_eq!(rnode.get("port"), Some("/dev/ttyACM0"));
let high = rnode.subsections.get("High Datarate").unwrap();
assert_eq!(high.get_bool("enabled"), Some(true));
assert_eq!(high.get_uint("vport"), Some(1));
assert_eq!(high.get_uint("frequency"), Some(2_400_000_000));
let low = rnode.subsections.get("Low Datarate").unwrap();
assert_eq!(low.get_bool("enabled"), Some(false));
assert_eq!(low.get_uint("vport"), Some(0));
assert_eq!(low.get_uint("frequency"), Some(865_600_000));
}
#[test]
fn test_parse_comments() {
let input = "# Full line comment\n[sec]\nkey = value # inline comment\n";
let config = Config::parse(input).unwrap();
let sec = config.section("sec").unwrap();
assert_eq!(sec.get("key"), Some("value"));
}
#[test]
fn test_parse_bool_variants() {
assert_eq!(parse_bool("True"), Some(true));
assert_eq!(parse_bool("true"), Some(true));
assert_eq!(parse_bool("YES"), Some(true));
assert_eq!(parse_bool("yes"), Some(true));
assert_eq!(parse_bool("On"), Some(true));
assert_eq!(parse_bool("1"), Some(true));
assert_eq!(parse_bool("False"), Some(false));
assert_eq!(parse_bool("false"), Some(false));
assert_eq!(parse_bool("NO"), Some(false));
assert_eq!(parse_bool("no"), Some(false));
assert_eq!(parse_bool("Off"), Some(false));
assert_eq!(parse_bool("0"), Some(false));
assert_eq!(parse_bool("maybe"), None);
}
#[test]
fn test_get_list() {
let input = "[sec]\nitems = one, two, three\n";
let config = Config::parse(input).unwrap();
let sec = config.section("sec").unwrap();
let list = sec.get_list("items").unwrap();
assert_eq!(list, vec!["one", "two", "three"]);
}
#[test]
fn test_get_hex() {
let input = "[sec]\nkey = aabbccdd\n";
let config = Config::parse(input).unwrap();
let sec = config.section("sec").unwrap();
let bytes = sec.get_hex("key").unwrap();
assert_eq!(bytes, vec![0xaa, 0xbb, 0xcc, 0xdd]);
}
#[test]
fn test_get_float() {
let input = "[sec]\nval = 1.25\n";
let config = Config::parse(input).unwrap();
let sec = config.section("sec").unwrap();
assert!((sec.get_float("val").unwrap() - 1.25).abs() < f64::EPSILON);
}
#[test]
fn test_keys_preserve_case_like_configobj() {
let input = "[sec]\nMyKey = hello\n";
let config = Config::parse(input).unwrap();
let sec = config.section("sec").unwrap();
assert_eq!(sec.get("MyKey"), Some("hello"));
assert_eq!(sec.get("mykey"), None);
}
#[test]
fn test_configobj_quoted_values_and_lists() {
let input = r#"
[sec]
empty =
empty_list = ,
quoted_empty = ""
quoted_hash = "value # kept" # dropped
quoted_comma = "one,two"
items = "one", "two,three", four,
"quoted key" = "quoted value"
"#;
let config = Config::parse(input).unwrap();
let sec = config.section("sec").unwrap();
assert_eq!(sec.get("empty"), Some(""));
assert_eq!(sec.get_list("empty"), Some(vec![String::new()]));
assert_eq!(sec.get_list("empty_list"), Some(Vec::new()));
assert_eq!(sec.get("quoted_empty"), Some(""));
assert_eq!(sec.get("quoted_hash"), Some("value # kept"));
assert_eq!(sec.get("quoted_comma"), Some("one,two"));
assert_eq!(
sec.get_list("items").unwrap(),
vec!["one", "two,three", "four"]
);
assert_eq!(sec.get("quoted key"), Some("quoted value"));
}
#[test]
fn test_configobj_quoted_sections_and_multiline_values() {
let input = "[interfaces]\n[[\"My Interface\"]]\ntype = AutoInterface\nnotes = \"\"\"first\nsecond\"\"\"\n";
let config = Config::parse(input).unwrap();
let iface = config.subsection("interfaces", "My Interface").unwrap();
assert_eq!(iface.get("type"), Some("AutoInterface"));
assert_eq!(iface.get("notes"), Some("first\nsecond"));
}
#[test]
fn test_duplicate_keys_and_sections_fail_like_configobj() {
assert!(Config::parse("[sec]\nkey = one\nkey = two\n").is_err());
assert!(Config::parse("[sec]\nkey = one\n[sec]\nkey = two\n").is_err());
assert!(Config::parse("[interfaces]\n[[iface]]\ntype = A\n[[iface]]\ntype = B\n").is_err());
}
#[test]
fn test_malformed_configobj_values_fail() {
assert!(Config::parse("[sec]\nkey = \"unterminated\n").is_err());
assert!(Config::parse("[sec]\nkey = one,,two\n").is_err());
assert!(Config::parse("[sec]\nkey = one, , two\n").is_err());
assert!(Config::parse("[sec]\nkey = \"\"\"unterminated\n").is_err());
}
#[test]
fn test_multiple_sections() {
let input = "[reticulum]\nkey1 = v1\n[logging]\nkey2 = v2\n";
let config = Config::parse(input).unwrap();
assert_eq!(config.section("reticulum").unwrap().get("key1"), Some("v1"));
assert_eq!(config.section("logging").unwrap().get("key2"), Some("v2"));
}
#[test]
fn test_multiple_subsections() {
let input = r#"
[interfaces]
[[iface1]]
type = TCPClientInterface
[[iface2]]
type = UDPInterface
"#;
let config = Config::parse(input).unwrap();
let subs = config.subsections("interfaces");
assert_eq!(subs.len(), 2);
assert_eq!(subs[0].0, "iface1");
assert_eq!(subs[1].0, "iface2");
}
#[test]
fn test_named_subsection_lookup() {
let input = r#"
[interfaces]
[[iface1]]
type = TCPClientInterface
[[iface2]]
type = UDPInterface
"#;
let config = Config::parse(input).unwrap();
assert_eq!(
config
.subsection("interfaces", "iface2")
.and_then(|s| s.get("type")),
Some("UDPInterface")
);
assert!(config.subsection("interfaces", "missing").is_none());
}
#[test]
fn test_subsection_without_section_fails() {
let result = Config::parse("[[orphan]]\nkey = val\n");
assert!(result.is_err());
}
#[test]
fn test_nested_subsection_without_parent_fails() {
let result = Config::parse("[interfaces]\n[[[orphan]]]\nkey = val\n");
assert!(result.is_err());
}
#[test]
fn test_empty_section_name_fails() {
let result = Config::parse("[]\nkey = val\n");
assert!(result.is_err());
}
#[test]
fn test_default_config_parses() {
let config = Config::parse(Config::default_config()).unwrap();
let ret = config.section("reticulum").unwrap();
assert_eq!(ret.get_bool("share_instance"), Some(true));
assert_eq!(ret.get_bool("enable_transport"), Some(false));
assert_eq!(ret.get("instance_name"), Some("default"));
assert_eq!(ret.get_uint("shared_instance_port"), None);
}
#[test]
fn test_loaded_config_rejects_malformed_identity_hash_lists() {
let dir = unique_test_dir("hash-list-validation");
let path = dir.join("config");
std::fs::write(&path, "[reticulum]\nremote_management_allowed = deadbeef\n").unwrap();
assert!(matches!(
Config::from_file(&path),
Err(ConfigError::InvalidValue { key, .. }) if key == "remote_management_allowed"
));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn test_loaded_config_preserves_network_identity_value_without_side_effect() {
let dir = unique_test_dir("network-identity");
let identity = dir.join("network.identity");
let path = dir.join("config");
std::fs::write(
&path,
format!(
"[reticulum]\nnetwork_identity = {}\n",
identity.file_name().unwrap().to_string_lossy()
),
)
.unwrap();
let config = Config::from_file(&path).unwrap();
assert!(!identity.is_file());
let expected = identity.file_name().unwrap().to_string_lossy();
assert_eq!(
config
.section("reticulum")
.and_then(|section| section.get("network_identity")),
Some(expected.as_ref())
);
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(unix)]
#[test]
fn test_from_file_follows_symlink_like_configobj() {
let dir = unique_test_dir("symlink-config");
let target = dir.join("target_config");
let link = dir.join("config");
std::fs::write(&target, "[reticulum]\nshare_instance = No\n").unwrap();
std::os::unix::fs::symlink(&target, &link).unwrap();
let config = Config::from_file(&link).unwrap();
assert_eq!(
config
.section("reticulum")
.and_then(|section| section.get_bool("share_instance")),
Some(false)
);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn test_get_bool_or_default() {
let sec = ConfigSection::new();
assert!(sec.get_bool_or("missing", true));
assert!(!sec.get_bool_or("missing", false));
}
#[test]
fn test_strip_comment_in_quotes() {
let result = strip_comment(r#"key = "value # with hash""#);
assert_eq!(result, r#"key = "value # with hash""#);
}
fn unique_test_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"reticulum_config_test_{name}_{}_{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&dir).unwrap();
dir
}
}
+40
View File
@@ -0,0 +1,40 @@
pub const LOCAL_INTERFACE_PORT: u16 = 37428;
pub const LOCAL_CONTROL_PORT: u16 = 37429;
pub const JOB_INTERVAL: u64 = 300;
pub const CLEAN_INTERVAL: u64 = 900;
pub const PERSIST_INTERVAL: u64 = 43200;
/// Minimum spacing between externally-requested persists.
pub const GRACIOUS_PERSIST_INTERVAL: u64 = 300;
pub const RESOURCE_CACHE: u64 = 86400;
pub const MAX_QUEUED_ANNOUNCES: usize = 16384;
pub const QUEUED_ANNOUNCE_LIFE: u64 = 86400;
/// Percentage matching Python `Reticulum.ANNOUNCE_CAP = 2`; transport actor
/// divides by 100 before applying to bitrate math.
pub const ANNOUNCE_CAP: f64 = 2.0;
pub const MINIMUM_BITRATE: u64 = 5;
pub const IFAC_MIN_SIZE: usize = 1;
pub const LOG_MAXSIZE: u64 = 5_242_880;
pub const DEFAULT_INSTANCE_NAME: &str = "default";
pub const RPC_AUTH_TAG: &[u8] = b"reticulum_rs_rpc_auth_v1";
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_constants() {
assert_eq!(LOCAL_INTERFACE_PORT, 37428);
assert_eq!(LOCAL_CONTROL_PORT, 37429);
assert_eq!(JOB_INTERVAL, 300);
assert_eq!(CLEAN_INTERVAL, 900);
assert_eq!(PERSIST_INTERVAL, 43200);
assert_eq!(RESOURCE_CACHE, 86400);
assert_eq!(LOG_MAXSIZE, 5_242_880);
}
}
File diff suppressed because it is too large. Load diff
+112
View File
@@ -0,0 +1,112 @@
//! Cache cleaning every 15 minutes, persistence every 12 hours (or next
//! 5-minute gracious interval on explicit request). Python: `Reticulum.py`.
use std::time::{Duration, Instant};
use crate::constants::*;
pub struct JobScheduler {
last_clean: Instant,
last_persist: Instant,
persist_requested: bool,
last_gracious_persist: Instant,
}
impl JobScheduler {
pub fn new() -> Self {
let now = Instant::now();
Self {
last_clean: now,
last_persist: now,
persist_requested: false,
last_gracious_persist: now,
}
}
pub fn tick(&mut self) -> Vec<Job> {
self.tick_at(Instant::now())
}
fn tick_at(&mut self, now: Instant) -> Vec<Job> {
let mut jobs = Vec::new();
if now.duration_since(self.last_clean) >= Duration::from_secs(CLEAN_INTERVAL) {
jobs.push(Job::CleanCache);
self.last_clean = now;
}
if now.duration_since(self.last_persist) >= Duration::from_secs(PERSIST_INTERVAL) {
jobs.push(Job::PersistData);
self.last_persist = now;
self.persist_requested = false;
}
if self.persist_requested
&& now.duration_since(self.last_gracious_persist)
>= Duration::from_secs(GRACIOUS_PERSIST_INTERVAL)
{
jobs.push(Job::PersistData);
self.last_gracious_persist = now;
self.persist_requested = false;
}
jobs
}
pub fn request_persist(&mut self) {
self.persist_requested = true;
}
}
impl Default for JobScheduler {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Job {
CleanCache,
PersistData,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_scheduler_initial_tick() {
let mut scheduler = JobScheduler::new();
let jobs = scheduler.tick();
assert!(jobs.is_empty());
}
#[test]
fn test_scheduler_persist_request() {
let mut scheduler = JobScheduler::new();
assert!(!scheduler.persist_requested);
scheduler.request_persist();
assert!(scheduler.persist_requested);
}
#[test]
fn test_scheduler_forced_persist() {
let mut scheduler = JobScheduler::new();
let now = Instant::now();
scheduler.last_gracious_persist = now;
scheduler.request_persist();
let jobs = scheduler.tick_at(now + Duration::from_secs(GRACIOUS_PERSIST_INTERVAL + 1));
assert!(jobs.contains(&Job::PersistData));
assert!(!scheduler.persist_requested);
}
#[test]
fn test_scheduler_clean_due() {
let mut scheduler = JobScheduler::new();
let now = Instant::now();
scheduler.last_clean = now;
let jobs = scheduler.tick_at(now + Duration::from_secs(CLEAN_INTERVAL + 1));
assert!(jobs.contains(&Job::CleanCache));
}
}
+19
View File
@@ -0,0 +1,19 @@
//! Reticulum runtime: config, lifecycle, RPC, and the [`reticulum::ReticulumHandle`]
//! that user code holds. Python reference: `RNS/Reticulum.py`.
pub mod config;
pub mod constants;
pub mod interface_factory;
pub mod jobs;
pub mod lifecycle;
pub mod link_client;
pub mod link_manager;
pub mod platform;
pub mod probe;
pub mod remote_management;
pub mod remote_management_schema;
pub mod reticulum;
pub mod rncp;
pub mod rnsh;
pub mod rpc;
pub mod rpc_server;
+147
View File
@@ -0,0 +1,147 @@
//! Ctrl-C / SIGTERM flip a shared flag that all runtime tasks observe,
//! allowing them to detach interfaces and flush state cleanly before exit.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use tokio::sync::mpsc;
#[derive(Clone)]
pub struct ShutdownSignal {
flag: Arc<AtomicBool>,
notify: Arc<tokio::sync::Notify>,
}
impl ShutdownSignal {
pub fn new() -> Self {
Self {
flag: Arc::new(AtomicBool::new(false)),
notify: Arc::new(tokio::sync::Notify::new()),
}
}
pub fn trigger(&self) {
if !self.flag.swap(true, Ordering::SeqCst) {
tracing::debug!("shutdown triggered, notifying waiters");
}
self.notify.notify_waiters();
}
pub fn is_triggered(&self) -> bool {
self.flag.load(Ordering::SeqCst)
}
pub async fn wait(&self) {
if self.is_triggered() {
return;
}
self.notify.notified().await;
}
}
impl Default for ShutdownSignal {
fn default() -> Self {
Self::new()
}
}
pub struct ExitHandler {
actions: Vec<Box<dyn FnOnce() + Send>>,
}
impl ExitHandler {
pub fn new() -> Self {
Self {
actions: Vec::new(),
}
}
pub fn register(&mut self, action: impl FnOnce() + Send + 'static) {
self.actions.push(Box::new(action));
}
pub fn execute(self) {
let n = self.actions.len();
tracing::debug!(actions = n, "running exit handlers");
for action in self.actions {
action();
}
}
}
impl Default for ExitHandler {
fn default() -> Self {
Self::new()
}
}
/// Install Ctrl-C / SIGTERM handlers that trip `shutdown`. Returned receiver
/// yields once on signal for await-based callers.
pub fn install_signal_handlers(shutdown: ShutdownSignal) -> mpsc::Receiver<()> {
let (tx, rx) = mpsc::channel(1);
let shutdown_clone = shutdown.clone();
tokio::spawn(async move {
let ctrl_c = tokio::signal::ctrl_c();
ctrl_c.await.ok();
tracing::info!("received shutdown signal");
shutdown_clone.trigger();
let _ = tx.send(()).await;
});
rx
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_shutdown_signal() {
let signal = ShutdownSignal::new();
assert!(!signal.is_triggered());
signal.trigger();
assert!(signal.is_triggered());
}
#[test]
fn test_shutdown_signal_clone() {
let signal = ShutdownSignal::new();
let clone = signal.clone();
signal.trigger();
assert!(clone.is_triggered());
}
#[test]
fn test_exit_handler() {
use std::sync::atomic::{AtomicU32, Ordering};
let counter = Arc::new(AtomicU32::new(0));
let mut handler = ExitHandler::new();
let c1 = counter.clone();
handler.register(move || {
c1.fetch_add(1, Ordering::SeqCst);
});
let c2 = counter.clone();
handler.register(move || {
c2.fetch_add(10, Ordering::SeqCst);
});
handler.execute();
assert_eq!(counter.load(Ordering::SeqCst), 11);
}
#[tokio::test]
async fn test_shutdown_wait() {
let signal = ShutdownSignal::new();
let signal_clone = signal.clone();
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
signal_clone.trigger();
});
signal.wait().await;
assert!(signal.is_triggered());
}
}
+680
View File
@@ -0,0 +1,680 @@
//! Initiator-side Link client for `rnstatus -R` / `rnpath -R`. Each `query`
//! does the full handshake (pubkey discovery → link → identify → request →
//! response → close) over its own destination channel.
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use bytes::Bytes;
use tokio::sync::mpsc;
use tokio::time::timeout;
use rns_crypto::ed25519::Ed25519PublicKey;
use rns_identity::destination::Destination;
use rns_identity::identity::Identity;
use rns_link::link::{CloseReason, Link};
use rns_protocol::resource::{InboundTransfer, TransferAction};
use rns_protocol::resource_adv::ResourceAdvertisement;
use rns_transport::link_messages::DestinationEvent;
use rns_transport::messages::{AnnounceHandlerEvent, OutboundRequest, TransportMessage};
#[derive(Debug, thiserror::Error)]
pub enum LinkClientError {
#[error("transport channel closed or full")]
TransportUnavailable,
#[error("timed out waiting for {0}")]
Timeout(&'static str),
#[error("could not discover remote identity public key for destination")]
PubkeyNotDiscovered,
#[error("link proof validation failed: {0}")]
ProofInvalid(String),
#[error("link establishment failed: {0}")]
HandshakeFailed(String),
#[error("local identity has no signing key (cannot identify on link)")]
NoSigningKey,
#[error("encryption failure on link: {0}")]
LinkCrypto(String),
#[error("unexpected response from remote: {0}")]
UnexpectedResponse(String),
}
#[derive(Clone)]
pub struct LinkClient {
transport_tx: mpsc::Sender<TransportMessage>,
identity: Arc<Identity>,
}
impl LinkClient {
pub fn new(transport_tx: mpsc::Sender<TransportMessage>, identity: Identity) -> Self {
Self {
transport_tx,
identity: Arc::new(identity),
}
}
/// Open a Link to `app_name` on `remote_transport_hash`, send one
/// request, return the response.
pub async fn query(
&self,
remote_transport_hash: [u8; 16],
app_name: &str,
path: &str,
payload: Vec<u8>,
hops: u8,
overall_timeout: Duration,
) -> Result<Vec<u8>, LinkClientError> {
let started = Instant::now();
let deadline = started + overall_timeout;
let dest_hash =
Destination::hash_from_name_and_identity(app_name, Some(&remote_transport_hash));
// Register the handler before the path request so the answering
// announce (carrying the pubkey) is observed.
let (ann_tx, mut ann_rx) = mpsc::channel::<AnnounceHandlerEvent>(64);
self.send_msg(TransportMessage::RegisterAnnounceHandler {
aspect_filter: Some(app_name.to_string()),
receive_path_responses: true,
callback_tx: ann_tx,
})
.await?;
self.send_msg(TransportMessage::RequestPath {
destination_hash: dest_hash,
})
.await?;
let pubkey = wait_for_pubkey(&mut ann_rx, dest_hash, time_remaining(deadline)?).await?;
let _ = self
.transport_tx
.try_send(TransportMessage::DeregisterAnnounceHandler {
aspect_filter: Some(app_name.to_string()),
});
let (mut link, request_data) = Link::new_initiator(dest_hash, hops);
let link_id = link.link_id;
// Register link_id as a destination so inbound LRPROOF / Response
// packets route back to this task via dest_rx.
let (dest_tx, mut dest_rx) = mpsc::channel::<DestinationEvent>(128);
self.send_msg(TransportMessage::RegisterDestination {
hash: link_id,
app_name: "rnstatus.linkclient".to_string(),
delivery_tx: Some(dest_tx),
})
.await?;
let req_pkt = build_link_request_packet(dest_hash, &request_data);
self.send_msg(TransportMessage::Outbound(OutboundRequest {
raw: req_pkt,
destination_hash: dest_hash,
}))
.await?;
let proof_data = wait_for_proof(&mut dest_rx, link_id, time_remaining(deadline)?).await?;
let identity_ed25519_pub: [u8; 32] = pubkey[32..64].try_into().map_err(|_| {
LinkClientError::ProofInvalid("remote public key is not 64 bytes".into())
})?;
let identity_verify_key = Ed25519PublicKey::from_bytes(&identity_ed25519_pub)
.map_err(|e| LinkClientError::ProofInvalid(format!("verify key: {e}")))?;
let rtt_data = link
.validate_proof(&proof_data, &identity_verify_key, &identity_ed25519_pub)
.map_err(|e| LinkClientError::ProofInvalid(format!("{e:?}")))?;
let rtt_pkt =
build_data_packet(link_id, rns_wire::context::PacketContext::Lrrtt, &rtt_data);
self.send_msg(TransportMessage::Outbound(OutboundRequest {
raw: rtt_pkt,
destination_hash: link_id,
}))
.await?;
let our_pub = self.identity.get_public_key();
let our_priv = self
.identity
.get_signing_key()
.ok_or(LinkClientError::NoSigningKey)?;
let identify_data = link
.identify(&our_pub, &our_priv)
.map_err(|e| LinkClientError::LinkCrypto(format!("identify: {e:?}")))?;
let identify_pkt = build_data_packet(
link_id,
rns_wire::context::PacketContext::LinkIdentify,
&identify_data,
);
self.send_msg(TransportMessage::Outbound(OutboundRequest {
raw: identify_pkt,
destination_hash: link_id,
}))
.await?;
let req_timeout = Duration::from_secs(5);
let (encrypted_req, request_id) = link
.request(path, Some(&payload), req_timeout)
.map_err(|e| LinkClientError::LinkCrypto(format!("request: {e:?}")))?;
let request_pkt = build_data_packet(
link_id,
rns_wire::context::PacketContext::Request,
&encrypted_req,
);
let packet_request_id = rns_wire::hash::truncated_packet_hash(
&request_pkt,
rns_wire::flags::HeaderType::Header1,
);
link.update_pending_request_id(&request_id, packet_request_id);
self.send_msg(TransportMessage::Outbound(OutboundRequest {
raw: request_pkt,
destination_hash: link_id,
}))
.await?;
let response = wait_for_response(
&self.transport_tx,
&mut dest_rx,
&mut link,
link_id,
packet_request_id,
time_remaining(deadline)?,
)
.await;
// Tear down even on failure so the remote doesn't keep link state.
let _ = self.send_close(&mut link).await;
let _ = self
.transport_tx
.try_send(TransportMessage::DeregisterDestination { hash: link_id });
response
}
async fn send_msg(&self, msg: TransportMessage) -> Result<(), LinkClientError> {
self.transport_tx
.send(msg)
.await
.map_err(|_| LinkClientError::TransportUnavailable)
}
async fn send_close(&self, link: &mut Link) -> Result<(), LinkClientError> {
let link_id = link.link_id;
let Some(teardown_data) = link.teardown(CloseReason::InitiatorClosed) else {
return Ok(());
};
let close_pkt = build_data_packet(
link_id,
rns_wire::context::PacketContext::LinkClose,
&teardown_data,
);
self.send_msg(TransportMessage::Outbound(OutboundRequest {
raw: close_pkt,
destination_hash: link_id,
}))
.await
}
}
fn time_remaining(deadline: Instant) -> Result<Duration, LinkClientError> {
let now = Instant::now();
if now >= deadline {
Err(LinkClientError::Timeout("overall query"))
} else {
Ok(deadline - now)
}
}
async fn wait_for_pubkey(
rx: &mut mpsc::Receiver<AnnounceHandlerEvent>,
target_dest_hash: [u8; 16],
deadline: Duration,
) -> Result<[u8; 64], LinkClientError> {
let fut = async {
while let Some(ev) = rx.recv().await {
if ev.destination_hash == target_dest_hash
&& let Some(pk) = ev.public_key
{
return Ok(pk);
}
}
Err(LinkClientError::PubkeyNotDiscovered)
};
timeout(deadline, fut)
.await
.map_err(|_| LinkClientError::Timeout("path/announce discovery"))?
}
async fn wait_for_proof(
rx: &mut mpsc::Receiver<DestinationEvent>,
link_id: [u8; 16],
deadline: Duration,
) -> Result<Vec<u8>, LinkClientError> {
let fut = async {
while let Some(ev) = rx.recv().await {
match ev {
DestinationEvent::LinkClosed { link_id: closed_id } if closed_id == link_id => {
return Err(LinkClientError::HandshakeFailed("link closed".into()));
}
DestinationEvent::InboundPacket { raw, .. } => {
let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) {
Ok(h) => h,
Err(_) => continue,
};
let is_proof = header.flags.packet_type == rns_wire::flags::PacketType::Proof
&& header.destination_hash == link_id;
if is_proof && raw.len() > data_offset {
return Ok(raw[data_offset..].to_vec());
}
}
_ => {}
}
}
Err(LinkClientError::HandshakeFailed(
"destination channel closed".into(),
))
};
timeout(deadline, fut)
.await
.map_err(|_| LinkClientError::Timeout("link proof"))?
}
async fn wait_for_response(
transport_tx: &mpsc::Sender<TransportMessage>,
rx: &mut mpsc::Receiver<DestinationEvent>,
link: &mut Link,
link_id: [u8; 16],
request_id: [u8; 16],
deadline: Duration,
) -> Result<Vec<u8>, LinkClientError> {
let fut = async {
let mut inbound_resources: HashMap<[u8; 32], InboundTransfer> = HashMap::new();
while let Some(ev) = rx.recv().await {
match ev {
DestinationEvent::LinkClosed { link_id: closed_id } if closed_id == link_id => {
return Err(LinkClientError::HandshakeFailed("link closed".into()));
}
DestinationEvent::InboundPacket { raw, .. } => {
let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) {
Ok(h) => h,
Err(_) => continue,
};
if header.destination_hash != link_id {
continue;
}
let body = &raw[data_offset..];
match header.context {
rns_wire::context::PacketContext::Response => {
match link.handle_response(body) {
Ok((id, response_data)) => {
if id == request_id {
return Ok(response_data);
}
}
Err(e) => {
return Err(LinkClientError::LinkCrypto(format!(
"response decrypt: {e:?}"
)));
}
}
}
rns_wire::context::PacketContext::ResourceAdv => {
let plaintext = link.decrypt(body).map_err(|e| {
LinkClientError::LinkCrypto(format!(
"resource advertisement decrypt: {e:?}"
))
})?;
let adv = ResourceAdvertisement::unpack(&plaintext).map_err(|e| {
LinkClientError::UnexpectedResponse(format!(
"resource advertisement: {e}"
))
})?;
if !adv.flags.is_response
|| adv.request_id.as_deref() != Some(request_id.as_slice())
{
continue;
}
let mut random_hash = [0u8; rns_protocol::resource::RANDOM_HASH_SIZE];
let copy_len = adv.random_hash.len().min(random_hash.len());
random_hash[..copy_len].copy_from_slice(&adv.random_hash[..copy_len]);
let rtt = link.rtt.unwrap_or(Duration::from_millis(500));
let mut transfer = InboundTransfer::from_advertisement(
adv.num_parts,
adv.transfer_size,
adv.data_size,
random_hash,
adv.resource_hash,
adv.flags,
adv.get_map_hashes(),
rtt,
)
.map_err(|e| {
LinkClientError::UnexpectedResponse(format!(
"resource transfer: {e:?}"
))
})?;
if let TransferAction::SendRequest(req) = transfer.request_next() {
send_link_data(
transport_tx,
link,
link_id,
rns_wire::context::PacketContext::ResourceReq,
&req,
true,
)?;
}
inbound_resources.insert(adv.resource_hash, transfer);
}
rns_wire::context::PacketContext::Resource => {
let mut action_to_send = None;
let mut completed_rh = None;
for (rh, transfer) in &mut inbound_resources {
let action = transfer.receive_part(body.to_vec());
match action {
TransferAction::SendHmu(_) | TransferAction::SendRequest(_) => {
action_to_send = Some(action);
}
TransferAction::Complete => {
completed_rh = Some(*rh);
}
TransferAction::Failed(reason) => {
return Err(LinkClientError::UnexpectedResponse(format!(
"resource transfer failed: {reason}"
)));
}
_ => {}
}
if completed_rh.is_none() && transfer.resource.is_complete() {
completed_rh = Some(*rh);
}
if action_to_send.is_some() || completed_rh.is_some() {
break;
}
}
if let Some(action) = action_to_send {
let (context, payload) = match action {
TransferAction::SendHmu(hmu) => {
(rns_wire::context::PacketContext::ResourceHmu, hmu)
}
TransferAction::SendRequest(req) => {
(rns_wire::context::PacketContext::ResourceReq, req)
}
_ => unreachable!(),
};
send_link_data(
transport_tx,
link,
link_id,
context,
&payload,
true,
)?;
}
if let Some(rh) = completed_rh {
let (assembled, proof) = {
let transfer =
inbound_resources.get_mut(&rh).ok_or_else(|| {
LinkClientError::UnexpectedResponse(
"completed resource disappeared".into(),
)
})?;
let keys = link.session_keys().ok_or_else(|| {
LinkClientError::LinkCrypto(
"resource response missing link keys".into(),
)
})?;
let decrypt_fn = move |data: &[u8]| {
rns_link::encryption::link_decrypt(&keys, data).map_err(
|_| {
rns_protocol::resource::ResourceError::DecryptFailed
},
)
};
transfer.complete(Some(&decrypt_fn)).map_err(|e| {
LinkClientError::UnexpectedResponse(format!(
"resource assemble: {e:?}"
))
})?
};
send_link_proof(transport_tx, link_id, &proof)?;
inbound_resources.remove(&rh);
match link.handle_response_plaintext(&assembled) {
Ok((id, response_data)) => {
if id == request_id {
return Ok(response_data);
}
}
Err(e) => {
return Err(LinkClientError::LinkCrypto(format!(
"resource response decode: {e:?}"
)));
}
}
}
}
rns_wire::context::PacketContext::ResourceHmu => {
let plaintext = link.decrypt(body).map_err(|e| {
LinkClientError::LinkCrypto(format!(
"resource hashmap update decrypt: {e:?}"
))
})?;
let (rh, segment, hashmap) =
rns_protocol::resource::parse_hashmap_update(&plaintext).map_err(
|e| {
LinkClientError::UnexpectedResponse(format!(
"resource hashmap update: {e:?}"
))
},
)?;
let Some(transfer) = inbound_resources.get_mut(&rh) else {
continue;
};
if let TransferAction::SendRequest(req) =
transfer.hashmap_update(segment, &hashmap)
{
send_link_data(
transport_tx,
link,
link_id,
rns_wire::context::PacketContext::ResourceReq,
&req,
true,
)?;
}
}
rns_wire::context::PacketContext::LinkClose
if link.receive_teardown(body) =>
{
return Err(LinkClientError::HandshakeFailed(
"link closed by remote".into(),
));
}
_ => {}
}
}
_ => {}
}
}
Err(LinkClientError::HandshakeFailed(
"destination channel closed".into(),
))
};
timeout(deadline, fut)
.await
.map_err(|_| LinkClientError::Timeout("response"))?
}
fn send_link_data(
transport_tx: &mpsc::Sender<TransportMessage>,
link: &Link,
link_id: [u8; 16],
context: rns_wire::context::PacketContext,
body: &[u8],
encrypt: bool,
) -> Result<(), LinkClientError> {
let payload = if encrypt {
link.encrypt(body)
.map_err(|e| LinkClientError::LinkCrypto(format!("resource control: {e:?}")))?
} else {
body.to_vec()
};
let packet = build_data_packet(link_id, context, &payload);
transport_tx
.try_send(TransportMessage::Outbound(OutboundRequest {
raw: packet,
destination_hash: link_id,
}))
.map_err(|_| LinkClientError::TransportUnavailable)
}
fn send_link_proof(
transport_tx: &mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
proof: &[u8],
) -> Result<(), LinkClientError> {
let packet = build_proof_packet(
link_id,
rns_wire::context::PacketContext::ResourcePrf,
proof,
);
transport_tx
.try_send(TransportMessage::Outbound(OutboundRequest {
raw: packet,
destination_hash: link_id,
}))
.map_err(|_| LinkClientError::TransportUnavailable)
}
fn build_link_request_packet(dest_hash: [u8; 16], request_data: &[u8]) -> Bytes {
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Single,
packet_type: rns_wire::flags::PacketType::LinkRequest,
},
hops: 0,
transport_id: None,
destination_hash: dest_hash,
context: rns_wire::context::PacketContext::None,
};
let mut raw = header.pack();
raw.extend_from_slice(request_data);
Bytes::from(raw)
}
fn build_proof_packet(
link_id: [u8; 16],
context: rns_wire::context::PacketContext,
body: &[u8],
) -> Bytes {
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Proof,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context,
};
let mut raw = header.pack();
raw.extend_from_slice(body);
Bytes::from(raw)
}
fn build_data_packet(
link_id: [u8; 16],
context: rns_wire::context::PacketContext,
body: &[u8],
) -> Bytes {
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Data,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context,
};
let mut raw = header.pack();
raw.extend_from_slice(body);
Bytes::from(raw)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn build_link_request_packet_has_link_request_type() {
let pkt = build_link_request_packet([0xAA; 16], &[0x01, 0x02, 0x03]);
let (header, _) = rns_wire::header::PacketHeader::unpack(&pkt).unwrap();
assert_eq!(
header.flags.packet_type,
rns_wire::flags::PacketType::LinkRequest
);
assert_eq!(header.destination_hash, [0xAA; 16]);
}
#[test]
fn build_data_packet_carries_context() {
let pkt = build_data_packet([0xBB; 16], rns_wire::context::PacketContext::Lrrtt, &[0x42]);
let (header, _) = rns_wire::header::PacketHeader::unpack(&pkt).unwrap();
assert_eq!(header.context, rns_wire::context::PacketContext::Lrrtt);
assert_eq!(header.flags.packet_type, rns_wire::flags::PacketType::Data);
}
#[tokio::test]
async fn time_remaining_returns_err_after_deadline() {
let past = Instant::now();
tokio::time::sleep(Duration::from_millis(1)).await;
assert!(matches!(
time_remaining(past),
Err(LinkClientError::Timeout(_))
));
}
#[tokio::test]
async fn send_close_uses_authenticated_teardown_payload() {
let dest_hash = [0xCC; 16];
let responder_key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let responder_pub = responder_key.public_key();
let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1);
let (mut responder, proof_data) =
Link::new_responder(&request_data, &responder_key, dest_hash, 1).unwrap();
let rtt_data = initiator
.validate_proof(&proof_data, &responder_pub, &responder_pub.to_bytes())
.unwrap();
responder.receive_rtt_packet(&rtt_data).unwrap();
let (transport_tx, mut transport_rx) = mpsc::channel(4);
let client = LinkClient::new(transport_tx, Identity::new());
client.send_close(&mut initiator).await.unwrap();
let TransportMessage::Outbound(request) = transport_rx.try_recv().unwrap() else {
panic!("expected outbound close packet");
};
let (header, offset) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
assert_eq!(header.context, rns_wire::context::PacketContext::LinkClose);
assert!(responder.receive_teardown(&request.raw[offset..]));
}
}
File diff suppressed because it is too large. Load diff
+173
View File
@@ -0,0 +1,173 @@
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Platform {
Linux,
MacOS,
Windows,
Android,
Other,
}
impl Platform {
pub fn current() -> Self {
if cfg!(target_os = "android") {
Platform::Android
} else if cfg!(target_os = "linux") {
Platform::Linux
} else if cfg!(target_os = "macos") {
Platform::MacOS
} else if cfg!(target_os = "windows") {
Platform::Windows
} else {
Platform::Other
}
}
pub fn has_unix_sockets(&self) -> bool {
matches!(self, Platform::Linux | Platform::MacOS | Platform::Android)
}
pub fn config_dir(&self) -> PathBuf {
match self {
Platform::Windows => {
if let Ok(appdata) = std::env::var("APPDATA") {
PathBuf::from(appdata).join("rsReticulum")
} else {
PathBuf::from(".rsReticulum")
}
}
Platform::Android => {
// Android has no user HOME; callers must pass an explicit configdir.
tracing::warn!(
"Platform::config_dir() called on Android without explicit configdir"
);
PathBuf::from("/data/local/tmp/.rsReticulum")
}
_ => {
if let Ok(home) = std::env::var("HOME") {
PathBuf::from(home).join(".rsReticulum")
} else {
PathBuf::from(".rsReticulum")
}
}
}
}
pub fn display_name(&self) -> &'static str {
match self {
Platform::Linux => "linux",
Platform::MacOS => "darwin",
Platform::Windows => "win32",
Platform::Android => "android",
Platform::Other => "unknown",
}
}
}
/// Explicit `configdir` wins. Without one, use rsReticulum-specific defaults:
/// `/etc/rsReticulum/config`, then `~/.config/rsReticulum/config`, then
/// `~/.rsReticulum` on Unix-like systems. Windows uses the appdata
/// `rsReticulum` directory. Pass `--config ~/.reticulum` explicitly when
/// intentionally sharing a Python Reticulum config.
pub fn resolve_config_dir(configdir: Option<&str>) -> PathBuf {
match configdir {
Some(dir) => PathBuf::from(dir),
None => {
let platform = Platform::current();
if !matches!(platform, Platform::Windows | Platform::Android) {
let etc = PathBuf::from("/etc/rsReticulum");
if etc.join("config").is_file() {
return etc;
}
if let Ok(home) = std::env::var("HOME") {
let xdg = PathBuf::from(home).join(".config/rsReticulum");
if xdg.join("config").is_file() {
return xdg;
}
}
}
platform.config_dir()
}
}
}
pub struct StoragePaths {
pub config_dir: PathBuf,
pub interface_dir: PathBuf,
pub storage_dir: PathBuf,
pub cache_dir: PathBuf,
pub resource_dir: PathBuf,
pub identity_dir: PathBuf,
pub blackhole_dir: PathBuf,
pub announce_cache_dir: PathBuf,
}
impl StoragePaths {
pub fn from_config_dir(config_dir: &Path) -> Self {
let storage_dir = config_dir.join("storage");
let cache_dir = storage_dir.join("cache");
Self {
config_dir: config_dir.to_path_buf(),
interface_dir: config_dir.join("interfaces"),
storage_dir: storage_dir.clone(),
cache_dir: cache_dir.clone(),
resource_dir: storage_dir.join("resources"),
identity_dir: storage_dir.join("identities"),
blackhole_dir: storage_dir.join("blackhole"),
announce_cache_dir: cache_dir.join("announces"),
}
}
pub fn ensure_dirs(&self) -> std::io::Result<()> {
std::fs::create_dir_all(&self.config_dir)?;
std::fs::create_dir_all(&self.interface_dir)?;
std::fs::create_dir_all(&self.storage_dir)?;
std::fs::create_dir_all(&self.cache_dir)?;
std::fs::create_dir_all(&self.resource_dir)?;
std::fs::create_dir_all(&self.identity_dir)?;
std::fs::create_dir_all(&self.blackhole_dir)?;
std::fs::create_dir_all(&self.announce_cache_dir)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_platform_detection() {
let platform = Platform::current();
let _ = platform.display_name();
let _ = platform.has_unix_sockets();
let _ = platform.config_dir();
}
#[test]
fn test_explicit_config_dir() {
let dir = resolve_config_dir(Some("/tmp/test_reticulum"));
assert_eq!(dir, PathBuf::from("/tmp/test_reticulum"));
}
#[test]
fn test_platform_config_dir_uses_rust_branded_name() {
let dir = Platform::current().config_dir();
assert!(
dir.ends_with("rsReticulum")
|| dir.ends_with(".rsReticulum")
|| dir.ends_with("/data/local/tmp/.rsReticulum")
);
}
#[test]
fn test_storage_paths() {
let config_dir = PathBuf::from("/tmp/test_config");
let paths = StoragePaths::from_config_dir(&config_dir);
assert_eq!(paths.interface_dir, config_dir.join("interfaces"));
assert_eq!(paths.storage_dir, config_dir.join("storage"));
assert_eq!(paths.cache_dir, config_dir.join("storage/cache"));
assert_eq!(paths.resource_dir, config_dir.join("storage/resources"));
assert_eq!(paths.identity_dir, config_dir.join("storage/identities"));
}
}
Loaded 100 of 178 files, more files were not shown because too many files have changed in this diff. Show more