mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-22 23:10:33 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6d0d698dd | ||
|
|
54c85253e3 | ||
|
|
5061c0f2bc | ||
|
|
d7151fde2f | ||
|
|
83be931e74 | ||
|
|
a839ec05c6 | ||
|
|
7631c75afd | ||
|
|
5dadbd44bd | ||
|
|
dfb229bb4e | ||
|
|
82502fb72c | ||
|
|
5e35c9f9d9 | ||
|
|
0ce5a12a65 | ||
|
|
24db8a0245 | ||
|
|
3d53958892 | ||
|
|
137c84e390 | ||
|
|
dec159dae4 | ||
|
|
973b8a8cd4 | ||
|
|
428c22ff15 | ||
|
|
8ce5059a55 | ||
|
|
0e9bf3408a | ||
|
|
f6b1190eba | ||
|
|
2d77484f93 | ||
|
|
d29bc9c42c | ||
|
|
6d2dad4f55 | ||
|
|
d623f2a604 | ||
|
|
3bb885cd63 | ||
|
|
ee9190db0f | ||
|
|
2fccaf0410 | ||
|
|
168ba42f89 | ||
|
|
f03a0c739d | ||
|
|
65d683404b | ||
|
|
4c4418ca93 | ||
|
|
3cd4ecadaa | ||
|
|
3aaff26b22 | ||
|
|
559525c3a4 | ||
|
|
add9d4f4b2 | ||
|
|
a9d534add4 | ||
|
|
09bb5c84dc | ||
|
|
dc77cdf014 | ||
|
|
5a974ae115 | ||
|
|
d7ec577253 | ||
|
|
03b6f411ad | ||
|
|
80b64223dc | ||
|
|
9b9226218d | ||
|
|
403c8084ba | ||
|
|
b0125cea65 | ||
|
|
4845bc1f93 | ||
|
|
7358306512 | ||
|
|
f0eedf453e | ||
|
|
df7b142d34 | ||
|
|
0e937f32ff | ||
|
|
45172c1cac | ||
|
|
b160045758 | ||
|
|
031550bbd6 | ||
|
|
2988da3757 | ||
|
|
7005c32200 | ||
|
|
0f411d35fb | ||
|
|
422b978a61 | ||
|
|
26e4bc308d | ||
|
|
54cdcbcc74 | ||
|
|
3811338f39 | ||
|
|
e1ce7f0064 | ||
|
|
124cc1ca6b | ||
|
|
27de48acc1 | ||
|
|
ad8c98cd0d | ||
|
|
20ed5a07b1 | ||
|
|
3d04714a3b | ||
|
|
874f742c27 | ||
|
|
8bdd1f828a | ||
|
|
0842e9d86e | ||
|
|
9bd2b80fba | ||
|
|
8e2dbf2bb9 | ||
|
|
55e6f37140 | ||
|
|
e8a21ce00c | ||
|
|
5b7ac43a82 | ||
|
|
0fa0d5e978 | ||
|
|
a25e7d384e | ||
|
|
73ca12852d | ||
|
|
19e65d4da9 | ||
|
|
71497c858d |
No files matched your search
@@ -2,6 +2,27 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
## 1.5.1 - 2026-11-18
|
||||
|
||||
- Bluetooth Peer runs in Gateway mode, so a node with transport on looks up the paths its Bluetooth peers ask for that it doesn't know yet. Nodes with transport off behave as before.
|
||||
- TCP and Backbone client interfaces report why they can't connect: `last_connect_error` (`refused`, `timed_out`, `dns`, `unreachable`, `closed_by_peer`, or `other`) and `connect_failures` in the interface stats, so an application can tell a hub that refuses or closes the connection from one still connecting. The shared-instance RPC doesn't carry them.
|
||||
- I2P interfaces log their `.b32.i2p` address once reachable, at loglevel 5 or higher, as Python Reticulum does.
|
||||
- Interface start-up code is compiled once instead of again in every crate that starts the runtime, which makes `rnsd-rs` about 1.5 MB smaller.
|
||||
- Bluetooth RNodes report battery, temperature, and channel load in the interface stats, as USB RNodes already do (`battery_state`, `battery_percent`, `cpu_temp`, `noise_floor`).
|
||||
- Bluetooth Peer: on Android, a link the app closes after a failed write reports `Disconnected`, so the peer no longer stays listed as connected. On Linux, disconnecting a peer reports it too, and the Central role keeps looking for a Bluetooth adapter that appears after start-up instead of giving up until restart.
|
||||
- Path requests are handled as in Python Reticulum 1.6.0. A node that knows a path but can't read its cached announce ignores the request instead of searching the network and blocking later requests for 45 seconds. A queued path response is dropped once other nodes are heard answering. Requests that arrive during a path-request burst are counted and checked before they wait, so duplicates no longer crowd out real ones. A search answer now also reaches a requester on the roaming interface it arrived on. A node asked again for a path it's about to answer keeps the answer's time, so a requester that repeats quickly is no longer left waiting forever.
|
||||
- Announce handler events carry `emitted`, the time the announcer stamped into the announce, so an application can tell an older cached announce in a path response from a newer one. `AnnounceHandlerEvent` struct literals need the new field.
|
||||
- **Follows Python Reticulum 1.6.1.** Announces and path requests are stamped by default, and `stamp_destinations` / `stamp_prs` can only turn stamping on, as upstream. New `[stamps] max_workers` and `worker_niceness`. Discovery stamps are accepted in both workblock forms. rngit takes `stamp_value` and `link_cost`.
|
||||
- Announces that can't change a known path are dropped before they are verified, each interface holds at most 64 announces during a burst and drops the useless ones early, and the announce rate table survives restarts. An announce isn't rebroadcast to an interface that already sent it to us, or after it only replaced an unresponsive path. A locally built announce must leave room for a relay's transport id, and is refused with `DestinationError::AnnounceTooLarge` (now `#[non_exhaustive]`) otherwise.
|
||||
- Paths to an instance's own local clients never time out, are marked responsive, and are answered only to the asker; a local client asking for a known path is answered from the table. A path request that leaves nothing in progress no longer blocks later requests for 45 seconds. Destination type filters take `<hash>` entries and the `known_destination_types` / `flagged_destination_types` files, Backbone listeners honour a `blocked_ips` file, interfaces take `hop_limiter`, and reverse-table entries expire after 3 minutes.
|
||||
- Tunnel synthesis carries signed stamp costs, version, and transport status, and hubs answer it; a bad signature or a blackholed hub detaches the interface, and an embedder hears each detach through `ReticulumHandle::subscribe_interface_detaches`. An unbound tunnel waits 10 minutes for its interface.
|
||||
- Received traffic is counted as accepted or filtered, links count their traffic and speeds, and the shared-instance RPC carries everything Python 1.6.1's `rnstatus` and `rnpath` read, plus `known_destinations`, `link_distribution`, and detach by tunnel id. rnstatus-rs and rnpath-rs show the 1.6.1 output, and the tools look for a path of their own before linking. `PathTableEntry.used` is now `Option<f64>`.
|
||||
- Backbone listeners take `client_limit` (default 500), and auto-connect stops at 12 discovered interfaces unless its caps are disabled.
|
||||
- A discovered interface's config entry drops line breaks and control characters from announced strings, so a pasted entry can't gain config sections.
|
||||
- `destination_stamper::prepare` makes and saves a destination's stamp before its first announce.
|
||||
- A shared-instance client's first announce is no longer lost: its registration path response now waits 250 ms, as upstream, so the shared instance passes the announce on. Integer config values take `_` digit groups (`1_0`), as Python's `int()` does.
|
||||
- rnsh-rs listeners no longer end a session when a client's identification and first message arrive together, rnx-rs sends results it used to drop silently (16 MB of output failed), and cuts output over about 30 MiB instead of dropping it, so the client prints its usual truncation notice, and rnpath-rs prints `Sending request...` only once its link is up.
|
||||
|
||||
## 1.5.0 - 2026-11-13
|
||||
|
||||
### Added
|
||||
|
||||
Generated
+22
-70
@@ -182,22 +182,13 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"
|
||||
dependencies = [
|
||||
"objc2 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -272,9 +263,9 @@ dependencies = [
|
||||
"futures",
|
||||
"jni 0.22.4",
|
||||
"log",
|
||||
"objc2 0.6.5",
|
||||
"objc2-core-bluetooth 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2",
|
||||
"objc2-core-bluetooth",
|
||||
"objc2-foundation",
|
||||
"once_cell",
|
||||
"static_assertions",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1445,22 +1436,6 @@ dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc-sys"
|
||||
version = "0.3.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804"
|
||||
dependencies = [
|
||||
"objc-sys",
|
||||
"objc2-encode",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.6.5"
|
||||
@@ -1470,17 +1445,6 @@ dependencies = [
|
||||
"objc2-encode",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-bluetooth"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a644b62ffb826a5277f536cf0f701493de420b13d40e700c452c36567771111"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"objc2 0.5.2",
|
||||
"objc2-foundation 0.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-bluetooth"
|
||||
version = "0.3.2"
|
||||
@@ -1488,8 +1452,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "79b30b9eacc37434a61377866f68b27acef9fa5496f25cc9ca8b2549032e0394"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2",
|
||||
"objc2-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1498,18 +1462,6 @@ version = "4.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
|
||||
|
||||
[[package]]
|
||||
name = "objc2-foundation"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2 0.5.1",
|
||||
"libc",
|
||||
"objc2 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-foundation"
|
||||
version = "0.3.2"
|
||||
@@ -1517,8 +1469,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
"block2",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1855,7 +1807,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-crypto"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"cbc",
|
||||
@@ -1876,7 +1828,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-git"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"clap",
|
||||
@@ -1897,7 +1849,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-identity"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"libc",
|
||||
@@ -1918,7 +1870,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-interface"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"bluer",
|
||||
"btleplug",
|
||||
@@ -1930,9 +1882,9 @@ dependencies = [
|
||||
"libc",
|
||||
"md-5",
|
||||
"mio",
|
||||
"objc2 0.5.2",
|
||||
"objc2-core-bluetooth 0.2.2",
|
||||
"objc2-foundation 0.2.2",
|
||||
"objc2",
|
||||
"objc2-core-bluetooth",
|
||||
"objc2-foundation",
|
||||
"rand 0.8.5",
|
||||
"rns-crypto",
|
||||
"rns-identity",
|
||||
@@ -1951,7 +1903,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-link"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"libc",
|
||||
@@ -1969,7 +1921,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-protocol"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"bzip2",
|
||||
"hex",
|
||||
@@ -1987,7 +1939,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-ratkey"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"bip39",
|
||||
@@ -2013,7 +1965,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-runtime"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
@@ -2042,7 +1994,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-tools"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bytes",
|
||||
@@ -2072,7 +2024,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-transport"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
@@ -2095,7 +2047,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-wire"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"rns-crypto",
|
||||
|
||||
+10
-10
@@ -15,7 +15,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
edition = "2024"
|
||||
license-file = "LICENSE"
|
||||
rust-version = "1.89"
|
||||
@@ -85,12 +85,12 @@ nix = { version = "0.29", features = ["term", "fs"] }
|
||||
proptest = "1"
|
||||
|
||||
# Workspace crates
|
||||
rns-crypto = { path = "crates/rns-crypto", version = "~1.5.0", default-features = false }
|
||||
rns-wire = { path = "crates/rns-wire", version = "~1.5.0", default-features = false }
|
||||
rns-identity = { path = "crates/rns-identity", version = "~1.5.0" }
|
||||
rns-transport = { path = "crates/rns-transport", version = "~1.5.0" }
|
||||
rns-link = { path = "crates/rns-link", version = "~1.5.0" }
|
||||
rns-protocol = { path = "crates/rns-protocol", version = "~1.5.0" }
|
||||
rns-interface = { path = "crates/rns-interface", version = "~1.5.0" }
|
||||
rns-runtime = { path = "crates/rns-runtime", version = "~1.5.0" }
|
||||
rns-ratkey = { path = "crates/rns-ratkey", version = "~1.5.0" }
|
||||
rns-crypto = { path = "crates/rns-crypto", version = "~1.5.1", default-features = false }
|
||||
rns-wire = { path = "crates/rns-wire", version = "~1.5.1", default-features = false }
|
||||
rns-identity = { path = "crates/rns-identity", version = "~1.5.1" }
|
||||
rns-transport = { path = "crates/rns-transport", version = "~1.5.1" }
|
||||
rns-link = { path = "crates/rns-link", version = "~1.5.1" }
|
||||
rns-protocol = { path = "crates/rns-protocol", version = "~1.5.1" }
|
||||
rns-interface = { path = "crates/rns-interface", version = "~1.5.1" }
|
||||
rns-runtime = { path = "crates/rns-runtime", version = "~1.5.1" }
|
||||
rns-ratkey = { path = "crates/rns-ratkey", version = "~1.5.1" }
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
[](LICENSE)
|
||||
[](https://www.rust-lang.org)
|
||||
[](https://reticulum.network/)
|
||||
[](https://reticulum.network/)
|
||||
[](#compatibility-notes)
|
||||
|
||||
[Reticulum Manual](https://reticulum.network/manual/) |
|
||||
@@ -36,13 +36,13 @@ a specification, and tracks the reference's wire behavior release by release.
|
||||
|
||||
## Build It
|
||||
|
||||
This guide describes the 1.5.0 release, [v1.5.0](https://github.com/ratspeak/rsReticulum/releases/tag/v1.5.0), the source line Ratspeak builds from.
|
||||
This guide describes the 1.5.1 release, [v1.5.1](https://github.com/ratspeak/rsReticulum/releases/tag/v1.5.1), the source line Ratspeak builds from.
|
||||
|
||||
From a new working directory:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/ratspeak/rsReticulum.git
|
||||
git -C rsReticulum checkout --detach v1.5.0
|
||||
git -C rsReticulum checkout --detach v1.5.1
|
||||
cd rsReticulum
|
||||
```
|
||||
|
||||
@@ -250,7 +250,7 @@ a password and give it only to programs you trust.
|
||||
|
||||
Runtime state is kept under `<config-dir>/storage/`. Known destinations and
|
||||
received ratchets are stored in `known_destinations.db` and cached announces in
|
||||
`cache/announces.db`, SQLite files in the format Python Reticulum 1.6.0 uses.
|
||||
`cache/announces.db`, SQLite files in the format Python Reticulum 1.6.1 uses.
|
||||
A shared-instance client reads the owner's database and never
|
||||
writes it. A database that cannot be opened is replaced by in-memory state for
|
||||
that session, with one log line. These stores come from the default
|
||||
@@ -295,7 +295,7 @@ identity.
|
||||
|
||||
## Compatibility Notes
|
||||
|
||||
rsReticulum 1.5.0 follows Python Reticulum 1.6.0, and its tools name that
|
||||
rsReticulum 1.5.1 follows Python Reticulum 1.6.1, and its tools name that
|
||||
release in `--version`.
|
||||
|
||||
Interface discovery announces this stack as `rsRNS`. `rnsd-rs` auto-connects to
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
# Rust API
|
||||
|
||||
This guide describes the 1.5.0 API, published as v1.5.0. The [1.5 migration
|
||||
This guide describes the 1.5.1 API, published as v1.5.1. The [1.5 migration
|
||||
guide](migrations/1.5.md) covers source and configuration changes.
|
||||
|
||||
Application code should begin with `rns_runtime::prelude`. It collects the
|
||||
@@ -76,7 +76,7 @@ The [capacity, IFAC, and receipt migration guide](migrations/capacity-and-receip
|
||||
|
||||
## Stability
|
||||
|
||||
The 1.5 line follows Reticulum 1.6.0. It makes the transport actor's state
|
||||
The 1.5 line follows Reticulum 1.6.0, and 1.6.1 from 1.5.1. It makes the transport actor's state
|
||||
private, marks growing enums and structs `#[non_exhaustive]`, keeps known
|
||||
destinations, ratchets, and cached announces in upstream's SQLite stores, and
|
||||
moves stamp costs and values to `f64`. See the
|
||||
|
||||
Generated
+19
-67
@@ -79,22 +79,13 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"
|
||||
dependencies = [
|
||||
"objc2 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -169,9 +160,9 @@ dependencies = [
|
||||
"futures",
|
||||
"jni 0.22.4",
|
||||
"log",
|
||||
"objc2 0.6.5",
|
||||
"objc2-core-bluetooth 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2",
|
||||
"objc2-core-bluetooth",
|
||||
"objc2-foundation",
|
||||
"once_cell",
|
||||
"static_assertions",
|
||||
"thiserror 2.0.20",
|
||||
@@ -994,22 +985,6 @@ dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc-sys"
|
||||
version = "0.3.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804"
|
||||
dependencies = [
|
||||
"objc-sys",
|
||||
"objc2-encode",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.6.5"
|
||||
@@ -1019,17 +994,6 @@ dependencies = [
|
||||
"objc2-encode",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-bluetooth"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a644b62ffb826a5277f536cf0f701493de420b13d40e700c452c36567771111"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"objc2 0.5.2",
|
||||
"objc2-foundation 0.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-bluetooth"
|
||||
version = "0.3.2"
|
||||
@@ -1037,8 +1001,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "79b30b9eacc37434a61377866f68b27acef9fa5496f25cc9ca8b2549032e0394"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2",
|
||||
"objc2-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1047,18 +1011,6 @@ version = "4.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
|
||||
|
||||
[[package]]
|
||||
name = "objc2-foundation"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2 0.5.1",
|
||||
"libc",
|
||||
"objc2 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-foundation"
|
||||
version = "0.3.2"
|
||||
@@ -1066,8 +1018,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
"block2",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1255,7 +1207,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-crypto"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"cbc",
|
||||
@@ -1273,7 +1225,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-identity"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"libc",
|
||||
@@ -1293,7 +1245,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-interface"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"bluer",
|
||||
"btleplug",
|
||||
@@ -1305,9 +1257,9 @@ dependencies = [
|
||||
"libc",
|
||||
"md-5",
|
||||
"mio",
|
||||
"objc2 0.5.2",
|
||||
"objc2-core-bluetooth 0.2.2",
|
||||
"objc2-foundation 0.2.2",
|
||||
"objc2",
|
||||
"objc2-core-bluetooth",
|
||||
"objc2-foundation",
|
||||
"rand",
|
||||
"rns-crypto",
|
||||
"rns-identity",
|
||||
@@ -1326,7 +1278,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-link"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"libc",
|
||||
@@ -1343,7 +1295,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-protocol"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"bzip2",
|
||||
"hex",
|
||||
@@ -1360,7 +1312,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-runtime"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
@@ -1388,7 +1340,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-transport"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
@@ -1408,7 +1360,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-wire"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"rns-crypto",
|
||||
"sha2",
|
||||
|
||||
@@ -106,6 +106,7 @@ control it.
|
||||
| `DiscoveryInterfaceConfig::backbone(String, ..)`, `DiscoveryInterfaceConfig::name: String` | `Option<String>`; `None` sends nil | `interface.discovery_name` may be unset (`RNS/Discovery.py:173`) |
|
||||
| `DiscoveryInterfaceConfig::modulation`, `DiscoveryInfo::modulation: Option<String>` | `Option<DiscoveryModulation>` | |
|
||||
| `PipeInterfaceConfig::respawn_delay: u64` | `f64` seconds | `c.as_float("respawn_delay")` (`RNS/Interfaces/PipeInterface.py:68`) |
|
||||
| `TunnelIdentity::synthesis(&self, name)` (1.5.1) | removed; a client interface asks transport (`TransportMessage::SynthesizeTunnel`), which signs with the identity from `SetTunnelIdentity` | the synthesis carries transport's signed costs and status (`RNS/Transport.py:3170`) |
|
||||
|
||||
`ble_peer::RATSPEAK_SERVICE_UUID`, `RATSPEAK_RX_UUID`, `RATSPEAK_TX_UUID`, and
|
||||
`RATSPEAK_ID_UUID` now hold the peer mesh's own UUIDs, service
|
||||
@@ -138,6 +139,8 @@ hardware MTU (`RNS/Interfaces/Interface.py:255-267`). Build them with `new`.
|
||||
| `constants::ANNOUNCE_CACHE_SWEEP_GRACE_SECS`, `constants::LINKS_CHECK_INTERVAL` | removed | |
|
||||
| `TransportActor::packet_metrics`, `packet_metrics_order` | `TransportQuery::GetPacketRssi`, `GetPacketSnr`, `GetPacketQ` | |
|
||||
| `InterfaceStatRpcEntry::ifac_size: usize` | `Option<usize>`; `None`, like `ifac_netname` and `ifac_signature`, for an interface without IFAC | `get_interface_stats()` (`RNS/Reticulum.py`) |
|
||||
| `IngressController::hold_announce(..)` returning `()` (1.5.1) | returns `HoldOutcome` (`Held`, `Replaced`, `Refused`); `is_filtered()` says whether the announce counts as filtered | a dropped or replaced held announce is filtered (`RNS/Interfaces/Interface.py:297-306`) |
|
||||
| `TransportMessage::SynthesizeTunnel { interface_id, raw_packet }` (1.5.1) | `SynthesizeTunnel { interface_id }`; the actor builds the synthesis | it carries signed costs, version, and transport status (`RNS/Transport.py:3170`) |
|
||||
| `TimerTick { timestamp }` | `TimerTick`, with no fields | |
|
||||
| `discovery::storage::classify(u64)`, `DiscoveredInterface::{discovered,last_heard}: u64` | `f64` timestamps | `time.time()` (`RNS/Discovery.py:604`) |
|
||||
| `discovery::build_local_manifest` | `build_manifest` | |
|
||||
@@ -420,6 +423,7 @@ constructor and match them with a wildcard arm:
|
||||
- **rns-runtime:** `InitOptions`, `ReticulumConfig`, `LinkManagerCommand`,
|
||||
`RnshError`.
|
||||
- **rns-link:** `CloseReason`.
|
||||
- **rns-identity:** `DestinationError`, from 1.5.1, which adds `AnnounceTooLarge`.
|
||||
|
||||
Exhaustive literals and matches over these types need updating:
|
||||
|
||||
@@ -443,8 +447,7 @@ Exhaustive literals and matches over these types need updating:
|
||||
`InboundTransfer`, `OutboundTransfer`, `MultiSegmentInbound`.
|
||||
- **rns-interface:** TCP, Backbone, Local, RNode, and BLE configs;
|
||||
`TcpInterfaceState`.
|
||||
- **rns-identity and rns-crypto:** `IdentityError`, `DestinationError`,
|
||||
`HkdfError`.
|
||||
- **rns-identity and rns-crypto:** `IdentityError`, `HkdfError`.
|
||||
|
||||
## Behaviour and configuration an operator sees
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"packages": [
|
||||
{
|
||||
"name": "rns-crypto",
|
||||
"version": "1.5.0",
|
||||
"version": "1.5.1",
|
||||
"rustVersion": "1.89",
|
||||
"edition": "2024",
|
||||
"features": {
|
||||
@@ -176,7 +176,7 @@
|
||||
},
|
||||
{
|
||||
"name": "rns-git",
|
||||
"version": "1.5.0",
|
||||
"version": "1.5.1",
|
||||
"rustVersion": "1.89",
|
||||
"edition": "2024",
|
||||
"features": {},
|
||||
@@ -258,7 +258,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
@@ -269,7 +269,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
@@ -291,7 +291,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
@@ -302,7 +302,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
@@ -360,7 +360,7 @@
|
||||
},
|
||||
{
|
||||
"name": "rns-identity",
|
||||
"version": "1.5.0",
|
||||
"version": "1.5.1",
|
||||
"rustVersion": "1.89",
|
||||
"edition": "2024",
|
||||
"features": {},
|
||||
@@ -426,7 +426,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
@@ -439,7 +439,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
@@ -545,7 +545,7 @@
|
||||
},
|
||||
{
|
||||
"name": "rns-interface",
|
||||
"version": "1.5.0",
|
||||
"version": "1.5.1",
|
||||
"rustVersion": "1.89",
|
||||
"edition": "2024",
|
||||
"features": {
|
||||
@@ -661,7 +661,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
@@ -674,7 +674,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
@@ -685,7 +685,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
@@ -696,7 +696,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
@@ -803,7 +803,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": "cfg(any(target_os = \"ios\", target_os = \"macos\"))",
|
||||
"requirement": "^0.5",
|
||||
"requirement": "^0.6",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
@@ -814,12 +814,14 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": "cfg(any(target_os = \"ios\", target_os = \"macos\"))",
|
||||
"requirement": "^0.2",
|
||||
"requirement": "^0.3",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
"CBAdvertisementData",
|
||||
"CBCentralManagerConstants"
|
||||
"CBCentralManagerConstants",
|
||||
"CBPeripheralManagerConstants",
|
||||
"std"
|
||||
],
|
||||
"sourceKind": "registry"
|
||||
},
|
||||
@@ -828,11 +830,12 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": "cfg(any(target_os = \"ios\", target_os = \"macos\"))",
|
||||
"requirement": "^0.2",
|
||||
"requirement": "^0.3",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
"NSString"
|
||||
"NSString",
|
||||
"std"
|
||||
],
|
||||
"sourceKind": "registry"
|
||||
},
|
||||
@@ -905,7 +908,7 @@
|
||||
},
|
||||
{
|
||||
"name": "rns-link",
|
||||
"version": "1.5.0",
|
||||
"version": "1.5.1",
|
||||
"rustVersion": "1.89",
|
||||
"edition": "2024",
|
||||
"features": {
|
||||
@@ -968,7 +971,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [],
|
||||
@@ -979,7 +982,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
@@ -990,7 +993,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [],
|
||||
@@ -1059,7 +1062,7 @@
|
||||
},
|
||||
{
|
||||
"name": "rns-protocol",
|
||||
"version": "1.5.0",
|
||||
"version": "1.5.1",
|
||||
"rustVersion": "1.89",
|
||||
"edition": "2024",
|
||||
"features": {},
|
||||
@@ -1125,7 +1128,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
@@ -1138,7 +1141,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
@@ -1149,7 +1152,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
@@ -1209,7 +1212,7 @@
|
||||
},
|
||||
{
|
||||
"name": "rns-ratkey",
|
||||
"version": "1.5.0",
|
||||
"version": "1.5.1",
|
||||
"rustVersion": "1.89",
|
||||
"edition": "2024",
|
||||
"features": {
|
||||
@@ -1326,7 +1329,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
@@ -1339,7 +1342,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
@@ -1445,7 +1448,7 @@
|
||||
},
|
||||
{
|
||||
"name": "rns-runtime",
|
||||
"version": "1.5.0",
|
||||
"version": "1.5.1",
|
||||
"rustVersion": "1.89",
|
||||
"edition": "2024",
|
||||
"features": {
|
||||
@@ -1560,7 +1563,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
@@ -1573,7 +1576,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
@@ -1584,7 +1587,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
@@ -1595,7 +1598,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
@@ -1606,7 +1609,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
@@ -1617,7 +1620,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
@@ -1628,7 +1631,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
@@ -1734,7 +1737,7 @@
|
||||
},
|
||||
{
|
||||
"name": "rns-tools",
|
||||
"version": "1.5.0",
|
||||
"version": "1.5.1",
|
||||
"rustVersion": "1.89",
|
||||
"edition": "2024",
|
||||
"features": {
|
||||
@@ -1851,7 +1854,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
@@ -1864,7 +1867,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
@@ -1875,7 +1878,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [
|
||||
@@ -1888,7 +1891,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": true,
|
||||
"defaultFeatures": true,
|
||||
"features": [
|
||||
@@ -1901,7 +1904,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [
|
||||
@@ -1914,7 +1917,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
@@ -1925,7 +1928,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
@@ -2055,7 +2058,7 @@
|
||||
},
|
||||
{
|
||||
"name": "rns-transport",
|
||||
"version": "1.5.0",
|
||||
"version": "1.5.1",
|
||||
"rustVersion": "1.89",
|
||||
"edition": "2024",
|
||||
"features": {
|
||||
@@ -2140,7 +2143,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
@@ -2153,7 +2156,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
@@ -2164,7 +2167,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
@@ -2248,7 +2251,7 @@
|
||||
},
|
||||
{
|
||||
"name": "rns-wire",
|
||||
"version": "1.5.0",
|
||||
"version": "1.5.1",
|
||||
"rustVersion": "1.89",
|
||||
"edition": "2024",
|
||||
"features": {
|
||||
@@ -2277,7 +2280,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "~1.5.0",
|
||||
"requirement": "~1.5.1",
|
||||
"optional": false,
|
||||
"defaultFeatures": false,
|
||||
"features": [],
|
||||
|
||||
@@ -283,7 +283,9 @@ impl rns_git::pages::PageNode
|
||||
pub fn rns_git::pages::PageNode::handle(&self, &rns_git::pages::PageRequest<'_>) -> rns_git::pages::PageReply
|
||||
pub fn rns_git::pages::PageNode::new(alloc::sync::Arc<std::sync::poison::rwlock::RwLock<rns_git::server::layout::Repositories>>, alloc::sync::Arc<rns_git::server::stats::Stats>, alloc::string::String, [u8; 16], &std::path::Path, rns_git::pages::PageOptions) -> Self
|
||||
pub struct rns_git::pages::PageOptions
|
||||
pub rns_git::pages::PageOptions::link_cost: f64
|
||||
pub rns_git::pages::PageOptions::media_conversion: bool
|
||||
pub rns_git::pages::PageOptions::stamp_value: core::option::Option<f64>
|
||||
pub rns_git::pages::PageOptions::use_nerdfonts: bool
|
||||
impl rns_git::pages::PageOptions
|
||||
pub fn rns_git::pages::PageOptions::from_config_text(&str) -> core::result::Result<Self, rns_runtime::config::ConfigError>
|
||||
@@ -406,12 +408,14 @@ pub rns_git::server::config::NodeConfig::aliases: alloc::collections::btree::map
|
||||
pub rns_git::server::config::NodeConfig::announce_interval: i64
|
||||
pub rns_git::server::config::NodeConfig::blocked_identities: alloc::vec::Vec<alloc::vec::Vec<u8>>
|
||||
pub rns_git::server::config::NodeConfig::fetch_limits: rns_git::server::config::FetchLimits
|
||||
pub rns_git::server::config::NodeConfig::link_cost: f64
|
||||
pub rns_git::server::config::NodeConfig::loglevel: core::option::Option<i64>
|
||||
pub rns_git::server::config::NodeConfig::mirror_interval: i64
|
||||
pub rns_git::server::config::NodeConfig::node_name: alloc::string::String
|
||||
pub rns_git::server::config::NodeConfig::record_stats: bool
|
||||
pub rns_git::server::config::NodeConfig::repositories: alloc::collections::btree::map::BTreeMap<alloc::string::String, alloc::string::String>
|
||||
pub rns_git::server::config::NodeConfig::serve_nomadnet: bool
|
||||
pub rns_git::server::config::NodeConfig::stamp_value: core::option::Option<f64>
|
||||
pub rns_git::server::config::NodeConfig::stats_ignored: alloc::vec::Vec<alloc::vec::Vec<u8>>
|
||||
pub rns_git::server::config::NodeConfig::stats_push_ignored: alloc::vec::Vec<alloc::vec::Vec<u8>>
|
||||
impl rns_git::server::config::NodeConfig
|
||||
@@ -419,6 +423,7 @@ pub fn rns_git::server::config::NodeConfig::parse(&str, i64) -> core::result::Re
|
||||
impl core::default::Default for rns_git::server::config::NodeConfig
|
||||
pub fn rns_git::server::config::NodeConfig::default() -> Self
|
||||
pub const rns_git::server::config::DEFAULT_CONFIG: &str
|
||||
pub const rns_git::server::config::DEFAULT_LINK_COST: f64
|
||||
pub const rns_git::server::config::DEFAULT_NODE_NAME: &str
|
||||
pub fn rns_git::server::config::expand_user(&str) -> std::path::PathBuf
|
||||
pub fn rns_git::server::config::load_or_create_identity(&std::path::Path) -> core::result::Result<rns_identity::identity::Identity, rns_identity::identity::IdentityError>
|
||||
|
||||
@@ -84,7 +84,8 @@ pub rns_identity::destination::DestType::Group = 1
|
||||
pub rns_identity::destination::DestType::Link = 3
|
||||
pub rns_identity::destination::DestType::Plain = 2
|
||||
pub rns_identity::destination::DestType::Single = 0
|
||||
pub enum rns_identity::destination::DestinationError
|
||||
#[non_exhaustive] pub enum rns_identity::destination::DestinationError
|
||||
pub rns_identity::destination::DestinationError::AnnounceTooLarge(usize)
|
||||
pub rns_identity::destination::DestinationError::DecryptionFailed
|
||||
pub rns_identity::destination::DestinationError::EncryptionUnavailable
|
||||
pub rns_identity::destination::DestinationError::Identity(rns_identity::identity::IdentityError)
|
||||
@@ -485,15 +486,28 @@ pub struct rns_identity::stamps::StampTarget(_)
|
||||
impl rns_identity::stamps::StampTarget
|
||||
pub fn rns_identity::stamps::StampTarget::accepts(&self, &[u8; 32]) -> bool
|
||||
pub fn rns_identity::stamps::StampTarget::to_be_bytes(&self) -> [u8; 33]
|
||||
pub struct rns_identity::stamps::StampWorkers
|
||||
pub rns_identity::stamps::StampWorkers::max_workers: core::option::Option<core::num::nonzero::NonZeroUsize>
|
||||
pub rns_identity::stamps::StampWorkers::niceness: u8
|
||||
impl rns_identity::stamps::StampWorkers
|
||||
pub fn rns_identity::stamps::StampWorkers::cap(&self, core::num::nonzero::NonZeroUsize) -> core::num::nonzero::NonZeroUsize
|
||||
pub fn rns_identity::stamps::StampWorkers::clamp_max_workers(i64) -> core::num::nonzero::NonZeroUsize
|
||||
pub fn rns_identity::stamps::StampWorkers::clamp_niceness(i64) -> u8
|
||||
pub fn rns_identity::stamps::StampWorkers::current() -> Self
|
||||
pub fn rns_identity::stamps::StampWorkers::install(self)
|
||||
impl core::default::Default for rns_identity::stamps::StampWorkers
|
||||
pub fn rns_identity::stamps::StampWorkers::default() -> Self
|
||||
pub struct rns_identity::stamps::StampedKey
|
||||
pub rns_identity::stamps::StampedKey::private: rns_crypto::x25519::X25519PrivateKey
|
||||
pub rns_identity::stamps::StampedKey::public: [u8; 32]
|
||||
pub rns_identity::stamps::StampedKey::value: f64
|
||||
pub const rns_identity::stamps::COST_FP: u32
|
||||
pub const rns_identity::stamps::COST_FP_BITS: u32
|
||||
pub const rns_identity::stamps::DEFAULT_WORKER_NICENESS: u8
|
||||
pub const rns_identity::stamps::LINK_COST_CAP: f64
|
||||
pub const rns_identity::stamps::MANTISSA_BITS: u32
|
||||
pub const rns_identity::stamps::MAX_VALUE_FP: u32
|
||||
pub const rns_identity::stamps::MAX_WORKER_NICENESS: u8
|
||||
pub const rns_identity::stamps::NETWORK_STAMP_SIZE: usize
|
||||
pub const rns_identity::stamps::PRM_DIGEST: &str
|
||||
pub const rns_identity::stamps::STAMP_COST_CAP: f64
|
||||
|
||||
@@ -148,6 +148,7 @@ pub fn rns_interface::backbone::BackboneClientConfig::python_name(&self) -> allo
|
||||
pub struct rns_interface::backbone::BackboneServerConfig
|
||||
pub rns_interface::backbone::BackboneServerConfig::bitrate: u64
|
||||
pub rns_interface::backbone::BackboneServerConfig::block_fast_flapping: bool
|
||||
pub rns_interface::backbone::BackboneServerConfig::client_limit: u64
|
||||
pub rns_interface::backbone::BackboneServerConfig::device: core::option::Option<alloc::string::String>
|
||||
pub rns_interface::backbone::BackboneServerConfig::fast_flapping_block_time: core::time::Duration
|
||||
pub rns_interface::backbone::BackboneServerConfig::fast_flapping_grace: u64
|
||||
@@ -162,6 +163,7 @@ impl rns_interface::backbone::BackboneServerConfig
|
||||
pub fn rns_interface::backbone::BackboneServerConfig::new(&str, &str, u16) -> Self
|
||||
pub const rns_interface::backbone::BITRATE_GUESS: u64
|
||||
pub const rns_interface::backbone::BLOCK_FAST_FLAPPING: bool
|
||||
pub const rns_interface::backbone::CLIENT_LIMIT: u64
|
||||
pub const rns_interface::backbone::DP_EC_DEAD_TIME: f64
|
||||
pub const rns_interface::backbone::DP_EC_HIGH_WM: u64
|
||||
pub const rns_interface::backbone::DP_EC_INTERVAL: core::time::Duration
|
||||
@@ -181,6 +183,7 @@ pub const rns_interface::backbone::TCP_PROBE_AFTER: u32
|
||||
pub const rns_interface::backbone::TCP_PROBE_INTERVAL: u32
|
||||
pub const rns_interface::backbone::TCP_USER_TIMEOUT: u32
|
||||
pub const rns_interface::backbone::TX_HWM: u64
|
||||
pub fn rns_interface::backbone::set_blocked_ips(impl core::iter::traits::collect::IntoIterator<Item = core::net::ip_addr::IpAddr>) -> usize
|
||||
pub async fn rns_interface::backbone::spawn_backbone_client(rns_interface::backbone::BackboneClientConfig, rns_interface::traits::InterfaceId, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>
|
||||
pub async fn rns_interface::backbone::spawn_backbone_client_observed(rns_interface::backbone::BackboneClientConfig, rns_interface::traits::InterfaceId, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> core::result::Result<rns_interface::tcp::SpawnedClientInterface, rns_interface::traits::InterfaceError>
|
||||
pub async fn rns_interface::backbone::spawn_backbone_server(rns_interface::backbone::BackboneServerConfig, rns_interface::traits::InterfaceId, alloc::sync::Arc<core::sync::atomic::AtomicU64>, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, tokio::sync::mpsc::bounded::Sender<rns_interface::traits::InterfaceHandle>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>
|
||||
@@ -1399,8 +1402,6 @@ pub rns_interface::traits::InterfaceHandle::rxb: core::option::Option<alloc::syn
|
||||
pub rns_interface::traits::InterfaceHandle::tx: tokio::sync::mpsc::bounded::Sender<bytes::bytes::Bytes>
|
||||
pub rns_interface::traits::InterfaceHandle::txb: core::option::Option<alloc::sync::Arc<core::sync::atomic::AtomicU64>>
|
||||
pub struct rns_interface::traits::TunnelIdentity(pub alloc::sync::Arc<rns_identity::identity::Identity>)
|
||||
impl rns_interface::traits::TunnelIdentity
|
||||
pub fn rns_interface::traits::TunnelIdentity::synthesis(&self, &str) -> core::option::Option<bytes::bytes::Bytes>
|
||||
impl core::fmt::Debug for rns_interface::traits::TunnelIdentity
|
||||
pub fn rns_interface::traits::TunnelIdentity::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
pub const rns_interface::traits::AR_FREQ_DECAY: f64
|
||||
|
||||
@@ -345,7 +345,9 @@ pub fn rns_protocol::resource::LinkResource::progress(&self) -> f64
|
||||
pub fn rns_protocol::resource::LinkResource::receive_part(&mut self, alloc::vec::Vec<u8>) -> bool
|
||||
pub fn rns_protocol::resource::LinkResource::validate_proof(&mut self, &[u8]) -> bool
|
||||
pub struct rns_protocol::resource::MultiSegmentInbound
|
||||
pub rns_protocol::resource::MultiSegmentInbound::assembled: alloc::vec::Vec<u8>
|
||||
pub rns_protocol::resource::MultiSegmentInbound::assembled_segments: alloc::vec::Vec<core::option::Option<alloc::vec::Vec<u8>>>
|
||||
pub rns_protocol::resource::MultiSegmentInbound::assembled_through: usize
|
||||
pub rns_protocol::resource::MultiSegmentInbound::data_size: usize
|
||||
pub rns_protocol::resource::MultiSegmentInbound::metadata: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_protocol::resource::MultiSegmentInbound::original_hash: [u8; 32]
|
||||
@@ -362,6 +364,7 @@ pub fn rns_protocol::resource::MultiSegmentInbound::reassemble(&self) -> core::r
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::set_metadata(&mut self, alloc::vec::Vec<u8>)
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::set_segment(&mut self, usize, rns_protocol::resource::InboundResource)
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::set_segment_data(&mut self, usize, alloc::vec::Vec<u8>) -> core::result::Result<(), rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::take_reassembled(&mut self) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::with_size_bound(self, usize) -> Self
|
||||
pub struct rns_protocol::resource::MultiSegmentOutbound
|
||||
pub rns_protocol::resource::MultiSegmentOutbound::data_size: usize
|
||||
|
||||
@@ -266,12 +266,18 @@ impl<T> core::default::Default for rns_runtime::destination_stamper::Destination
|
||||
pub fn rns_runtime::destination_stamper::DestinationStamps<T>::default() -> Self
|
||||
impl<T> core::ops::drop::Drop for rns_runtime::destination_stamper::DestinationStamps<T>
|
||||
pub fn rns_runtime::destination_stamper::DestinationStamps<T>::drop(&mut self)
|
||||
pub struct rns_runtime::destination_stamper::PreparedStamp
|
||||
impl rns_runtime::destination_stamper::PreparedStamp
|
||||
pub async fn rns_runtime::destination_stamper::PreparedStamp::ready(self) -> core::option::Option<rns_runtime::destination_stamper::DestinationStamp>
|
||||
impl core::ops::drop::Drop for rns_runtime::destination_stamper::PreparedStamp
|
||||
pub fn rns_runtime::destination_stamper::PreparedStamp::drop(&mut self)
|
||||
pub struct rns_runtime::destination_stamper::StampOutcome
|
||||
pub rns_runtime::destination_stamper::StampOutcome::stamp: core::option::Option<rns_runtime::destination_stamper::DestinationStamp>
|
||||
pub async fn rns_runtime::destination_stamper::announce_packet(&mut rns_identity::destination::Destination, &rns_identity::identity::Identity, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>, bool, core::option::Option<&[u8]>) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_runtime::destination_stamper::configure(rns_transport::stamps::StampPolicy, core::option::Option<std::path::PathBuf>)
|
||||
pub fn rns_runtime::destination_stamper::load_stored_stamp(&mut rns_identity::destination::Destination, &rns_identity::identity::Identity)
|
||||
pub fn rns_runtime::destination_stamper::policy() -> rns_transport::stamps::StampPolicy
|
||||
pub fn rns_runtime::destination_stamper::prepare(&rns_identity::destination::Destination, &rns_identity::identity::Identity) -> core::option::Option<rns_runtime::destination_stamper::PreparedStamp>
|
||||
pub type rns_runtime::destination_stamper::DestinationStamp = ([u8; 14], f64)
|
||||
pub mod rns_runtime::interface_factory
|
||||
pub enum rns_runtime::interface_factory::InterfaceConfig
|
||||
@@ -327,6 +333,7 @@ pub rns_runtime::interface_factory::AutoInterfaceConfig::name: alloc::string::St
|
||||
pub struct rns_runtime::interface_factory::BackboneInterfaceConfig
|
||||
pub rns_runtime::interface_factory::BackboneInterfaceConfig::bitrate: u64
|
||||
pub rns_runtime::interface_factory::BackboneInterfaceConfig::block_fast_flapping: bool
|
||||
pub rns_runtime::interface_factory::BackboneInterfaceConfig::client_limit: u64
|
||||
pub rns_runtime::interface_factory::BackboneInterfaceConfig::connect_timeout: u64
|
||||
pub rns_runtime::interface_factory::BackboneInterfaceConfig::device: core::option::Option<alloc::string::String>
|
||||
pub rns_runtime::interface_factory::BackboneInterfaceConfig::fast_flapping_block_time: core::time::Duration
|
||||
@@ -376,6 +383,7 @@ pub rns_runtime::interface_factory::InterfacePostInit::bitrate: core::option::Op
|
||||
pub rns_runtime::interface_factory::InterfacePostInit::default_ifac_size: usize
|
||||
pub rns_runtime::interface_factory::InterfacePostInit::destination_cost: core::option::Option<f64>
|
||||
pub rns_runtime::interface_factory::InterfacePostInit::gravity: core::option::Option<i64>
|
||||
pub rns_runtime::interface_factory::InterfacePostInit::hop_limiter: core::option::Option<u8>
|
||||
pub rns_runtime::interface_factory::InterfacePostInit::ifac_network_name: core::option::Option<alloc::string::String>
|
||||
pub rns_runtime::interface_factory::InterfacePostInit::ifac_passphrase: core::option::Option<zeroize::Zeroizing<alloc::string::String>>
|
||||
pub rns_runtime::interface_factory::InterfacePostInit::ifac_size: core::option::Option<usize>
|
||||
@@ -384,6 +392,8 @@ pub rns_runtime::interface_factory::InterfacePostInit::ingress_overrides: rns_tr
|
||||
pub rns_runtime::interface_factory::InterfacePostInit::outgoing: bool
|
||||
pub rns_runtime::interface_factory::InterfacePostInit::pr_cost: core::option::Option<f64>
|
||||
pub rns_runtime::interface_factory::InterfacePostInit::recursive_prs: bool
|
||||
pub rns_runtime::interface_factory::InterfacePostInit::shared_medium: bool
|
||||
pub rns_runtime::interface_factory::InterfacePostInit::spawned_hop_limiter: bool
|
||||
impl rns_runtime::interface_factory::InterfacePostInit
|
||||
pub fn rns_runtime::interface_factory::InterfacePostInit::try_from_section(&rns_runtime::config::ConfigSection) -> core::result::Result<Self, rns_runtime::interface_factory::InterfaceFactoryError>
|
||||
pub fn rns_runtime::interface_factory::InterfacePostInit::with_default_ifac_size(self, usize) -> Self
|
||||
@@ -1637,6 +1647,7 @@ pub fn rns_runtime::reticulum::ReticulumHandle::startup_interface_failures(&self
|
||||
pub fn rns_runtime::reticulum::ReticulumHandle::startup_rnode_runtimes(&self) -> alloc::vec::Vec<rns_runtime::reticulum::StartupRNodeRuntime>
|
||||
pub async fn rns_runtime::reticulum::ReticulumHandle::subscribe_announces(&self, core::option::Option<alloc::string::String>, bool) -> core::result::Result<rns_runtime::reticulum::AnnounceSubscription, rns_runtime::reticulum::AnnounceSubscriptionError>
|
||||
pub async fn rns_runtime::reticulum::ReticulumHandle::subscribe_announces_with_capacity(&self, core::option::Option<alloc::string::String>, bool, usize) -> core::result::Result<rns_runtime::reticulum::AnnounceSubscription, rns_runtime::reticulum::AnnounceSubscriptionError>
|
||||
pub fn rns_runtime::reticulum::ReticulumHandle::subscribe_interface_detaches(&self) -> tokio::sync::broadcast::Receiver<rns_runtime::reticulum::InterfaceDetach>
|
||||
pub fn rns_runtime::reticulum::ReticulumHandle::transport_enabled(&self) -> bool
|
||||
pub async fn rns_runtime::reticulum::ReticulumHandle::unwants_all_destination_types(&self) -> bool
|
||||
pub async fn rns_runtime::reticulum::ReticulumHandle::unwants_all_destination_types_as(&self, &[u8], core::option::Option<&[u8]>) -> bool
|
||||
@@ -1845,6 +1856,11 @@ pub rns_runtime::reticulum::InitOptions::keep_starting_after_interface_failure:
|
||||
pub rns_runtime::reticulum::InitOptions::require_shared_instance: bool
|
||||
pub rns_runtime::reticulum::InitOptions::shared_instance_type: core::option::Option<rns_runtime::reticulum::SharedInstanceType>
|
||||
pub rns_runtime::reticulum::InitOptions::start_interfaces_concurrently: bool
|
||||
#[non_exhaustive] pub struct rns_runtime::reticulum::InterfaceDetach
|
||||
pub rns_runtime::reticulum::InterfaceDetach::interface_id: rns_transport::messages::InterfaceId
|
||||
pub rns_runtime::reticulum::InterfaceDetach::name: alloc::string::String
|
||||
pub rns_runtime::reticulum::InterfaceDetach::parent_id: core::option::Option<rns_transport::messages::InterfaceId>
|
||||
pub rns_runtime::reticulum::InterfaceDetach::reason: rns_transport::messages::DetachReason
|
||||
pub struct rns_runtime::reticulum::InterfaceStats
|
||||
pub rns_runtime::reticulum::InterfaceStats::interfaces: alloc::vec::Vec<rns_transport::messages::InterfaceStatRpcEntry>
|
||||
pub rns_runtime::reticulum::InterfaceStats::network_id: core::option::Option<[u8; 16]>
|
||||
@@ -1937,6 +1953,7 @@ pub rns_runtime::reticulum::ReticulumConfig::rpc_key: core::option::Option<alloc
|
||||
pub rns_runtime::reticulum::ReticulumConfig::share_instance: bool
|
||||
pub rns_runtime::reticulum::ReticulumConfig::shared_instance_port: u16
|
||||
pub rns_runtime::reticulum::ReticulumConfig::shared_instance_type: rns_runtime::reticulum::SharedInstanceType
|
||||
pub rns_runtime::reticulum::ReticulumConfig::stamp_workers: rns_identity::stamps::StampWorkers
|
||||
pub rns_runtime::reticulum::ReticulumConfig::stamps: rns_transport::stamps::StampPolicy
|
||||
pub rns_runtime::reticulum::ReticulumConfig::static_transport_identity: bool
|
||||
pub rns_runtime::reticulum::ReticulumConfig::use_implicit_proof: bool
|
||||
@@ -2009,6 +2026,7 @@ pub fn rns_runtime::reticulum::ReticulumHandle::startup_interface_failures(&self
|
||||
pub fn rns_runtime::reticulum::ReticulumHandle::startup_rnode_runtimes(&self) -> alloc::vec::Vec<rns_runtime::reticulum::StartupRNodeRuntime>
|
||||
pub async fn rns_runtime::reticulum::ReticulumHandle::subscribe_announces(&self, core::option::Option<alloc::string::String>, bool) -> core::result::Result<rns_runtime::reticulum::AnnounceSubscription, rns_runtime::reticulum::AnnounceSubscriptionError>
|
||||
pub async fn rns_runtime::reticulum::ReticulumHandle::subscribe_announces_with_capacity(&self, core::option::Option<alloc::string::String>, bool, usize) -> core::result::Result<rns_runtime::reticulum::AnnounceSubscription, rns_runtime::reticulum::AnnounceSubscriptionError>
|
||||
pub fn rns_runtime::reticulum::ReticulumHandle::subscribe_interface_detaches(&self) -> tokio::sync::broadcast::Receiver<rns_runtime::reticulum::InterfaceDetach>
|
||||
pub fn rns_runtime::reticulum::ReticulumHandle::transport_enabled(&self) -> bool
|
||||
pub async fn rns_runtime::reticulum::ReticulumHandle::unwants_all_destination_types(&self) -> bool
|
||||
pub async fn rns_runtime::reticulum::ReticulumHandle::unwants_all_destination_types_as(&self, &[u8], core::option::Option<&[u8]>) -> bool
|
||||
@@ -2061,6 +2079,7 @@ pub rns_runtime::reticulum::StartupRNodeRuntime::interface_id: rns_interface::tr
|
||||
pub rns_runtime::reticulum::StartupRNodeRuntime::observer: rns_runtime::reticulum::RNodeRuntimeObserver
|
||||
pub const rns_runtime::reticulum::BLACKHOLE_LINK_COST: f64
|
||||
pub const rns_runtime::reticulum::DEFAULT_ANNOUNCE_SUBSCRIPTION_CAPACITY: usize
|
||||
pub fn rns_runtime::reticulum::configure_destination_stamper(core::option::Option<&str>, &rns_runtime::reticulum::InitOptions) -> core::result::Result<(), rns_runtime::reticulum::ReticulumError>
|
||||
pub fn rns_runtime::reticulum::get_instance() -> core::option::Option<&'static rns_runtime::reticulum::ReticulumHandle>
|
||||
pub async fn rns_runtime::reticulum::init(core::option::Option<&str>, core::option::Option<std::path::PathBuf>, rns_runtime::lifecycle::ShutdownSignal, alloc::sync::Arc<core::sync::atomic::AtomicBool>) -> core::result::Result<rns_runtime::reticulum::ReticulumHandle, rns_runtime::reticulum::ReticulumError>
|
||||
pub async fn rns_runtime::reticulum::init_with_options(core::option::Option<&str>, core::option::Option<std::path::PathBuf>, rns_runtime::lifecycle::ShutdownSignal, alloc::sync::Arc<core::sync::atomic::AtomicBool>, rns_runtime::reticulum::InitOptions) -> core::result::Result<rns_runtime::reticulum::ReticulumHandle, rns_runtime::reticulum::ReticulumError>
|
||||
@@ -2301,6 +2320,7 @@ pub rns_runtime::rpc::RpcRequest::GetBlackholedIdentities
|
||||
pub rns_runtime::rpc::RpcRequest::GetFirstHopTimeout
|
||||
pub rns_runtime::rpc::RpcRequest::GetFirstHopTimeout::destination_hash: alloc::vec::Vec<u8>
|
||||
pub rns_runtime::rpc::RpcRequest::GetInterfaceStats
|
||||
pub rns_runtime::rpc::RpcRequest::GetKnownDestinations
|
||||
pub rns_runtime::rpc::RpcRequest::GetLinkCount
|
||||
pub rns_runtime::rpc::RpcRequest::GetLinkDistribution
|
||||
pub rns_runtime::rpc::RpcRequest::GetLowestInterfaceBitrate
|
||||
@@ -2356,6 +2376,8 @@ pub rns_runtime::rpc::RpcResponse::FloatResult(core::option::Option<f64>)
|
||||
pub rns_runtime::rpc::RpcResponse::HashResult(core::option::Option<alloc::vec::Vec<u8>>)
|
||||
pub rns_runtime::rpc::RpcResponse::IntResult(i64)
|
||||
pub rns_runtime::rpc::RpcResponse::InterfaceStats(alloc::vec::Vec<rns_transport::messages::InterfaceStatRpcEntry>)
|
||||
pub rns_runtime::rpc::RpcResponse::KnownDestinations(alloc::vec::Vec<rns_runtime::rpc::KnownDestinationEntry>)
|
||||
pub rns_runtime::rpc::RpcResponse::LinkDistribution(alloc::vec::Vec<rns_runtime::rpc::LinkDistributionEntry>)
|
||||
pub rns_runtime::rpc::RpcResponse::Ok
|
||||
pub rns_runtime::rpc::RpcResponse::OptBoolResult(core::option::Option<bool>)
|
||||
pub rns_runtime::rpc::RpcResponse::PathTable(alloc::vec::Vec<rns_runtime::rpc::PathTableEntry>)
|
||||
@@ -2371,14 +2393,38 @@ pub rns_runtime::rpc::InterfaceStatsTotals::rxb: u64
|
||||
pub rns_runtime::rpc::InterfaceStatsTotals::rxpps: u64
|
||||
pub rns_runtime::rpc::InterfaceStatsTotals::txb: u64
|
||||
pub rns_runtime::rpc::InterfaceStatsTotals::txpps: u64
|
||||
pub struct rns_runtime::rpc::KnownDestinationEntry
|
||||
pub rns_runtime::rpc::KnownDestinationEntry::app_data: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_runtime::rpc::KnownDestinationEntry::destination_hash: alloc::vec::Vec<u8>
|
||||
pub rns_runtime::rpc::KnownDestinationEntry::last_heard: f64
|
||||
pub rns_runtime::rpc::KnownDestinationEntry::lr_cost: core::option::Option<f64>
|
||||
pub rns_runtime::rpc::KnownDestinationEntry::packet_hash: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_runtime::rpc::KnownDestinationEntry::public_key: alloc::vec::Vec<u8>
|
||||
pub rns_runtime::rpc::KnownDestinationEntry::stamp: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_runtime::rpc::KnownDestinationEntry::stamp_value: f64
|
||||
pub rns_runtime::rpc::KnownDestinationEntry::used: f64
|
||||
impl rns_runtime::rpc::KnownDestinationEntry
|
||||
pub fn rns_runtime::rpc::KnownDestinationEntry::to_row(&self) -> core::option::Option<rns_transport::store::KnownDestinationRow>
|
||||
impl core::convert::From<&rns_transport::store::KnownDestinationRow> for rns_runtime::rpc::KnownDestinationEntry
|
||||
pub fn rns_runtime::rpc::KnownDestinationEntry::from(&rns_transport::store::KnownDestinationRow) -> Self
|
||||
pub struct rns_runtime::rpc::LinkDistributionEntry
|
||||
pub rns_runtime::rpc::LinkDistributionEntry::active: u64
|
||||
pub rns_runtime::rpc::LinkDistributionEntry::destination_hash: alloc::vec::Vec<u8>
|
||||
pub rns_runtime::rpc::LinkDistributionEntry::from_interfaces: alloc::vec::Vec<alloc::vec::Vec<u8>>
|
||||
pub rns_runtime::rpc::LinkDistributionEntry::pending: u64
|
||||
pub rns_runtime::rpc::LinkDistributionEntry::traffic: u64
|
||||
impl core::convert::From<&rns_transport::messages::LinkDistributionRpcEntry> for rns_runtime::rpc::LinkDistributionEntry
|
||||
pub fn rns_runtime::rpc::LinkDistributionEntry::from(&rns_transport::messages::LinkDistributionRpcEntry) -> Self
|
||||
pub struct rns_runtime::rpc::PathTableEntry
|
||||
pub rns_runtime::rpc::PathTableEntry::expires: f64
|
||||
pub rns_runtime::rpc::PathTableEntry::hash: alloc::vec::Vec<u8>
|
||||
pub rns_runtime::rpc::PathTableEntry::hops: u8
|
||||
pub rns_runtime::rpc::PathTableEntry::interface: alloc::string::String
|
||||
pub rns_runtime::rpc::PathTableEntry::interface_hash: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_runtime::rpc::PathTableEntry::lr_cost: core::option::Option<f64>
|
||||
pub rns_runtime::rpc::PathTableEntry::state: core::option::Option<u8>
|
||||
pub rns_runtime::rpc::PathTableEntry::timestamp: f64
|
||||
pub rns_runtime::rpc::PathTableEntry::used: f64
|
||||
pub rns_runtime::rpc::PathTableEntry::used: core::option::Option<f64>
|
||||
pub rns_runtime::rpc::PathTableEntry::value: core::option::Option<f64>
|
||||
pub rns_runtime::rpc::PathTableEntry::via: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub struct rns_runtime::rpc::RateTableEntry
|
||||
|
||||
@@ -54,6 +54,7 @@ pub rns_tools::rnx::CommandResult::stderr_len: core::option::Option<u64>
|
||||
pub rns_tools::rnx::CommandResult::stdout: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_tools::rnx::CommandResult::stdout_len: core::option::Option<u64>
|
||||
impl rns_tools::rnx::CommandResult
|
||||
pub fn rns_tools::rnx::CommandResult::into_msgpack_within(self, usize) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_tools::rnx::CommandResult::to_msgpack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_tools::rnx::CommandResult::to_value(&self) -> rmpv::Value
|
||||
pub struct rns_tools::rnx::Rendered
|
||||
@@ -127,6 +128,7 @@ pub const rns_tools::RETICULUM_COMPAT_VERSION: &str
|
||||
pub const rns_tools::RS_RETICULUM_VERSION: &str
|
||||
pub fn rns_tools::config_log_timestamps(&std::path::Path) -> bool
|
||||
pub async fn rns_tools::exit(&rns_runtime::reticulum::ReticulumHandle, i32) -> never
|
||||
pub async fn rns_tools::has_local_path(&rns_runtime::reticulum::ReticulumHandle, [u8; 16]) -> bool
|
||||
pub fn rns_tools::init_tracing<W>(rns_tools::LogLevel, bool, bool, W) where W: for<'a> tracing_subscriber::fmt::writer::MakeWriter<'a> + core::marker::Send + core::marker::Sync + 'static
|
||||
pub fn rns_tools::link_closed_text(core::option::Option<rns_link::link::CloseReason>) -> core::option::Option<&'static str>
|
||||
pub async fn rns_tools::medium_path_timeout(&rns_runtime::reticulum::ReticulumHandle) -> f64
|
||||
|
||||
@@ -17,6 +17,7 @@ pub async fn rns_transport::actor::PersistenceTrigger::request(&self) -> bool
|
||||
pub struct rns_transport::actor::RecentAnnounce
|
||||
pub rns_transport::actor::RecentAnnounce::app_data: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_transport::actor::RecentAnnounce::dest_hash: [u8; 16]
|
||||
pub rns_transport::actor::RecentAnnounce::emitted: core::option::Option<u64>
|
||||
pub rns_transport::actor::RecentAnnounce::facts_known: bool
|
||||
pub rns_transport::actor::RecentAnnounce::hops: u8
|
||||
pub rns_transport::actor::RecentAnnounce::is_path_response: bool
|
||||
@@ -83,6 +84,7 @@ pub rns_transport::background_egress::BackgroundRegistrationError::Duplicate
|
||||
pub struct rns_transport::background_egress::BackgroundAnnounceReceiver
|
||||
impl rns_transport::background_egress::BackgroundAnnounceReceiver
|
||||
pub fn rns_transport::background_egress::BackgroundAnnounceReceiver::has_offer(&self) -> bool
|
||||
pub async fn rns_transport::background_egress::BackgroundAnnounceReceiver::offered(&self)
|
||||
pub fn rns_transport::background_egress::BackgroundAnnounceReceiver::ordinary_is_empty(&self) -> bool
|
||||
pub fn rns_transport::background_egress::BackgroundAnnounceReceiver::register(&tokio::sync::mpsc::bounded::Sender<bytes::bytes::Bytes>) -> core::result::Result<Self, rns_transport::background_egress::BackgroundRegistrationError>
|
||||
pub fn rns_transport::background_egress::BackgroundAnnounceReceiver::retire_generation(&self)
|
||||
@@ -208,7 +210,9 @@ pub const rns_transport::constants::PATHFINDER_G: f64
|
||||
pub const rns_transport::constants::PATHFINDER_M: u8
|
||||
pub const rns_transport::constants::PATHFINDER_R: u8
|
||||
pub const rns_transport::constants::PATHFINDER_RW: f64
|
||||
pub const rns_transport::constants::PATH_POOL_UNUSED_TARGET: usize
|
||||
pub const rns_transport::constants::PATH_POOL_UNUSED_MAX: usize
|
||||
pub const rns_transport::constants::PATH_POOL_UNUSED_MIN: usize
|
||||
pub const rns_transport::constants::PATH_POOL_USED_TARGET: usize
|
||||
pub const rns_transport::constants::PATH_REQUEST_GATE_TIMEOUT: f64
|
||||
pub const rns_transport::constants::PATH_REQUEST_GRACE: f64
|
||||
pub const rns_transport::constants::PATH_REQUEST_MI: f64
|
||||
@@ -229,6 +233,7 @@ pub const rns_transport::constants::STARTUP_GRACE_PERIOD: f64
|
||||
pub const rns_transport::constants::STATE_SAVE_INTERVAL_SECS: f64
|
||||
pub const rns_transport::constants::TABLES_CULL_INTERVAL: f64
|
||||
pub const rns_transport::constants::TUNNEL_PATH_TIMEOUT: u64
|
||||
pub const rns_transport::constants::TUNNEL_RECONNECT_WINDOW: u64
|
||||
pub const rns_transport::constants::TUNNEL_TIMEOUT: u64
|
||||
pub const rns_transport::constants::UNUSED_DESTINATION_LINGER: f64
|
||||
pub const rns_transport::constants::UNUSED_PATH_LINGER: f64
|
||||
@@ -236,8 +241,10 @@ pub const rns_transport::constants::UNUSED_PATH_LINGER_LEAF: f64
|
||||
pub mod rns_transport::destination_filter
|
||||
pub struct rns_transport::destination_filter::FilterPolicy
|
||||
pub rns_transport::destination_filter::FilterPolicy::allowed_types: alloc::vec::Vec<alloc::string::String>
|
||||
pub rns_transport::destination_filter::FilterPolicy::flagged_types: alloc::vec::Vec<alloc::string::String>
|
||||
pub rns_transport::destination_filter::FilterPolicy::hop_limiter: u8
|
||||
pub rns_transport::destination_filter::FilterPolicy::ignored_types: alloc::vec::Vec<alloc::string::String>
|
||||
pub rns_transport::destination_filter::FilterPolicy::known_types: alloc::vec::Vec<alloc::string::String>
|
||||
pub rns_transport::destination_filter::FilterPolicy::required_only: bool
|
||||
impl rns_transport::destination_filter::FilterPolicy
|
||||
pub fn rns_transport::destination_filter::FilterPolicy::clamp_hop_limiter(i64) -> u8
|
||||
@@ -492,24 +499,29 @@ pub struct rns_transport::discovery::stamper::NullStamper
|
||||
impl rns_transport::discovery::stamper::DiscoveryStamper for rns_transport::discovery::stamper::NullStamper
|
||||
pub fn rns_transport::discovery::stamper::NullStamper::generate(&self, &[u8; 32], f64, &rns_identity::stamps::StampControl) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_transport::discovery::stamper::NullStamper::valid(&self, &[u8; 32], &[u8], f64) -> bool
|
||||
pub fn rns_transport::discovery::stamper::NullStamper::validate(&self, &[u8; 32], &[u8], f64) -> core::option::Option<f64>
|
||||
pub fn rns_transport::discovery::stamper::NullStamper::value(&self, &[u8; 32], &[u8]) -> f64
|
||||
pub struct rns_transport::discovery::stamper::RnsDiscoveryStamper
|
||||
impl rns_transport::discovery::stamper::DiscoveryStamper for rns_transport::discovery::stamper::RnsDiscoveryStamper
|
||||
pub fn rns_transport::discovery::stamper::RnsDiscoveryStamper::generate(&self, &[u8; 32], f64, &rns_identity::stamps::StampControl) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_transport::discovery::stamper::RnsDiscoveryStamper::valid(&self, &[u8; 32], &[u8], f64) -> bool
|
||||
pub fn rns_transport::discovery::stamper::RnsDiscoveryStamper::validate(&self, &[u8; 32], &[u8], f64) -> core::option::Option<f64>
|
||||
pub fn rns_transport::discovery::stamper::RnsDiscoveryStamper::value(&self, &[u8; 32], &[u8]) -> f64
|
||||
pub const rns_transport::discovery::stamper::POOLING_THRESHOLD_COST: f64
|
||||
pub trait rns_transport::discovery::stamper::DiscoveryStamper: core::marker::Send + core::marker::Sync
|
||||
pub fn rns_transport::discovery::stamper::DiscoveryStamper::generate(&self, &[u8; 32], f64, &rns_identity::stamps::StampControl) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_transport::discovery::stamper::DiscoveryStamper::valid(&self, &[u8; 32], &[u8], f64) -> bool
|
||||
pub fn rns_transport::discovery::stamper::DiscoveryStamper::validate(&self, &[u8; 32], &[u8], f64) -> core::option::Option<f64>
|
||||
pub fn rns_transport::discovery::stamper::DiscoveryStamper::value(&self, &[u8; 32], &[u8]) -> f64
|
||||
impl rns_transport::discovery::stamper::DiscoveryStamper for rns_transport::discovery::stamper::NullStamper
|
||||
pub fn rns_transport::discovery::stamper::NullStamper::generate(&self, &[u8; 32], f64, &rns_identity::stamps::StampControl) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_transport::discovery::stamper::NullStamper::valid(&self, &[u8; 32], &[u8], f64) -> bool
|
||||
pub fn rns_transport::discovery::stamper::NullStamper::validate(&self, &[u8; 32], &[u8], f64) -> core::option::Option<f64>
|
||||
pub fn rns_transport::discovery::stamper::NullStamper::value(&self, &[u8; 32], &[u8]) -> f64
|
||||
impl rns_transport::discovery::stamper::DiscoveryStamper for rns_transport::discovery::stamper::RnsDiscoveryStamper
|
||||
pub fn rns_transport::discovery::stamper::RnsDiscoveryStamper::generate(&self, &[u8; 32], f64, &rns_identity::stamps::StampControl) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_transport::discovery::stamper::RnsDiscoveryStamper::valid(&self, &[u8; 32], &[u8], f64) -> bool
|
||||
pub fn rns_transport::discovery::stamper::RnsDiscoveryStamper::validate(&self, &[u8; 32], &[u8], f64) -> core::option::Option<f64>
|
||||
pub fn rns_transport::discovery::stamper::RnsDiscoveryStamper::value(&self, &[u8; 32], &[u8]) -> f64
|
||||
pub mod rns_transport::discovery::storage
|
||||
pub enum rns_transport::discovery::storage::DiscoveryStatus
|
||||
@@ -672,6 +684,7 @@ pub struct rns_transport::discovery::NullStamper
|
||||
impl rns_transport::discovery::stamper::DiscoveryStamper for rns_transport::discovery::stamper::NullStamper
|
||||
pub fn rns_transport::discovery::stamper::NullStamper::generate(&self, &[u8; 32], f64, &rns_identity::stamps::StampControl) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_transport::discovery::stamper::NullStamper::valid(&self, &[u8; 32], &[u8], f64) -> bool
|
||||
pub fn rns_transport::discovery::stamper::NullStamper::validate(&self, &[u8; 32], &[u8], f64) -> core::option::Option<f64>
|
||||
pub fn rns_transport::discovery::stamper::NullStamper::value(&self, &[u8; 32], &[u8]) -> f64
|
||||
pub struct rns_transport::discovery::ReceiverConfig
|
||||
pub rns_transport::discovery::ReceiverConfig::decryptor: core::option::Option<alloc::sync::Arc<dyn rns_transport::discovery::receiver::DiscoveryDecryptor>>
|
||||
@@ -686,20 +699,24 @@ pub struct rns_transport::discovery::RnsDiscoveryStamper
|
||||
impl rns_transport::discovery::stamper::DiscoveryStamper for rns_transport::discovery::stamper::RnsDiscoveryStamper
|
||||
pub fn rns_transport::discovery::stamper::RnsDiscoveryStamper::generate(&self, &[u8; 32], f64, &rns_identity::stamps::StampControl) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_transport::discovery::stamper::RnsDiscoveryStamper::valid(&self, &[u8; 32], &[u8], f64) -> bool
|
||||
pub fn rns_transport::discovery::stamper::RnsDiscoveryStamper::validate(&self, &[u8; 32], &[u8], f64) -> core::option::Option<f64>
|
||||
pub fn rns_transport::discovery::stamper::RnsDiscoveryStamper::value(&self, &[u8; 32], &[u8]) -> f64
|
||||
pub trait rns_transport::discovery::DiscoveryDecryptor: core::marker::Send + core::marker::Sync
|
||||
pub fn rns_transport::discovery::DiscoveryDecryptor::decrypt(&self, &[u8]) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub trait rns_transport::discovery::DiscoveryStamper: core::marker::Send + core::marker::Sync
|
||||
pub fn rns_transport::discovery::DiscoveryStamper::generate(&self, &[u8; 32], f64, &rns_identity::stamps::StampControl) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_transport::discovery::DiscoveryStamper::valid(&self, &[u8; 32], &[u8], f64) -> bool
|
||||
pub fn rns_transport::discovery::DiscoveryStamper::validate(&self, &[u8; 32], &[u8], f64) -> core::option::Option<f64>
|
||||
pub fn rns_transport::discovery::DiscoveryStamper::value(&self, &[u8; 32], &[u8]) -> f64
|
||||
impl rns_transport::discovery::stamper::DiscoveryStamper for rns_transport::discovery::stamper::NullStamper
|
||||
pub fn rns_transport::discovery::stamper::NullStamper::generate(&self, &[u8; 32], f64, &rns_identity::stamps::StampControl) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_transport::discovery::stamper::NullStamper::valid(&self, &[u8; 32], &[u8], f64) -> bool
|
||||
pub fn rns_transport::discovery::stamper::NullStamper::validate(&self, &[u8; 32], &[u8], f64) -> core::option::Option<f64>
|
||||
pub fn rns_transport::discovery::stamper::NullStamper::value(&self, &[u8; 32], &[u8]) -> f64
|
||||
impl rns_transport::discovery::stamper::DiscoveryStamper for rns_transport::discovery::stamper::RnsDiscoveryStamper
|
||||
pub fn rns_transport::discovery::stamper::RnsDiscoveryStamper::generate(&self, &[u8; 32], f64, &rns_identity::stamps::StampControl) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_transport::discovery::stamper::RnsDiscoveryStamper::valid(&self, &[u8; 32], &[u8], f64) -> bool
|
||||
pub fn rns_transport::discovery::stamper::RnsDiscoveryStamper::validate(&self, &[u8; 32], &[u8], f64) -> core::option::Option<f64>
|
||||
pub fn rns_transport::discovery::stamper::RnsDiscoveryStamper::value(&self, &[u8; 32], &[u8]) -> f64
|
||||
pub fn rns_transport::discovery::apply_manifest(&mut rns_transport::blackhole::BlackholeTable, &[([u8; 16], rns_transport::discovery::blackhole_manifest::BlackholeManifestEntry)], f64) -> usize
|
||||
pub fn rns_transport::discovery::build_manifest(&rns_transport::blackhole::BlackholeTable, rns_wire::types::IdentityHash) -> core::result::Result<alloc::vec::Vec<u8>, rns_transport::discovery::blackhole_manifest::ManifestError>
|
||||
@@ -755,6 +772,12 @@ pub fn rns_transport::inbound_queues::InboundQueues::lengths(&self) -> rns_trans
|
||||
pub fn rns_transport::inbound_queues::InboundQueues::snapshot(&self) -> rns_transport::inbound_queues::InboundQueueSnapshot
|
||||
pub fn rns_transport::inbound_queues::traffic_class(&[u8], core::option::Option<(&[u8; 64], usize)>) -> rns_transport::inbound_queues::TrafficClass
|
||||
pub mod rns_transport::ingress
|
||||
pub enum rns_transport::ingress::HoldOutcome
|
||||
pub rns_transport::ingress::HoldOutcome::Held
|
||||
pub rns_transport::ingress::HoldOutcome::Refused
|
||||
pub rns_transport::ingress::HoldOutcome::Replaced
|
||||
impl rns_transport::ingress::HoldOutcome
|
||||
pub fn rns_transport::ingress::HoldOutcome::is_filtered(self) -> bool
|
||||
pub struct rns_transport::ingress::HeldAnnounce
|
||||
pub rns_transport::ingress::HeldAnnounce::destination_hash: [u8; 16]
|
||||
pub rns_transport::ingress::HeldAnnounce::hops: u8
|
||||
@@ -764,18 +787,22 @@ pub struct rns_transport::ingress::IngressController
|
||||
impl rns_transport::ingress::IngressController
|
||||
pub fn rns_transport::ingress::IngressController::age(&self) -> f64
|
||||
pub fn rns_transport::ingress::IngressController::announce_and_path_request_bytes(&self) -> (u64, u64, u64, u64)
|
||||
pub fn rns_transport::ingress::IngressController::announces_filtered(&self) -> u64
|
||||
pub fn rns_transport::ingress::IngressController::announces_received(&self) -> u64
|
||||
pub fn rns_transport::ingress::IngressController::announces_sent(&self) -> u64
|
||||
pub fn rns_transport::ingress::IngressController::burst_activated(&self) -> std::time::Instant
|
||||
pub fn rns_transport::ingress::IngressController::burst_freq(&self) -> f64
|
||||
pub fn rns_transport::ingress::IngressController::burst_freq_new(&self) -> f64
|
||||
pub fn rns_transport::ingress::IngressController::cull_and_release(&mut self, &[[u8; 16]]) -> core::option::Option<rns_transport::ingress::HeldAnnounce>
|
||||
pub fn rns_transport::ingress::IngressController::disabled() -> Self
|
||||
pub fn rns_transport::ingress::IngressController::ec_pr_freq(&self) -> f64
|
||||
pub fn rns_transport::ingress::IngressController::exempt_announce_limit(&mut self)
|
||||
pub fn rns_transport::ingress::IngressController::filtered_announce(&mut self)
|
||||
pub fn rns_transport::ingress::IngressController::held_announces(&self) -> impl core::iter::traits::iterator::Iterator<Item = &rns_transport::ingress::HeldAnnounce>
|
||||
pub fn rns_transport::ingress::IngressController::held_count(&self) -> usize
|
||||
pub fn rns_transport::ingress::IngressController::held_release_at(&self) -> std::time::Instant
|
||||
pub fn rns_transport::ingress::IngressController::held_release_interval(&self) -> f64
|
||||
pub fn rns_transport::ingress::IngressController::hold_announce(&mut self, rns_transport::ingress::HeldAnnounce)
|
||||
pub fn rns_transport::ingress::IngressController::hold_announce(&mut self, rns_transport::ingress::HeldAnnounce) -> rns_transport::ingress::HoldOutcome
|
||||
pub fn rns_transport::ingress::IngressController::incoming_announce_frequency(&mut self) -> f64
|
||||
pub fn rns_transport::ingress::IngressController::incoming_pr_frequency(&mut self) -> f64
|
||||
pub fn rns_transport::ingress::IngressController::is_announce_limit_exempt(&self) -> bool
|
||||
@@ -795,6 +822,7 @@ pub fn rns_transport::ingress::IngressController::received_announce(&mut self)
|
||||
pub fn rns_transport::ingress::IngressController::received_announce_bytes(&mut self, usize)
|
||||
pub fn rns_transport::ingress::IngressController::received_path_request(&mut self)
|
||||
pub fn rns_transport::ingress::IngressController::received_path_request_bytes(&mut self, usize)
|
||||
pub fn rns_transport::ingress::IngressController::release_due(&mut self) -> bool
|
||||
pub fn rns_transport::ingress::IngressController::sent_announce(&mut self)
|
||||
pub fn rns_transport::ingress::IngressController::sent_announce_bytes(&mut self, usize)
|
||||
pub fn rns_transport::ingress::IngressController::sent_path_request(&mut self)
|
||||
@@ -968,6 +996,9 @@ pub rns_transport::link_transit::LinkTransitError::InvalidSignalling(rns_wire::l
|
||||
pub rns_transport::link_transit::LinkTransitError::StaleInterface
|
||||
pub rns_transport::link_transit::LinkTransitError::UnsupportedTransitModeTransform
|
||||
pub mod rns_transport::messages
|
||||
#[non_exhaustive] pub enum rns_transport::messages::DetachReason
|
||||
pub rns_transport::messages::DetachReason::BlackholedTransport
|
||||
pub rns_transport::messages::DetachReason::InvalidSynthesis
|
||||
pub enum rns_transport::messages::InterfaceCapacityError
|
||||
pub rns_transport::messages::InterfaceCapacityError::Empty
|
||||
pub rns_transport::messages::InterfaceCapacityError::IfacExceedsWire
|
||||
@@ -978,6 +1009,10 @@ pub rns_transport::messages::InterfaceCapacityError::LinkCapacityUnavailable
|
||||
pub rns_transport::messages::InterfaceCapacityError::LinkCapacityUnavailable::clear_mtu: u32
|
||||
pub rns_transport::messages::InterfaceCapacityError::LinkCapacityUnavailable::interface_id: rns_transport::messages::InterfaceId
|
||||
pub rns_transport::messages::InterfaceCapacityError::LinkCapacityUnavailable::required: u32
|
||||
#[non_exhaustive] pub enum rns_transport::messages::InterfaceControl
|
||||
pub rns_transport::messages::InterfaceControl::Detach
|
||||
pub rns_transport::messages::InterfaceControl::Detach::interface_id: rns_transport::messages::InterfaceId
|
||||
pub rns_transport::messages::InterfaceControl::Detach::reason: rns_transport::messages::DetachReason
|
||||
pub enum rns_transport::messages::InterfaceRole
|
||||
pub rns_transport::messages::InterfaceRole::LocalClient
|
||||
pub rns_transport::messages::InterfaceRole::Normal
|
||||
@@ -1145,6 +1180,8 @@ pub rns_transport::messages::TransportMessage::SetBlackholeSources
|
||||
pub rns_transport::messages::TransportMessage::SetBlackholeSources::sources: alloc::vec::Vec<[u8; 16]>
|
||||
pub rns_transport::messages::TransportMessage::SetFilterPolicy
|
||||
pub rns_transport::messages::TransportMessage::SetFilterPolicy::policy: rns_transport::destination_filter::FilterPolicy
|
||||
pub rns_transport::messages::TransportMessage::SetInterfaceControl
|
||||
pub rns_transport::messages::TransportMessage::SetInterfaceControl::tx: tokio::sync::mpsc::unbounded::UnboundedSender<rns_transport::messages::InterfaceControl>
|
||||
pub rns_transport::messages::TransportMessage::SetLocalDestinationKey
|
||||
pub rns_transport::messages::TransportMessage::SetLocalDestinationKey::hash: [u8; 16]
|
||||
pub rns_transport::messages::TransportMessage::SetLocalDestinationKey::public_key: [u8; 64]
|
||||
@@ -1162,13 +1199,14 @@ pub rns_transport::messages::TransportMessage::SetTransportEnabled
|
||||
pub rns_transport::messages::TransportMessage::SetTransportEnabled::enabled: bool
|
||||
pub rns_transport::messages::TransportMessage::SetTransportIdentity
|
||||
pub rns_transport::messages::TransportMessage::SetTransportIdentity::identity_hash: [u8; 16]
|
||||
pub rns_transport::messages::TransportMessage::SetTunnelIdentity
|
||||
pub rns_transport::messages::TransportMessage::SetTunnelIdentity::identity: alloc::sync::Arc<rns_identity::identity::Identity>
|
||||
pub rns_transport::messages::TransportMessage::SharedConnectionLost
|
||||
pub rns_transport::messages::TransportMessage::SharedConnectionRestored
|
||||
pub rns_transport::messages::TransportMessage::SharedConnectionRestored::interface_id: rns_transport::messages::InterfaceId
|
||||
pub rns_transport::messages::TransportMessage::Shutdown
|
||||
pub rns_transport::messages::TransportMessage::SynthesizeTunnel
|
||||
pub rns_transport::messages::TransportMessage::SynthesizeTunnel::interface_id: rns_transport::messages::InterfaceId
|
||||
pub rns_transport::messages::TransportMessage::SynthesizeTunnel::raw_packet: bytes::bytes::Bytes
|
||||
pub rns_transport::messages::TransportMessage::Tick(rns_transport::messages::TimerTick)
|
||||
pub rns_transport::messages::TransportMessage::UnbindLinkEndpoint
|
||||
pub rns_transport::messages::TransportMessage::UnbindLinkEndpoint::link_id: [u8; 16]
|
||||
@@ -1205,7 +1243,9 @@ pub rns_transport::messages::TransportQuery::FirstHopTimeout::dest: [u8; 16]
|
||||
pub rns_transport::messages::TransportQuery::GetActiveLinkCount
|
||||
pub rns_transport::messages::TransportQuery::GetBlackholedIdentities
|
||||
pub rns_transport::messages::TransportQuery::GetInterfaceStats
|
||||
pub rns_transport::messages::TransportQuery::GetKnownDestinations
|
||||
pub rns_transport::messages::TransportQuery::GetLinkCount
|
||||
pub rns_transport::messages::TransportQuery::GetLinkDistribution
|
||||
pub rns_transport::messages::TransportQuery::GetNextHop
|
||||
pub rns_transport::messages::TransportQuery::GetNextHop::dest: [u8; 16]
|
||||
pub rns_transport::messages::TransportQuery::GetNextHopBitrate
|
||||
@@ -1236,6 +1276,9 @@ pub rns_transport::messages::TransportQuery::HopsTo
|
||||
pub rns_transport::messages::TransportQuery::HopsTo::dest: [u8; 16]
|
||||
pub rns_transport::messages::TransportQuery::IsBlackholed
|
||||
pub rns_transport::messages::TransportQuery::IsBlackholed::hash: [u8; 16]
|
||||
pub rns_transport::messages::TransportQuery::KnownDestinationsLoaded
|
||||
pub rns_transport::messages::TransportQuery::LoadKnownDestinations
|
||||
pub rns_transport::messages::TransportQuery::LoadKnownDestinations::rows: alloc::vec::Vec<rns_transport::store::KnownDestinationRow>
|
||||
pub rns_transport::messages::TransportQuery::PathIsUnresponsive
|
||||
pub rns_transport::messages::TransportQuery::PathIsUnresponsive::dest: [u8; 16]
|
||||
pub rns_transport::messages::TransportQuery::PurgeUnverifiedBlackholes
|
||||
@@ -1296,6 +1339,8 @@ pub rns_transport::messages::TransportQueryResponse::FloatResult(core::option::O
|
||||
pub rns_transport::messages::TransportQueryResponse::HashResult(core::option::Option<[u8; 16]>)
|
||||
pub rns_transport::messages::TransportQueryResponse::IntResult(i64)
|
||||
pub rns_transport::messages::TransportQueryResponse::InterfaceStats(alloc::vec::Vec<rns_transport::messages::InterfaceStatRpcEntry>)
|
||||
pub rns_transport::messages::TransportQueryResponse::KnownDestinations(alloc::vec::Vec<rns_transport::store::KnownDestinationRow>)
|
||||
pub rns_transport::messages::TransportQueryResponse::LinkDistribution(alloc::vec::Vec<rns_transport::messages::LinkDistributionRpcEntry>)
|
||||
pub rns_transport::messages::TransportQueryResponse::Ok
|
||||
pub rns_transport::messages::TransportQueryResponse::OptBoolResult(core::option::Option<bool>)
|
||||
pub rns_transport::messages::TransportQueryResponse::PathStateResult(rns_transport::constants::PathState)
|
||||
@@ -1308,6 +1353,7 @@ pub struct rns_transport::messages::AnnounceHandlerEvent
|
||||
pub rns_transport::messages::AnnounceHandlerEvent::announce_packet_hash: [u8; 32]
|
||||
pub rns_transport::messages::AnnounceHandlerEvent::app_data: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_transport::messages::AnnounceHandlerEvent::destination_hash: [u8; 16]
|
||||
pub rns_transport::messages::AnnounceHandlerEvent::emitted: u64
|
||||
pub rns_transport::messages::AnnounceHandlerEvent::hops: u8
|
||||
pub rns_transport::messages::AnnounceHandlerEvent::identity_hash: core::option::Option<[u8; 16]>
|
||||
pub rns_transport::messages::AnnounceHandlerEvent::is_path_response: bool
|
||||
@@ -1318,6 +1364,7 @@ pub struct rns_transport::messages::AnnounceHandlerId(_)
|
||||
#[non_exhaustive] pub struct rns_transport::messages::AnnounceRpcEntry
|
||||
pub rns_transport::messages::AnnounceRpcEntry::app_data: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_transport::messages::AnnounceRpcEntry::dest_hash: [u8; 16]
|
||||
pub rns_transport::messages::AnnounceRpcEntry::emitted: core::option::Option<u64>
|
||||
pub rns_transport::messages::AnnounceRpcEntry::facts_known: bool
|
||||
pub rns_transport::messages::AnnounceRpcEntry::hops: u8
|
||||
pub rns_transport::messages::AnnounceRpcEntry::is_path_response: bool
|
||||
@@ -1360,6 +1407,7 @@ pub rns_transport::messages::InterfaceEntry::bitrate: u64
|
||||
pub rns_transport::messages::InterfaceEntry::destination_cost: core::option::Option<f64>
|
||||
pub rns_transport::messages::InterfaceEntry::direction: rns_transport::constants::InterfaceDirection
|
||||
pub rns_transport::messages::InterfaceEntry::gravity: i64
|
||||
pub rns_transport::messages::InterfaceEntry::hop_limiter: core::option::Option<u8>
|
||||
pub rns_transport::messages::InterfaceEntry::ifac_key: core::option::Option<rns_identity::ifac::IfacKey>
|
||||
pub rns_transport::messages::InterfaceEntry::ifac_netname: core::option::Option<alloc::string::String>
|
||||
pub rns_transport::messages::InterfaceEntry::ifac_size: usize
|
||||
@@ -1380,6 +1428,7 @@ pub rns_transport::messages::InterfaceEntry::protocol_violations: u64
|
||||
pub rns_transport::messages::InterfaceEntry::recursive_prs: bool
|
||||
pub rns_transport::messages::InterfaceEntry::role: rns_transport::messages::InterfaceRole
|
||||
pub rns_transport::messages::InterfaceEntry::rxb: core::option::Option<alloc::sync::Arc<core::sync::atomic::AtomicU64>>
|
||||
pub rns_transport::messages::InterfaceEntry::shared_medium: bool
|
||||
pub rns_transport::messages::InterfaceEntry::tx: tokio::sync::mpsc::bounded::Sender<bytes::bytes::Bytes>
|
||||
pub rns_transport::messages::InterfaceEntry::tx_dropped_bytes: u64
|
||||
pub rns_transport::messages::InterfaceEntry::tx_drops: alloc::sync::Arc<core::sync::atomic::AtomicU64>
|
||||
@@ -1389,6 +1438,7 @@ pub fn rns_transport::messages::InterfaceEntry::accepts_clear_packet(&self, usiz
|
||||
pub fn rns_transport::messages::InterfaceEntry::active_ifac_bytes(&self) -> usize
|
||||
pub fn rns_transport::messages::InterfaceEntry::effective_clear_mtu(&self) -> core::result::Result<u32, rns_transport::interface_ownership::InterfaceCapacityError>
|
||||
pub fn rns_transport::messages::InterfaceEntry::new(alloc::string::String, rns_transport::constants::InterfaceMode, rns_transport::constants::InterfaceDirection, u64, u32, tokio::sync::mpsc::bounded::Sender<bytes::bytes::Bytes>) -> Self
|
||||
pub fn rns_transport::messages::InterfaceEntry::tunnels_allowed(&self) -> bool
|
||||
pub fn rns_transport::messages::InterfaceEntry::with_announce_rate(self, f64, u32, f64) -> Self
|
||||
pub fn rns_transport::messages::InterfaceEntry::with_counters(self, alloc::sync::Arc<core::sync::atomic::AtomicBool>, alloc::sync::Arc<core::sync::atomic::AtomicU64>, alloc::sync::Arc<core::sync::atomic::AtomicU64>) -> Self
|
||||
pub fn rns_transport::messages::InterfaceEntry::with_ifac(self, [u8; 64], usize) -> Self
|
||||
@@ -1396,6 +1446,7 @@ pub fn rns_transport::messages::InterfaceEntry::with_multipoint(self, bool) -> S
|
||||
pub fn rns_transport::messages::InterfaceEntry::with_owner(self, rns_transport::interface_ownership::InterfaceOwner) -> Self
|
||||
pub fn rns_transport::messages::InterfaceEntry::with_packet_capacity(self, rns_transport::interface_ownership::InterfacePacketCapacity) -> Self
|
||||
pub fn rns_transport::messages::InterfaceEntry::with_role(self, rns_transport::messages::InterfaceRole) -> Self
|
||||
pub fn rns_transport::messages::InterfaceEntry::with_shared_medium(self, bool) -> Self
|
||||
impl core::fmt::Debug for rns_transport::messages::InterfaceEntry
|
||||
pub fn rns_transport::messages::InterfaceEntry::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
pub struct rns_transport::messages::InterfaceIdentity
|
||||
@@ -1408,9 +1459,11 @@ pub fn rns_transport::messages::InterfaceIdentity::new(impl core::convert::Into<
|
||||
pub struct rns_transport::messages::InterfaceInspectionSnapshot
|
||||
pub rns_transport::messages::InterfaceInspectionSnapshot::active_clients: core::option::Option<u64>
|
||||
pub rns_transport::messages::InterfaceInspectionSnapshot::blocked_ips: core::option::Option<u64>
|
||||
pub rns_transport::messages::InterfaceInspectionSnapshot::connect_failures: u32
|
||||
pub rns_transport::messages::InterfaceInspectionSnapshot::i2p_b32: core::option::Option<alloc::string::String>
|
||||
pub rns_transport::messages::InterfaceInspectionSnapshot::i2p_connectable: core::option::Option<bool>
|
||||
pub rns_transport::messages::InterfaceInspectionSnapshot::i2p_tunnel_state: core::option::Option<u8>
|
||||
pub rns_transport::messages::InterfaceInspectionSnapshot::last_connect_error: core::option::Option<&'static str>
|
||||
pub rns_transport::messages::InterfaceInspectionSnapshot::peers: core::option::Option<u64>
|
||||
pub rns_transport::messages::InterfaceInspectionSnapshot::radio: alloc::vec::Vec<(&'static str, rns_transport::messages::InterfaceStatValue)>
|
||||
pub rns_transport::messages::InterfaceInspectionSnapshot::tx_buffered: u64
|
||||
@@ -1459,6 +1512,7 @@ pub rns_transport::messages::InterfaceStatRpcEntry::announce_rate_penalty: core:
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::announce_rate_target: core::option::Option<f64>
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::announce_rx_bytes: u64
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::announce_tx_bytes: u64
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::announces_filtered: u64
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::announces_received: u64
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::announces_sent: u64
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::announces_to_internal: core::option::Option<bool>
|
||||
@@ -1469,6 +1523,10 @@ pub rns_transport::messages::InterfaceStatRpcEntry::burst_activated: f64
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::burst_active: bool
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::burst_count: core::option::Option<u64>
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::clients: core::option::Option<u64>
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::connect_failures: u32
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::filtered_rx_bytes: u64
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::filtered_speeds: core::option::Option<[f64; 2]>
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::filtered_tx_bytes: u64
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::gravity: i64
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::held_announces: u64
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::i2p_b32: core::option::Option<alloc::string::String>
|
||||
@@ -1482,6 +1540,7 @@ pub rns_transport::messages::InterfaceStatRpcEntry::ifac_size: core::option::Opt
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::ifac_violations: u64
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::incoming_announce_frequency: f64
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::incoming_pr_frequency: f64
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::last_connect_error: core::option::Option<alloc::string::String>
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::mode: alloc::string::String
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::mtu: u32
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::name: alloc::string::String
|
||||
@@ -1501,6 +1560,8 @@ pub rns_transport::messages::InterfaceStatRpcEntry::pr_burst_active: bool
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::pr_burst_count: core::option::Option<u64>
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::protocol_violations: u64
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::radio: alloc::vec::Vec<(&'static str, rns_transport::messages::InterfaceStatValue)>
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::remote_transport: core::option::Option<rns_transport::tunnel::RemoteTransportInfo>
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::remote_transport_id: core::option::Option<[u8; 16]>
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::role: alloc::string::String
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::rssi: core::option::Option<f64>
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::rx_bytes: u64
|
||||
@@ -1508,6 +1569,7 @@ pub rns_transport::messages::InterfaceStatRpcEntry::rx_rate: u64
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::signal_quality: core::option::Option<f64>
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::snr: core::option::Option<f64>
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::speeds: core::option::Option<[f64; 6]>
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::tunnel_id: core::option::Option<[u8; 32]>
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::tx_buffered: u64
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::tx_bytes: u64
|
||||
pub rns_transport::messages::InterfaceStatRpcEntry::tx_dropped_bytes: u64
|
||||
@@ -1529,6 +1591,12 @@ pub fn rns_transport::interface_ownership::InterfaceTransportSender::owner(&self
|
||||
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::ready(&self) -> bool
|
||||
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::send(&self, rns_transport::messages::TransportMessage) -> core::result::Result<(), tokio::sync::mpsc::error::SendError<rns_transport::messages::TransportMessage>>
|
||||
pub fn rns_transport::interface_ownership::InterfaceTransportSender::try_send(&self, rns_transport::messages::TransportMessage) -> core::result::Result<(), tokio::sync::mpsc::error::TrySendError<rns_transport::messages::TransportMessage>>
|
||||
#[non_exhaustive] pub struct rns_transport::messages::LinkDistributionRpcEntry
|
||||
pub rns_transport::messages::LinkDistributionRpcEntry::active: u64
|
||||
pub rns_transport::messages::LinkDistributionRpcEntry::destination_hash: [u8; 16]
|
||||
pub rns_transport::messages::LinkDistributionRpcEntry::from_interfaces: alloc::vec::Vec<[u8; 32]>
|
||||
pub rns_transport::messages::LinkDistributionRpcEntry::pending: u64
|
||||
pub rns_transport::messages::LinkDistributionRpcEntry::traffic: u64
|
||||
pub struct rns_transport::messages::LinkEndpointBinding
|
||||
pub rns_transport::messages::LinkEndpointBinding::interface_id: rns_transport::messages::InterfaceId
|
||||
pub rns_transport::messages::LinkEndpointBinding::interface_owner: core::option::Option<rns_transport::interface_ownership::InterfaceOwnerId>
|
||||
@@ -1550,10 +1618,12 @@ pub rns_transport::messages::PathTableRpcEntry::expires: f64
|
||||
pub rns_transport::messages::PathTableRpcEntry::hash: [u8; 16]
|
||||
pub rns_transport::messages::PathTableRpcEntry::hops: u8
|
||||
pub rns_transport::messages::PathTableRpcEntry::interface: alloc::string::String
|
||||
pub rns_transport::messages::PathTableRpcEntry::interface_hash: [u8; 32]
|
||||
pub rns_transport::messages::PathTableRpcEntry::interface_id: rns_transport::messages::InterfaceId
|
||||
pub rns_transport::messages::PathTableRpcEntry::interface_mode: rns_transport::constants::InterfaceMode
|
||||
pub rns_transport::messages::PathTableRpcEntry::interface_role: rns_transport::messages::InterfaceRole
|
||||
pub rns_transport::messages::PathTableRpcEntry::lr_cost: core::option::Option<f64>
|
||||
pub rns_transport::messages::PathTableRpcEntry::state: rns_transport::constants::PathState
|
||||
pub rns_transport::messages::PathTableRpcEntry::timestamp: f64
|
||||
pub rns_transport::messages::PathTableRpcEntry::used: f64
|
||||
pub rns_transport::messages::PathTableRpcEntry::value: core::option::Option<f64>
|
||||
@@ -1594,6 +1664,7 @@ impl core::fmt::Debug for rns_transport::messages::TrackedReceiptRegistration
|
||||
pub fn rns_transport::messages::TrackedReceiptRegistration::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
#[non_exhaustive] pub struct rns_transport::messages::TrafficTotalsRpcEntry
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::active_link_count: u64
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::announce_filtered_packets: u64
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::announce_rx_packets: u64
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::announce_tx_packets: u64
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::arxb: u64
|
||||
@@ -1602,7 +1673,15 @@ pub rns_transport::messages::TrafficTotalsRpcEntry::arxs: f64
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::atxb: u64
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::atxf: f64
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::atxs: f64
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::frxb: u64
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::frxs: f64
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::ftxb: u64
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::ftxs: f64
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::link_count: u64
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::lrxb: u64
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::lrxs: f64
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::ltxb: u64
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::ltxs: f64
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::measured: bool
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::path_count: u64
|
||||
pub rns_transport::messages::TrafficTotalsRpcEntry::pr_rx_packets: u64
|
||||
@@ -1684,11 +1763,12 @@ pub fn rns_transport::path_table::PathEntry::add_random_blob(&mut self, [u8; 10]
|
||||
pub fn rns_transport::path_table::PathEntry::blobs_for_persist(&self) -> alloc::vec::Vec<[u8; 10]>
|
||||
pub fn rns_transport::path_table::PathEntry::has_random_blob(&self, &[u8; 10]) -> bool
|
||||
pub fn rns_transport::path_table::PathEntry::is_expired(&self) -> bool
|
||||
pub fn rns_transport::path_table::PathEntry::is_retained(&self) -> bool
|
||||
pub fn rns_transport::path_table::PathEntry::mark_used(&mut self)
|
||||
pub fn rns_transport::path_table::PathEntry::new(core::option::Option<[u8; 16]>, u8, rns_transport::messages::InterfaceId, rns_transport::constants::InterfaceMode) -> Self
|
||||
pub struct rns_transport::path_table::PathTable
|
||||
impl rns_transport::path_table::PathTable
|
||||
pub fn rns_transport::path_table::PathTable::cull(&mut self, f64, f64, bool, impl core::ops::function::Fn(rns_transport::messages::InterfaceId) -> core::option::Option<u64>) -> (usize, core::option::Option<usize>)
|
||||
pub fn rns_transport::path_table::PathTable::cull(&mut self, f64, f64, bool, u8, impl core::ops::function::Fn(rns_transport::messages::InterfaceId) -> core::option::Option<u64>) -> (usize, core::option::Option<(usize, usize)>)
|
||||
pub fn rns_transport::path_table::PathTable::cull_dead_interfaces(&mut self, &std::collections::hash::set::HashSet<rns_transport::messages::InterfaceId>) -> usize
|
||||
pub fn rns_transport::path_table::PathTable::cull_expired(&mut self) -> usize
|
||||
pub fn rns_transport::path_table::PathTable::cull_expired_batch(&mut self, usize) -> usize
|
||||
@@ -2060,11 +2140,37 @@ pub type rns_transport::store::DestHash = [u8; 16]
|
||||
pub type rns_transport::store::PacketHash = [u8; 32]
|
||||
pub type rns_transport::store::Ratchet = [u8; 32]
|
||||
pub mod rns_transport::tunnel
|
||||
#[non_exhaustive] pub enum rns_transport::tunnel::TunnelExtError
|
||||
pub rns_transport::tunnel::TunnelExtError::InvalidCost
|
||||
pub rns_transport::tunnel::TunnelExtError::InvalidImplementation
|
||||
pub rns_transport::tunnel::TunnelExtError::InvalidTransport
|
||||
pub rns_transport::tunnel::TunnelExtError::InvalidVersion
|
||||
pub rns_transport::tunnel::TunnelExtError::MissingKey(u8)
|
||||
pub rns_transport::tunnel::TunnelExtError::NotAMap
|
||||
pub rns_transport::tunnel::TunnelExtError::Undecodable
|
||||
#[non_exhaustive] pub struct rns_transport::tunnel::RemoteTransportInfo
|
||||
pub rns_transport::tunnel::RemoteTransportInfo::destination_cost: f64
|
||||
pub rns_transport::tunnel::RemoteTransportInfo::implementation: alloc::string::String
|
||||
pub rns_transport::tunnel::RemoteTransportInfo::pr_cost: f64
|
||||
pub rns_transport::tunnel::RemoteTransportInfo::transport: bool
|
||||
pub rns_transport::tunnel::RemoteTransportInfo::version: alloc::vec::Vec<u64>
|
||||
impl rns_transport::tunnel::RemoteTransportInfo
|
||||
pub fn rns_transport::tunnel::RemoteTransportInfo::decode(&[u8]) -> core::result::Result<Self, rns_transport::tunnel::TunnelExtError>
|
||||
pub fn rns_transport::tunnel::RemoteTransportInfo::new(alloc::string::String, alloc::vec::Vec<u64>, bool, f64, f64) -> Self
|
||||
pub struct rns_transport::tunnel::TunnelEntry
|
||||
pub rns_transport::tunnel::TunnelEntry::expires: f64
|
||||
pub rns_transport::tunnel::TunnelEntry::interface_id: core::option::Option<rns_transport::messages::InterfaceId>
|
||||
pub rns_transport::tunnel::TunnelEntry::tunnel_id: [u8; 32]
|
||||
pub rns_transport::tunnel::TunnelEntry::tunnel_paths: std::collections::hash::map::HashMap<[u8; 16], rns_transport::tunnel::TunnelPath>
|
||||
pub struct rns_transport::tunnel::TunnelExt
|
||||
pub rns_transport::tunnel::TunnelExt::destination_cost: f64
|
||||
pub rns_transport::tunnel::TunnelExt::implementation: alloc::string::String
|
||||
pub rns_transport::tunnel::TunnelExt::pr_cost: f64
|
||||
pub rns_transport::tunnel::TunnelExt::transport: bool
|
||||
pub rns_transport::tunnel::TunnelExt::version: alloc::string::String
|
||||
impl rns_transport::tunnel::TunnelExt
|
||||
pub fn rns_transport::tunnel::TunnelExt::encode(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_transport::tunnel::TunnelExt::local(bool, f64, f64) -> Self
|
||||
pub struct rns_transport::tunnel::TunnelPath
|
||||
pub rns_transport::tunnel::TunnelPath::expires: f64
|
||||
pub rns_transport::tunnel::TunnelPath::hops: u8
|
||||
@@ -2074,6 +2180,7 @@ pub rns_transport::tunnel::TunnelPath::random_blobs: alloc::vec::Vec<[u8; 10]>
|
||||
pub rns_transport::tunnel::TunnelPath::timestamp: f64
|
||||
pub rns_transport::tunnel::TunnelPath::used: f64
|
||||
pub struct rns_transport::tunnel::TunnelSynthesisData
|
||||
pub rns_transport::tunnel::TunnelSynthesisData::ext: alloc::vec::Vec<u8>
|
||||
pub rns_transport::tunnel::TunnelSynthesisData::interface_hash: [u8; 32]
|
||||
pub rns_transport::tunnel::TunnelSynthesisData::public_key: [u8; 64]
|
||||
pub rns_transport::tunnel::TunnelSynthesisData::random_hash: [u8; 16]
|
||||
@@ -2081,6 +2188,7 @@ pub rns_transport::tunnel::TunnelSynthesisData::signature: [u8; 64]
|
||||
impl rns_transport::tunnel::TunnelSynthesisData
|
||||
pub fn rns_transport::tunnel::TunnelSynthesisData::is_signed(&self) -> bool
|
||||
pub fn rns_transport::tunnel::TunnelSynthesisData::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_transport::tunnel::TunnelSynthesisData::transport_identity_hash(&self) -> [u8; 16]
|
||||
pub fn rns_transport::tunnel::TunnelSynthesisData::tunnel_id(&self) -> [u8; 32]
|
||||
pub fn rns_transport::tunnel::TunnelSynthesisData::unpack(&[u8]) -> core::option::Option<Self>
|
||||
pub struct rns_transport::tunnel::TunnelTable
|
||||
@@ -2091,6 +2199,7 @@ pub fn rns_transport::tunnel::TunnelTable::get(&self, &[u8; 32]) -> core::option
|
||||
pub fn rns_transport::tunnel::TunnelTable::get_mut(&mut self, &[u8; 32]) -> core::option::Option<&mut rns_transport::tunnel::TunnelEntry>
|
||||
pub fn rns_transport::tunnel::TunnelTable::get_mut_by_interface(&mut self, rns_transport::messages::InterfaceId) -> core::option::Option<&mut rns_transport::tunnel::TunnelEntry>
|
||||
pub fn rns_transport::tunnel::TunnelTable::insert(&mut self, rns_transport::tunnel::TunnelEntry)
|
||||
pub fn rns_transport::tunnel::TunnelTable::interface_tunnel(&self, rns_transport::messages::InterfaceId) -> core::option::Option<[u8; 32]>
|
||||
pub fn rns_transport::tunnel::TunnelTable::is_empty(&self) -> bool
|
||||
pub fn rns_transport::tunnel::TunnelTable::iter(&self) -> impl core::iter::traits::iterator::Iterator<Item = (&[u8; 32], &rns_transport::tunnel::TunnelEntry)>
|
||||
pub fn rns_transport::tunnel::TunnelTable::iter_mut(&mut self) -> impl core::iter::traits::iterator::Iterator<Item = (&[u8; 32], &mut rns_transport::tunnel::TunnelEntry)>
|
||||
@@ -2101,7 +2210,11 @@ pub fn rns_transport::tunnel::TunnelTable::tunnel_paths(&self) -> impl core::ite
|
||||
pub fn rns_transport::tunnel::TunnelTable::void_interface(&mut self, rns_transport::messages::InterfaceId) -> usize
|
||||
impl core::default::Default for rns_transport::tunnel::TunnelTable
|
||||
pub fn rns_transport::tunnel::TunnelTable::default() -> Self
|
||||
pub const rns_transport::tunnel::SYNTHESIS_LEGACY_LEN: usize
|
||||
pub const rns_transport::tunnel::SYNTHESIS_MAX_LEN: usize
|
||||
pub const rns_transport::tunnel::TUNNEL_INTERFACE_CLASSES: &[&str]
|
||||
pub fn rns_transport::tunnel::build_tunnel_synthesis_packet(&rns_identity::identity::Identity, [u8; 32]) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_transport::tunnel::build_tunnel_synthesis_packet_with_ext(&rns_identity::identity::Identity, [u8; 32], &rns_transport::tunnel::TunnelExt) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_transport::tunnel::handle_tunnel(&mut rns_transport::tunnel::TunnelTable, [u8; 32], rns_transport::messages::InterfaceId)
|
||||
pub fn rns_transport::tunnel::interface_hash(&str) -> [u8; 32]
|
||||
pub macro rns_transport::notice!
|
||||
|
||||
+19
-14
@@ -42,8 +42,8 @@
|
||||
"tier": "candidate-stable",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-identity.txt",
|
||||
"itemCount": 523,
|
||||
"sha256": "102a60eaeb149803b61e8d9c1edaac1a9e31be09f8ebeb69c54abad0a426ce67"
|
||||
"itemCount": 537,
|
||||
"sha256": "f525e1b3f59c1092454ad4e36bc8cd7a5294ed97a33707891780748fa21286c4"
|
||||
},
|
||||
{
|
||||
"name": "rns-transport",
|
||||
@@ -51,8 +51,8 @@
|
||||
"tier": "provisional",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-transport.txt",
|
||||
"itemCount": 2160,
|
||||
"sha256": "18a2a12e0f5ab6de901b7d439708e131e1756db23dafabd117153229067ca882"
|
||||
"itemCount": 2273,
|
||||
"sha256": "7894fdab76428a6fd8cd7097e60058409a6a593d8c4970c01c5d440e98613fa1"
|
||||
},
|
||||
{
|
||||
"name": "rns-link",
|
||||
@@ -69,8 +69,8 @@
|
||||
"tier": "candidate-stable",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-protocol.txt",
|
||||
"itemCount": 670,
|
||||
"sha256": "c597cd463ba4cc68357fee72f7a3926086473383cf52014a38235a8f462e7ddf"
|
||||
"itemCount": 673,
|
||||
"sha256": "cac91c8ac80f6706f0d2a4257da740f8188846ffc7da61a8ff2a8a293ad6dee3"
|
||||
},
|
||||
{
|
||||
"name": "rns-interface",
|
||||
@@ -78,8 +78,8 @@
|
||||
"tier": "candidate-stable",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-interface.txt",
|
||||
"itemCount": 1588,
|
||||
"sha256": "7826b034a8acc97cb587507c23427a01017028323b21949b46371bb36a3d1409"
|
||||
"itemCount": 1589,
|
||||
"sha256": "d62d9d2d0825bbc56ea00c440fabe45d056447f316cd78761c1001118a3fc23c"
|
||||
},
|
||||
{
|
||||
"name": "rns-runtime",
|
||||
@@ -87,8 +87,8 @@
|
||||
"tier": "provisional",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-runtime.txt",
|
||||
"itemCount": 2455,
|
||||
"sha256": "a524be641056e26ad32a59742a71efe64e4cdb79ab81191b50519595a5cbe524"
|
||||
"itemCount": 2501,
|
||||
"sha256": "485e4b02fd9c45b681c6b7d928d4d068aa50a3419b3a49175c144491bf22b63d"
|
||||
},
|
||||
{
|
||||
"name": "rns-tools",
|
||||
@@ -96,8 +96,8 @@
|
||||
"tier": "tool-internal",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-tools.txt",
|
||||
"itemCount": 135,
|
||||
"sha256": "b40d0f735ef75aafd36dbf51f0a11411cb0c01bffaf8cb3dda11fcf6d2f0d4e0"
|
||||
"itemCount": 137,
|
||||
"sha256": "064dd502544660e246ff7ffe49e11783bbc369213955c09b03af80819ffef88d"
|
||||
},
|
||||
{
|
||||
"name": "rns-git",
|
||||
@@ -105,8 +105,8 @@
|
||||
"tier": "tool-internal",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-git.txt",
|
||||
"itemCount": 600,
|
||||
"sha256": "3368d32f751194b716361dfa2b90b70c27f8a4d10a3b51892c7b40658b712eff"
|
||||
"itemCount": 605,
|
||||
"sha256": "b4bee5c983267ce1db8229af30fa2ceca00d0fccceb70fbdffc810524779b0e2"
|
||||
},
|
||||
{
|
||||
"name": "rns-ratkey",
|
||||
@@ -129,6 +129,7 @@
|
||||
"rns-identity": [
|
||||
"impl core::default::Default for rns_identity::ratchet::ReceivedRatchetStore",
|
||||
"impl rns_identity::ratchet::ReceivedRatchetStore",
|
||||
"pub enum rns_identity::destination::DestinationError",
|
||||
"pub fn rns_identity::ratchet::ReceivedRatchetStore::clean_expired(&mut self)",
|
||||
"pub fn rns_identity::ratchet::ReceivedRatchetStore::current_ratchet_id(&mut self, &[u8; 16]) -> core::option::Option<alloc::vec::Vec<u8>>",
|
||||
"pub fn rns_identity::ratchet::ReceivedRatchetStore::default() -> Self",
|
||||
@@ -248,6 +249,7 @@
|
||||
"pub fn rns_transport::discovery::stamper::NullStamper::valid(&self, &[u8; 32], &[u8], u8) -> bool",
|
||||
"pub fn rns_transport::discovery::stamper::NullStamper::value(&self, &[u8; 32], &[u8]) -> u8",
|
||||
"pub fn rns_transport::discovery::storage::classify(u64) -> rns_transport::discovery::storage::DiscoveryStatus",
|
||||
"pub fn rns_transport::ingress::IngressController::hold_announce(&mut self, rns_transport::ingress::HeldAnnounce)",
|
||||
"pub fn rns_transport::ingress::IngressController::incoming_announce_frequency(&self) -> f64",
|
||||
"pub fn rns_transport::ingress::IngressController::incoming_pr_frequency(&self) -> f64",
|
||||
"pub fn rns_transport::ingress::IngressController::outgoing_announce_frequency(&self) -> f64",
|
||||
@@ -405,6 +407,7 @@
|
||||
"pub rns_transport::link_table::LinkEntry::validated: bool",
|
||||
"pub rns_transport::messages::InterfaceStatRpcEntry::ifac_size: usize",
|
||||
"pub rns_transport::messages::TimerTick::timestamp: f64",
|
||||
"pub rns_transport::messages::TransportMessage::SynthesizeTunnel::raw_packet: bytes::bytes::Bytes",
|
||||
"pub rns_transport::persistence::LegacyPersistedAnnounceEntryV5::app_data: core::option::Option<alloc::vec::Vec<u8>>",
|
||||
"pub rns_transport::persistence::LegacyPersistedAnnounceEntryV5::destination_hash: alloc::vec::Vec<u8>",
|
||||
"pub rns_transport::persistence::LegacyPersistedAnnounceEntryV5::hops: u8",
|
||||
@@ -458,6 +461,7 @@
|
||||
"pub fn rns_protocol::resource::WindowState::grow(&mut self, usize)"
|
||||
],
|
||||
"rns-interface": [
|
||||
"impl rns_interface::traits::TunnelIdentity",
|
||||
"pub async fn rns_interface::auto::spawn_auto_interface(rns_interface::auto::AutoInterfaceConfig, rns_interface::traits::InterfaceId, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, alloc::sync::Arc<core::sync::atomic::AtomicBool>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>",
|
||||
"pub const rns_interface::backbone::CHILD_BITRATE_GUESS: u64",
|
||||
"pub const rns_interface::i2p::RECONNECT_WAIT_MAX: u64",
|
||||
@@ -465,6 +469,7 @@
|
||||
"pub const rns_interface::tcp::RECONNECT_WAIT_MAX: u64",
|
||||
"pub const rns_interface::traits::IC_BURST_MIN_SAMPLES: usize",
|
||||
"pub fn rns_interface::rnode::process_rnode_response(u8, &[u8], rns_interface::traits::InterfaceId, &mut core::option::Option<f32>, &mut core::option::Option<f32>) -> rns_interface::rnode::RNodeResponse",
|
||||
"pub fn rns_interface::traits::TunnelIdentity::synthesis(&self, &str) -> core::option::Option<bytes::bytes::Bytes>",
|
||||
"pub rns_interface::backbone::BackboneServerConfig::listen_ip: alloc::string::String",
|
||||
"pub rns_interface::ble_rnode::BleRNodeConfig::lt_alock: core::option::Option<f32>",
|
||||
"pub rns_interface::ble_rnode::BleRNodeConfig::st_alock: core::option::Option<f32>",
|
||||
|
||||
@@ -71,7 +71,7 @@ pub fn encrypt(plaintext: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
|
||||
let ciphertext =
|
||||
aes_cbc::encrypt(encryption_key, &iv, &padded).map_err(|_| TokenError::EncryptionFailed)?;
|
||||
|
||||
let mut signed_parts = Vec::with_capacity(16 + ciphertext.len());
|
||||
let mut signed_parts = Vec::with_capacity(16 + ciphertext.len() + 32);
|
||||
signed_parts.extend_from_slice(&iv);
|
||||
signed_parts.extend_from_slice(&ciphertext);
|
||||
|
||||
|
||||
@@ -125,11 +125,11 @@ fn abort(
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the path is known and its announce has reached this process.
|
||||
/// A shared-instance client's `has_path` reads the daemon's path table, so the
|
||||
/// identity can arrive just after the path shows up there.
|
||||
/// Whether this process's own path table has the path and its identity is
|
||||
/// known, as `RNS.Transport.has_path` in `client.py`. Known destinations loaded
|
||||
/// over RPC give the identity before any path of our own.
|
||||
async fn path_ready(handle: &ReticulumHandle, hash: [u8; 16]) -> bool {
|
||||
handle.has_path(hash).await.unwrap_or(false)
|
||||
rns_tools::has_local_path(handle, hash).await
|
||||
&& matches!(handle.recall_without_use(hash).await, Ok(Some(_)))
|
||||
}
|
||||
|
||||
@@ -149,7 +149,7 @@ async fn await_path(handle: &ReticulumHandle, hash: [u8; 16]) -> bool {
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
handle.has_path(hash).await.unwrap_or(false)
|
||||
rns_tools::has_local_path(handle, hash).await
|
||||
}
|
||||
|
||||
fn init_logging(configdir: &Path, rnsconfig: Option<&str>, level: Option<i64>) {
|
||||
|
||||
@@ -212,6 +212,8 @@ async fn start_page_node(
|
||||
Destination::hash_from_name_and_identity(rns_git::pages::APP_NAME, Some(&identity.hash));
|
||||
let options = DestinationRuntimeOptions {
|
||||
endpoint_dispatch: Some(handle.link_endpoint_dispatch_handle()),
|
||||
stamp_value: node.options.stamp_value.filter(|value| *value > 0.0),
|
||||
link_cost: Some(node.options.link_cost),
|
||||
..DestinationRuntimeOptions::default()
|
||||
};
|
||||
let registered = match handle
|
||||
@@ -1238,6 +1240,8 @@ async fn main() {
|
||||
|
||||
let options = DestinationRuntimeOptions {
|
||||
endpoint_dispatch: Some(handle.link_endpoint_dispatch_handle()),
|
||||
stamp_value: config.stamp_value.filter(|value| *value > 0.0),
|
||||
link_cost: Some(config.link_cost),
|
||||
..DestinationRuntimeOptions::default()
|
||||
};
|
||||
let page_identity = identity.clone();
|
||||
|
||||
@@ -111,10 +111,14 @@ const PLAIN_TEMPLATES: [&str; 12] = [
|
||||
];
|
||||
|
||||
/// The `[pages]` keys `NomadNetworkNode.__init__` reads (`pages.py`).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct PageOptions {
|
||||
pub use_nerdfonts: bool,
|
||||
pub media_conversion: bool,
|
||||
/// Quantized; applied to the node destination only when above 0.
|
||||
pub stamp_value: Option<f64>,
|
||||
/// Quantized announced link request cost.
|
||||
pub link_cost: f64,
|
||||
}
|
||||
|
||||
impl Default for PageOptions {
|
||||
@@ -122,13 +126,15 @@ impl Default for PageOptions {
|
||||
Self {
|
||||
use_nerdfonts: true,
|
||||
media_conversion: true,
|
||||
stamp_value: None,
|
||||
link_cost: crate::server::config::DEFAULT_LINK_COST,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PageOptions {
|
||||
/// Read `unicode_icons` and `media_conversion` from the node config text;
|
||||
/// a value `as_bool` rejects is an error, as upstream raises.
|
||||
/// Read the `[pages]` keys from the node config text; a value `as_bool`
|
||||
/// or `as_float` rejects is an error, as upstream raises.
|
||||
pub fn from_config_text(text: &str) -> Result<Self, rns_runtime::config::ConfigError> {
|
||||
let mut options = Self::default();
|
||||
let config = rns_runtime::config::Config::parse(text)?;
|
||||
@@ -150,6 +156,16 @@ impl PageOptions {
|
||||
if section.has("media_conversion") {
|
||||
options.media_conversion = as_bool("media_conversion")?;
|
||||
}
|
||||
if section.has("link_cost") {
|
||||
options.link_cost = crate::server::config::as_cost(section, "pages", "link_cost")?;
|
||||
}
|
||||
if section.has("stamp_value") {
|
||||
options.stamp_value = Some(crate::server::config::as_cost(
|
||||
section,
|
||||
"pages",
|
||||
"stamp_value",
|
||||
)?);
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
}
|
||||
@@ -798,3 +814,22 @@ pub(crate) fn field_num(value: &Value, key: &str) -> f64 {
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::PageOptions;
|
||||
|
||||
#[test]
|
||||
fn page_stamp_keys_follow_upstream() {
|
||||
let options = PageOptions::from_config_text("[pages]\nserve_nomadnet = yes\n").unwrap();
|
||||
assert_eq!((options.stamp_value, options.link_cost), (None, 18.0));
|
||||
let options =
|
||||
PageOptions::from_config_text("[pages]\nstamp_value = 27.5\nlink_cost = 18.7\n")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(options.stamp_value, options.link_cost),
|
||||
(Some(27.5), 4787.0 / 256.0)
|
||||
);
|
||||
assert!(PageOptions::from_config_text("[pages]\nlink_cost = x\n").is_err());
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,8 @@ use super::py_len;
|
||||
pub const DEFAULT_CONFIG: &str = include_str!("default_config.txt");
|
||||
|
||||
pub const DEFAULT_NODE_NAME: &str = "Anonymous Git Node";
|
||||
/// `DEFAULT_LINK_COST` of both rngit destinations (`server.py`, `pages.py`).
|
||||
pub const DEFAULT_LINK_COST: f64 = 18.0;
|
||||
const LOG_NONE: i64 = -1;
|
||||
const LOG_EXTREME: i64 = 8;
|
||||
|
||||
@@ -40,11 +42,16 @@ impl Default for FetchLimits {
|
||||
}
|
||||
|
||||
/// What `__apply_config` takes from the config file.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct NodeConfig {
|
||||
pub node_name: String,
|
||||
/// Seconds; 0 never announces.
|
||||
pub announce_interval: i64,
|
||||
/// `[rngit] stamp_value`, quantized; applied to the repositories
|
||||
/// destination only when above 0, as upstream tests it for truth.
|
||||
pub stamp_value: Option<f64>,
|
||||
/// `[rngit] link_cost`, quantized: the announced link request cost.
|
||||
pub link_cost: f64,
|
||||
/// Seconds; 0 disables periodic mirror sync.
|
||||
pub mirror_interval: i64,
|
||||
pub record_stats: bool,
|
||||
@@ -68,6 +75,8 @@ impl Default for NodeConfig {
|
||||
Self {
|
||||
node_name: DEFAULT_NODE_NAME.to_string(),
|
||||
announce_interval: 0,
|
||||
stamp_value: None,
|
||||
link_cost: DEFAULT_LINK_COST,
|
||||
mirror_interval: 24 * 60 * 60,
|
||||
record_stats: false,
|
||||
serve_nomadnet: false,
|
||||
@@ -107,6 +116,15 @@ fn as_limit(section: &ConfigSection, name: &str, key: &str) -> Result<u64, Confi
|
||||
Ok(value.max(1) as u64)
|
||||
}
|
||||
|
||||
/// `Stamps.quantize_cost(section.as_float(key))`, which raises on a value
|
||||
/// `float()` rejects and on NaN or infinity.
|
||||
pub(crate) fn as_cost(section: &ConfigSection, name: &str, key: &str) -> Result<f64, ConfigError> {
|
||||
let value = section
|
||||
.get_float(key)
|
||||
.ok_or_else(|| invalid(name, key, "not a float"))?;
|
||||
rns_identity::stamps::quantize_cost(value).map_err(|e| invalid(name, key, &e.to_string()))
|
||||
}
|
||||
|
||||
/// ConfigObj `as_bool`, which raises on anything but its boolean words.
|
||||
fn as_bool(section: &ConfigSection, name: &str, key: &str) -> Result<bool, ConfigError> {
|
||||
section
|
||||
@@ -154,6 +172,12 @@ impl NodeConfig {
|
||||
if section.has("announce_interval") {
|
||||
node.announce_interval = as_int(section, name, "announce_interval")? * 60;
|
||||
}
|
||||
if section.has("stamp_value") {
|
||||
node.stamp_value = Some(as_cost(section, name, "stamp_value")?);
|
||||
}
|
||||
if section.has("link_cost") {
|
||||
node.link_cost = as_cost(section, name, "link_cost")?;
|
||||
}
|
||||
if section.has("mirror_interval") {
|
||||
node.mirror_interval = (as_int(section, name, "mirror_interval")? * 3600).max(0);
|
||||
}
|
||||
@@ -271,3 +295,44 @@ pub fn expand_user(path: &str) -> PathBuf {
|
||||
_ => PathBuf::from(path),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn stamp_value_and_link_cost_follow_upstream() {
|
||||
let node = NodeConfig::parse("[rngit]\n", 0).unwrap();
|
||||
assert_eq!((node.stamp_value, node.link_cost), (None, 18.0));
|
||||
let node = NodeConfig::parse("[rngit]\nstamp_value = 27.5\nlink_cost = 18.7\n", 0).unwrap();
|
||||
// quantize_cost: 18.7 is 4787/256.
|
||||
assert_eq!(
|
||||
(node.stamp_value, node.link_cost),
|
||||
(Some(27.5), 4787.0 / 256.0)
|
||||
);
|
||||
let node = NodeConfig::parse("[rngit]\nstamp_value = -3\nlink_cost = 150\n", 0).unwrap();
|
||||
assert_eq!((node.stamp_value, node.link_cost), (Some(0.0), 100.0));
|
||||
for body in ["stamp_value = high", "link_cost = nan", "link_cost = inf"] {
|
||||
assert!(
|
||||
NodeConfig::parse(&format!("[rngit]\n{body}\n"), 0).is_err(),
|
||||
"{body}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_config_carries_the_upstream_stamp_lines() {
|
||||
// A Windows checkout embeds the template with CRLF line endings.
|
||||
let config = DEFAULT_CONFIG.replace("\r\n", "\n");
|
||||
for (section, destination) in [("[rngit]", "repository node"), ("[pages]", "page node")] {
|
||||
let start = config.find(section).unwrap();
|
||||
let text = &config[start..];
|
||||
assert!(text.contains(&format!(
|
||||
"# You can configure the required link stamp cost for\n# connecting to the {destination}.\n\n# link_cost = 18.0\n"
|
||||
)));
|
||||
}
|
||||
assert_eq!(config.matches("# stamp_value = 25.0\n").count(), 2);
|
||||
let node = NodeConfig::parse(DEFAULT_CONFIG, 0).unwrap();
|
||||
assert_eq!((node.stamp_value, node.link_cost), (None, 18.0));
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,16 @@ announce_interval = 360
|
||||
|
||||
# node_name = Anonymous Git Node
|
||||
|
||||
# You can configure the required link stamp cost for
|
||||
# connecting to the repository node.
|
||||
|
||||
# link_cost = 18.0
|
||||
|
||||
# The target stamp value for the repositories destination
|
||||
# can also be configured.
|
||||
|
||||
# stamp_value = 25.0
|
||||
|
||||
# You can enable collecting view, fetch and push statistics
|
||||
# which can be displayed on the stats pages of repositories.
|
||||
# Remember to set the "s" (stats) permission appropriately
|
||||
@@ -140,6 +150,16 @@ internal = rw:9710b86ba12c42d1d8f30f74fe509286
|
||||
|
||||
# serve_nomadnet = no
|
||||
|
||||
# You can configure the required link stamp cost for
|
||||
# connecting to the page node.
|
||||
|
||||
# link_cost = 18.0
|
||||
|
||||
# The target stamp value for the node destination can
|
||||
# also be configured.
|
||||
|
||||
# stamp_value = 25.0
|
||||
|
||||
# It is possible to disable Nerd Font icons and instead
|
||||
# use simpler (but more compatible) unicode icons.
|
||||
|
||||
|
||||
@@ -100,6 +100,7 @@ pub enum AllowPolicy {
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum DestinationError {
|
||||
#[error("SINGLE destination requires an identity")]
|
||||
MissingIdentity,
|
||||
@@ -133,6 +134,13 @@ pub enum DestinationError {
|
||||
SigningUnavailable,
|
||||
#[error("announce link cost is not a finite number: {0}")]
|
||||
InvalidLinkCost(f64),
|
||||
/// Packet.py: a HEADER_1 announce must leave room for the transport id a
|
||||
/// relay inserts. Carries the size with that id.
|
||||
#[error(
|
||||
"transport-inserted announce size of {0} bytes exceeds the MTU of {mtu} bytes",
|
||||
mtu = rns_wire::constants::MTU
|
||||
)]
|
||||
AnnounceTooLarge(usize),
|
||||
}
|
||||
|
||||
/// Wire-shape controls for [`Destination::pack_packet`].
|
||||
@@ -1157,7 +1165,7 @@ impl Destination {
|
||||
let (announce_data, has_ratchet) =
|
||||
self.create_announce_with_ext_at(identity, app_data, ratchet, tag, time, stamp_ext)?;
|
||||
|
||||
Ok(self.pack_announce_packet(&announce_data, has_ratchet, path_response))
|
||||
self.pack_announce_packet(&announce_data, has_ratchet, path_response)
|
||||
}
|
||||
|
||||
/// `Destination.stamp_material()`: hash, public key, name hash.
|
||||
@@ -1230,9 +1238,12 @@ impl Destination {
|
||||
|
||||
self.path_responses
|
||||
.retain(|_, cached| cache_now <= cached.timestamp + PR_TAG_WINDOW);
|
||||
Ok(self.path_responses.get(tag).map(|cached| {
|
||||
self.pack_announce_packet(&cached.announce_data, cached.has_ratchet, true)
|
||||
}))
|
||||
self.path_responses
|
||||
.get(tag)
|
||||
.map(|cached| {
|
||||
self.pack_announce_packet(&cached.announce_data, cached.has_ratchet, true)
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn pack_announce_packet(
|
||||
@@ -1240,7 +1251,7 @@ impl Destination {
|
||||
announce_data: &[u8],
|
||||
has_ratchet: bool,
|
||||
path_response: bool,
|
||||
) -> Vec<u8> {
|
||||
) -> Result<Vec<u8>, DestinationError> {
|
||||
let context = if path_response {
|
||||
rns_wire::context::PacketContext::PathResponse
|
||||
} else {
|
||||
@@ -1264,7 +1275,11 @@ impl Destination {
|
||||
|
||||
let mut raw = header.pack();
|
||||
raw.extend_from_slice(announce_data);
|
||||
raw
|
||||
let inserted = raw.len() + rns_wire::constants::TRUNCATED_HASHLENGTH / 8;
|
||||
if inserted > rns_wire::constants::MTU {
|
||||
return Err(DestinationError::AnnounceTooLarge(inserted));
|
||||
}
|
||||
Ok(raw)
|
||||
}
|
||||
|
||||
pub fn remove_link(&mut self, link_id: &[u8; 16]) {
|
||||
@@ -1927,6 +1942,41 @@ mod tests {
|
||||
assert!(dest.auto_identity().is_none());
|
||||
}
|
||||
|
||||
/// Upstream 1.6.1 `Packet.pack` packs a 484-byte HEADER_1 announce and
|
||||
/// refuses one byte more: 317 bytes of app data, 285 with a ratchet
|
||||
/// (`RNS.Packet(dest, data, ANNOUNCE).pack()` over app-data sizes).
|
||||
#[test]
|
||||
fn an_announce_leaves_room_for_a_transport_id() {
|
||||
let identity = Identity::new();
|
||||
let mut dest =
|
||||
Destination::new(Some(&identity), Direction::In, DestType::Single, "test.mtu").unwrap();
|
||||
for (ratchet, largest) in [(None, 317), (Some(&[0x5A; 32]), 285)] {
|
||||
let raw = dest
|
||||
.announce_packet(
|
||||
&identity,
|
||||
Some(&vec![7; largest]),
|
||||
ratchet,
|
||||
false,
|
||||
None,
|
||||
1.0,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(raw.len(), 484);
|
||||
let too_large = dest.announce_packet(
|
||||
&identity,
|
||||
Some(&vec![7; largest + 1]),
|
||||
ratchet,
|
||||
false,
|
||||
None,
|
||||
1.0,
|
||||
);
|
||||
assert!(matches!(
|
||||
too_large,
|
||||
Err(DestinationError::AnnounceTooLarge(501))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_path_response_preserves_ratcheted_announce_context() {
|
||||
let identity = Identity::new();
|
||||
|
||||
@@ -265,16 +265,9 @@ fn barrier_unsupported(error: &io::Error) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// On Apple targets `sync_all` is already `F_FULLFSYNC`.
|
||||
fn file_barrier(file: &File) -> io::Result<()> {
|
||||
supported_barrier(file.sync_all())?;
|
||||
#[cfg(any(target_os = "macos", target_os = "ios"))]
|
||||
{
|
||||
use std::os::fd::AsRawFd;
|
||||
if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_FULLFSYNC) } == -1 {
|
||||
supported_barrier(Err(io::Error::last_os_error()))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
supported_barrier(file.sync_all())
|
||||
}
|
||||
|
||||
fn parent_barrier(_path: &Path) -> io::Result<()> {
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
use std::num::NonZeroUsize;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
use rand::RngCore;
|
||||
@@ -471,6 +471,85 @@ pub fn stamp_valid_fp(stamp: &[u8], target_fp: u16, workblock: &[u8]) -> Result<
|
||||
Ok(target_from_fp(target_fp)?.accepts(&hash_with(workblock, stamp)))
|
||||
}
|
||||
|
||||
/// Python `Stamps.NICENESS`.
|
||||
pub const DEFAULT_WORKER_NICENESS: u8 = 16;
|
||||
/// Upper clamp of `[stamps] worker_niceness`.
|
||||
pub const MAX_WORKER_NICENESS: u8 = 20;
|
||||
|
||||
static MAX_WORKERS: AtomicUsize = AtomicUsize::new(0);
|
||||
static WORKER_NICENESS: AtomicU8 = AtomicU8::new(DEFAULT_WORKER_NICENESS);
|
||||
|
||||
/// Process-wide limits on stamp search threads: Python `Stamps.MAX_WORKERS`
|
||||
/// and `Stamps.NICENESS`, set from `[stamps] max_workers` and `worker_niceness`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StampWorkers {
|
||||
/// Cap on the threads of one search; `None` keeps the caller's count.
|
||||
pub max_workers: Option<NonZeroUsize>,
|
||||
/// Nice increment each thread of a multi-threaded search applies to
|
||||
/// itself, `0..=20`. Linux only, where nice values are per thread; a no-op
|
||||
/// elsewhere.
|
||||
pub niceness: u8,
|
||||
}
|
||||
|
||||
impl Default for StampWorkers {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_workers: None,
|
||||
niceness: DEFAULT_WORKER_NICENESS,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StampWorkers {
|
||||
/// Python `max(1, v)`.
|
||||
pub fn clamp_max_workers(value: i64) -> NonZeroUsize {
|
||||
usize::try_from(value)
|
||||
.ok()
|
||||
.and_then(NonZeroUsize::new)
|
||||
.unwrap_or(NonZeroUsize::MIN)
|
||||
}
|
||||
|
||||
/// Python `min(20, max(0, v))`.
|
||||
pub fn clamp_niceness(value: i64) -> u8 {
|
||||
value.clamp(0, i64::from(MAX_WORKER_NICENESS)) as u8
|
||||
}
|
||||
|
||||
/// The installed process settings.
|
||||
pub fn current() -> Self {
|
||||
Self {
|
||||
max_workers: NonZeroUsize::new(MAX_WORKERS.load(Ordering::Relaxed)),
|
||||
niceness: WORKER_NICENESS.load(Ordering::Relaxed),
|
||||
}
|
||||
}
|
||||
|
||||
/// Install for every later search in this process.
|
||||
pub fn install(self) {
|
||||
MAX_WORKERS.store(
|
||||
self.max_workers.map_or(0, NonZeroUsize::get),
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
WORKER_NICENESS.store(self.niceness.min(MAX_WORKER_NICENESS), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// `threads` capped at `max_workers`.
|
||||
pub fn cap(&self, threads: NonZeroUsize) -> NonZeroUsize {
|
||||
self.max_workers.map_or(threads, |max| threads.min(max))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn renice_search_thread(increment: u8) {
|
||||
if increment > 0 {
|
||||
// SAFETY: nice(2) only adjusts the calling thread; errors are ignored, as upstream ignores them.
|
||||
unsafe {
|
||||
libc::nice(libc::c_int::from(increment));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn renice_search_thread(_increment: u8) {}
|
||||
|
||||
/// Stop conditions and parallelism for a stamp search.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StampControl {
|
||||
@@ -508,19 +587,30 @@ fn generation_target(cost: f64) -> Result<StampTarget, StampError> {
|
||||
target_from_cost(cost)
|
||||
}
|
||||
|
||||
/// Run `worker` on `ctl.threads` threads until one returns a result or all stop.
|
||||
/// Run `worker` on `ctl.threads` threads, capped by the installed
|
||||
/// [`StampWorkers`], until one returns a result or all stop.
|
||||
fn search<T: Send>(
|
||||
ctl: &StampControl,
|
||||
worker: impl Fn(&AtomicBool) -> Option<T> + Sync,
|
||||
) -> Option<T> {
|
||||
search_with(ctl, StampWorkers::current(), worker)
|
||||
}
|
||||
|
||||
fn search_with<T: Send>(
|
||||
ctl: &StampControl,
|
||||
workers: StampWorkers,
|
||||
worker: impl Fn(&AtomicBool) -> Option<T> + Sync,
|
||||
) -> Option<T> {
|
||||
let found = AtomicBool::new(false);
|
||||
if ctl.threads.get() == 1 {
|
||||
let threads = workers.cap(ctl.threads).get();
|
||||
if threads == 1 {
|
||||
return worker(&found);
|
||||
}
|
||||
let result = Mutex::new(None);
|
||||
std::thread::scope(|scope| {
|
||||
for _ in 0..ctl.threads.get() {
|
||||
for _ in 0..threads {
|
||||
scope.spawn(|| {
|
||||
renice_search_thread(workers.niceness);
|
||||
if let Some(hit) = worker(&found) {
|
||||
found.store(true, Ordering::Relaxed);
|
||||
result
|
||||
@@ -730,6 +820,74 @@ mod tests {
|
||||
assert_eq!(stamp_valid(&stamp, 10.0, &workblock), Ok(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worker_settings_clamp_as_python() {
|
||||
assert_eq!(StampWorkers::default().max_workers, None);
|
||||
assert_eq!(StampWorkers::default().niceness, 16);
|
||||
assert_eq!(StampWorkers::clamp_max_workers(0).get(), 1);
|
||||
assert_eq!(StampWorkers::clamp_max_workers(-3).get(), 1);
|
||||
assert_eq!(StampWorkers::clamp_max_workers(6).get(), 6);
|
||||
assert_eq!(StampWorkers::clamp_niceness(-3), 0);
|
||||
assert_eq!(StampWorkers::clamp_niceness(25), 20);
|
||||
assert_eq!(StampWorkers::clamp_niceness(7), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_workers_caps_search_threads() {
|
||||
let ctl = StampControl {
|
||||
threads: NonZeroUsize::new(4).unwrap(),
|
||||
..StampControl::default()
|
||||
};
|
||||
let count = |workers: StampWorkers| {
|
||||
let started = AtomicUsize::new(0);
|
||||
search_with(&ctl, workers, |_| {
|
||||
started.fetch_add(1, Ordering::Relaxed);
|
||||
None::<()>
|
||||
});
|
||||
started.into_inner()
|
||||
};
|
||||
let capped = StampWorkers {
|
||||
max_workers: NonZeroUsize::new(2),
|
||||
niceness: 0,
|
||||
};
|
||||
assert_eq!(count(capped), 2);
|
||||
assert_eq!(
|
||||
count(StampWorkers {
|
||||
niceness: 0,
|
||||
..StampWorkers::default()
|
||||
}),
|
||||
4
|
||||
);
|
||||
let above = StampWorkers {
|
||||
max_workers: NonZeroUsize::new(9),
|
||||
niceness: 0,
|
||||
};
|
||||
assert_eq!(count(above), 4);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn pooled_search_threads_are_niced() {
|
||||
// SAFETY: getpriority(2) reads the calling thread's nice value.
|
||||
let nice = || unsafe { libc::getpriority(libc::PRIO_PROCESS, 0) };
|
||||
let base = nice();
|
||||
let ctl = StampControl {
|
||||
threads: NonZeroUsize::new(2).unwrap(),
|
||||
..StampControl::default()
|
||||
};
|
||||
let workers = StampWorkers {
|
||||
max_workers: None,
|
||||
niceness: 16,
|
||||
};
|
||||
assert_eq!(
|
||||
search_with(&ctl, workers, |_| Some(nice())),
|
||||
Some((base + 16).min(19))
|
||||
);
|
||||
let single = StampControl::default();
|
||||
assert_eq!(search_with(&single, workers, |_| Some(nice())), Some(base));
|
||||
assert_eq!(nice(), base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generation_rejects_costs_python_rejects() {
|
||||
let ctl = StampControl::default();
|
||||
|
||||
@@ -45,9 +45,9 @@ md-5 = { workspace = true }
|
||||
# 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 = { version = "0.2", features = ["NSString"] }
|
||||
objc2-core-bluetooth = { version = "0.2", features = ["CBAdvertisementData", "CBCentralManagerConstants"] }
|
||||
objc2 = "0.6"
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSString"] }
|
||||
objc2-core-bluetooth = { version = "0.3", default-features = false, features = ["std", "CBAdvertisementData", "CBCentralManagerConstants", "CBPeripheralManagerConstants"] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
//! Owned Objective-C values for the Apple BLE modules. Their calls run on Tokio
|
||||
//! workers and other threads with no autorelease pool, where an autoreleased
|
||||
//! object lives until the thread exits.
|
||||
|
||||
use objc2::msg_send;
|
||||
use objc2::rc::{Allocated, Retained};
|
||||
use objc2::runtime::{AnyClass, AnyObject};
|
||||
use objc2_foundation::NSString;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// `UUIDWithString:` autoreleases, so call this inside `autoreleasepool`.
|
||||
pub(crate) fn cbuuid(uuid: &Uuid) -> Retained<AnyObject> {
|
||||
let s = NSString::from_str(&uuid.to_string());
|
||||
let cls = AnyClass::get(c"CBUUID").expect("CBUUID must exist at runtime");
|
||||
unsafe { msg_send![cls, UUIDWithString: &*s] }
|
||||
}
|
||||
|
||||
/// A copy of `bytes`, never autoreleased.
|
||||
pub(crate) fn nsdata(bytes: &[u8]) -> Retained<AnyObject> {
|
||||
let cls = AnyClass::get(c"NSData").expect("NSData must exist at runtime");
|
||||
unsafe {
|
||||
let obj: Allocated<AnyObject> = msg_send![cls, alloc];
|
||||
msg_send![obj,
|
||||
initWithBytes: bytes.as_ptr().cast::<std::ffi::c_void>(),
|
||||
length: bytes.len()]
|
||||
}
|
||||
}
|
||||
|
||||
/// Never autoreleased; the array retains each element.
|
||||
pub(crate) fn nsarray(objects: &[&AnyObject]) -> Retained<AnyObject> {
|
||||
let cls = AnyClass::get(c"NSArray").expect("NSArray must exist at runtime");
|
||||
let ptrs: Vec<*const AnyObject> = objects.iter().map(|o| *o as *const AnyObject).collect();
|
||||
unsafe {
|
||||
let obj: Allocated<AnyObject> = msg_send![cls, alloc];
|
||||
msg_send![obj, initWithObjects: ptrs.as_ptr(), count: ptrs.len()]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use objc2::rc::{Weak, autoreleasepool};
|
||||
|
||||
/// Runs `make` on a thread with no autorelease pool, drops what it returns,
|
||||
/// and reports whether every returned object was freed. A stray retain or
|
||||
/// an autorelease outside `make`'s own pool keeps the object alive.
|
||||
pub(crate) fn freed_on_drop<F>(make: F) -> bool
|
||||
where
|
||||
F: FnOnce() -> Vec<Retained<AnyObject>> + Send + 'static,
|
||||
{
|
||||
std::thread::spawn(move || {
|
||||
let weak: Vec<Weak<AnyObject>> = {
|
||||
let objs = make();
|
||||
let weak: Vec<_> = objs.iter().map(Weak::from_retained).collect();
|
||||
// A class without weak-reference support would pass vacuously.
|
||||
assert!(weak.iter().all(|w| w.load().is_some()));
|
||||
weak
|
||||
};
|
||||
weak.iter().all(|w| w.load().is_none())
|
||||
})
|
||||
.join()
|
||||
.expect("probe thread")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_sees_an_autoreleased_object() {
|
||||
assert!(!freed_on_drop(|| {
|
||||
let cls = AnyClass::get(c"NSData").unwrap();
|
||||
let bytes = [0xCDu8; 300];
|
||||
unsafe {
|
||||
let raw: *mut AnyObject = msg_send![cls,
|
||||
dataWithBytes: bytes.as_ptr().cast::<std::ffi::c_void>(),
|
||||
length: bytes.len()];
|
||||
vec![Retained::retain(raw).unwrap()]
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nsdata_and_nsarray_are_never_autoreleased() {
|
||||
assert!(freed_on_drop(|| {
|
||||
let data = nsdata(&[0xAB; 300]);
|
||||
let arr = nsarray(&[&data]);
|
||||
vec![data, arr]
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cbuuid_holds_no_extra_retain() {
|
||||
assert!(freed_on_drop(|| {
|
||||
autoreleasepool(|_| vec![cbuuid(&crate::ble_peer::RATSPEAK_SERVICE_UUID)])
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -5,10 +5,10 @@
|
||||
//! encoded frame; this is not a bound on total connection memory.
|
||||
|
||||
use rns_transport::messages::InterfaceTransportSender;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::net::IpAddr;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::sync::{Arc, Mutex, OnceLock, RwLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::Bytes;
|
||||
@@ -18,6 +18,7 @@ use tokio::sync::mpsc;
|
||||
|
||||
use crate::hdlc;
|
||||
use crate::socket_tuning::{set_keepalive_tuned, set_socket_buffers};
|
||||
use crate::tcp::{ConnectDiagnostics, ConnectError};
|
||||
use crate::traits::{
|
||||
ByteCounter, InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, TunnelIdentity,
|
||||
handoff_accepted_interface, open_client_connection, python_address_name, python_host,
|
||||
@@ -48,6 +49,8 @@ pub const BLOCK_FAST_FLAPPING: bool = true;
|
||||
pub const FAST_FLAPPING_THRESHOLD: Duration = Duration::from_secs(20);
|
||||
pub const FAST_FLAPPING_GRACE: u64 = 5;
|
||||
pub const FAST_FLAPPING_BLOCK_TIME: Duration = Duration::from_secs(12 * 60 * 60);
|
||||
/// Python `BackboneInterface.CLIENT_LIMIT`: accepted clients a listener keeps.
|
||||
pub const CLIENT_LIMIT: u64 = 500;
|
||||
|
||||
const TX_CHANNEL_DEPTH: usize = 1024;
|
||||
|
||||
@@ -72,6 +75,30 @@ pub const DP_IC_RCVBUF: usize = 32768;
|
||||
/// safeguard itself into an unbounded allocation.
|
||||
const MAX_TRACKED_FAST_FLAP_IPS: usize = 4096;
|
||||
|
||||
/// The flap count Python gives an address from `blocked_ips` (Reticulum.py).
|
||||
const BLOCKED_IP_FLAPS: u64 = 0xFFFF;
|
||||
|
||||
type BlockedIps = Arc<RwLock<HashSet<IpAddr>>>;
|
||||
|
||||
fn process_blocked_ips() -> &'static BlockedIps {
|
||||
static BLOCKED: OnceLock<BlockedIps> = OnceLock::new();
|
||||
BLOCKED.get_or_init(BlockedIps::default)
|
||||
}
|
||||
|
||||
/// Replace the process-wide addresses from the config directory's
|
||||
/// `blocked_ips` file (Reticulum.py). Listeners with `block_fast_flapping`
|
||||
/// refuse them for good, unless `fast_flapping_grace` reaches 65535.
|
||||
/// Addresses compare canonically, so an IPv4 entry also blocks its
|
||||
/// IPv4-mapped IPv6 form. Returns the number of distinct addresses.
|
||||
pub fn set_blocked_ips(ips: impl IntoIterator<Item = IpAddr>) -> usize {
|
||||
let ips: HashSet<IpAddr> = ips.into_iter().map(|ip| ip.to_canonical()).collect();
|
||||
let count = ips.len();
|
||||
*process_blocked_ips()
|
||||
.write()
|
||||
.unwrap_or_else(|e| e.into_inner()) = ips;
|
||||
count
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BackboneServerConfig {
|
||||
pub name: String,
|
||||
@@ -93,6 +120,9 @@ pub struct BackboneServerConfig {
|
||||
pub fast_flapping_grace: u64,
|
||||
/// Time since the latest short connection before its state expires.
|
||||
pub fast_flapping_block_time: Duration,
|
||||
/// A new connection is closed while this many clients are connected;
|
||||
/// zero refuses every client.
|
||||
pub client_limit: u64,
|
||||
/// Bitrate the hardware MTU is optimised for; accepted peers inherit it.
|
||||
pub bitrate: u64,
|
||||
/// IFAC size in bytes; accepted peers inherit it.
|
||||
@@ -112,6 +142,7 @@ impl BackboneServerConfig {
|
||||
fast_flapping_threshold: FAST_FLAPPING_THRESHOLD,
|
||||
fast_flapping_grace: FAST_FLAPPING_GRACE,
|
||||
fast_flapping_block_time: FAST_FLAPPING_BLOCK_TIME,
|
||||
client_limit: CLIENT_LIMIT,
|
||||
bitrate: BITRATE_GUESS,
|
||||
ifac_size: crate::tcp::DEFAULT_IFAC_SIZE,
|
||||
}
|
||||
@@ -130,8 +161,8 @@ pub struct BackboneClientConfig {
|
||||
/// Retries allowed within one outage; `None` retries forever.
|
||||
pub max_reconnect_tries: Option<usize>,
|
||||
pub mode: InterfaceMode,
|
||||
/// Identity used to request a signed tunnel synthesis for each connection.
|
||||
/// `None`, or an identity without signing material, sends no synthesis.
|
||||
/// Set when each connection asks transport for a tunnel synthesis;
|
||||
/// transport signs it with its own wire identity.
|
||||
pub tunnel_identity: Option<TunnelIdentity>,
|
||||
/// Bitrate the hardware MTU is optimised for.
|
||||
pub bitrate: u64,
|
||||
@@ -227,6 +258,7 @@ impl FastFlapTable {
|
||||
struct FastFlapRuntime {
|
||||
clock: Arc<dyn MonotonicClock>,
|
||||
table: Arc<Mutex<FastFlapTable>>,
|
||||
blocked: BlockedIps,
|
||||
}
|
||||
|
||||
impl FastFlapRuntime {
|
||||
@@ -237,9 +269,19 @@ impl FastFlapRuntime {
|
||||
table: Arc::clone(TABLE.get_or_init(|| {
|
||||
Arc::new(Mutex::new(FastFlapTable::new(MAX_TRACKED_FAST_FLAP_IPS)))
|
||||
})),
|
||||
blocked: Arc::clone(process_blocked_ips()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Addresses from `blocked_ips`, when this listener's policy refuses them.
|
||||
fn blocked_ips(
|
||||
&self,
|
||||
policy: FastFlapPolicy,
|
||||
) -> Option<std::sync::RwLockReadGuard<'_, HashSet<IpAddr>>> {
|
||||
(policy.enabled && policy.grace < BLOCKED_IP_FLAPS)
|
||||
.then(|| self.blocked.read().unwrap_or_else(|e| e.into_inner()))
|
||||
}
|
||||
|
||||
fn admit(&self, remote_ip: IpAddr, policy: FastFlapPolicy) -> FastFlapAdmission {
|
||||
let started_at = self.clock.now();
|
||||
if !policy.enabled {
|
||||
@@ -251,6 +293,14 @@ impl FastFlapRuntime {
|
||||
});
|
||||
}
|
||||
|
||||
if self
|
||||
.blocked_ips(policy)
|
||||
.is_some_and(|blocked| blocked.contains(&remote_ip.to_canonical()))
|
||||
{
|
||||
return FastFlapAdmission::Rejected {
|
||||
flaps: BLOCKED_IP_FLAPS,
|
||||
};
|
||||
}
|
||||
let mut table = self.table.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(entry) = table.entries.get(&remote_ip).copied() {
|
||||
if started_at.saturating_sub(entry.last_flap) > policy.block_time {
|
||||
@@ -313,14 +363,22 @@ impl FastFlapRuntime {
|
||||
active_clients: &AtomicU64,
|
||||
) -> InterfaceInspectionSnapshot {
|
||||
let blocked_ips = if policy.enabled {
|
||||
let listed = self.blocked_ips(policy);
|
||||
let listed_count = listed.as_ref().map_or(0, |listed| listed.len());
|
||||
let now = self.clock.now();
|
||||
let mut table = self.table.lock().unwrap_or_else(|e| e.into_inner());
|
||||
table.prune_expired(now, policy.block_time);
|
||||
table
|
||||
let flapping = table
|
||||
.entries
|
||||
.values()
|
||||
.filter(|entry| entry.flaps > policy.grace)
|
||||
.count() as u64
|
||||
.iter()
|
||||
.filter(|(ip, entry)| {
|
||||
entry.flaps > policy.grace
|
||||
&& !listed
|
||||
.as_ref()
|
||||
.is_some_and(|listed| listed.contains(&ip.to_canonical()))
|
||||
})
|
||||
.count();
|
||||
(listed_count + flapping) as u64
|
||||
} else {
|
||||
0
|
||||
};
|
||||
@@ -411,7 +469,7 @@ async fn backbone_read_loop(
|
||||
online: Arc<AtomicBool>,
|
||||
rxb: ByteCounter,
|
||||
(bitrate, ifac_size): (u64, usize),
|
||||
) {
|
||||
) -> ConnectError {
|
||||
// ReceiveBuffer(HW_MTU, HEADER_MINSIZE, HW_MTU + ifac_size) (BackboneInterface.py).
|
||||
let hw_mtu = crate::tcp::hardware_mtu(bitrate, None) as usize;
|
||||
let mut deframer = hdlc::HdlcDeframer::with_limits(
|
||||
@@ -421,6 +479,7 @@ async fn backbone_read_loop(
|
||||
);
|
||||
// Large buffer to amortise syscalls.
|
||||
let mut buf = vec![0u8; 65536];
|
||||
let mut ended = ConnectError::ClosedByPeer;
|
||||
loop {
|
||||
match reader.read(&mut buf).await {
|
||||
Ok(0) => {
|
||||
@@ -443,17 +502,19 @@ async fn backbone_read_loop(
|
||||
if transport_tx.send(msg).await.is_err() {
|
||||
tracing::warn!(interface_id, "transport channel closed");
|
||||
online.store(false, Ordering::SeqCst);
|
||||
return;
|
||||
return ConnectError::Other;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(interface_id, error = %e, "backbone read error");
|
||||
ended = ConnectError::from_io(&e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
online.store(false, Ordering::SeqCst);
|
||||
ended
|
||||
}
|
||||
|
||||
/// Per-connection dataplane egress control state (Python `_dp_ec_*`).
|
||||
@@ -543,12 +604,16 @@ struct EgressState {
|
||||
}
|
||||
|
||||
impl EgressState {
|
||||
fn inspection(state: Arc<Self>) -> InterfaceInspectionSource {
|
||||
InterfaceInspectionSource::new(move || InterfaceInspectionSnapshot {
|
||||
tx_stalled: state.stalled.load(Ordering::Relaxed),
|
||||
tx_buffered: state.buffered.load(Ordering::Relaxed),
|
||||
fn snapshot(&self) -> InterfaceInspectionSnapshot {
|
||||
InterfaceInspectionSnapshot {
|
||||
tx_stalled: self.stalled.load(Ordering::Relaxed),
|
||||
tx_buffered: self.buffered.load(Ordering::Relaxed),
|
||||
..InterfaceInspectionSnapshot::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn inspection(state: Arc<Self>) -> InterfaceInspectionSource {
|
||||
InterfaceInspectionSource::new(move || state.snapshot())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -560,7 +625,7 @@ async fn backbone_write_loop(
|
||||
txb: &ByteCounter,
|
||||
name: &str,
|
||||
state: &EgressState,
|
||||
) {
|
||||
) -> ConnectError {
|
||||
let started = tokio::time::Instant::now();
|
||||
let mut control = EgressControl::new(0.0);
|
||||
let mut tick = tokio::time::interval_at(started + DP_EC_INTERVAL, DP_EC_INTERVAL);
|
||||
@@ -583,12 +648,12 @@ async fn backbone_write_loop(
|
||||
DP_EC_DEAD_TIME,
|
||||
name,
|
||||
);
|
||||
return;
|
||||
return ConnectError::Other;
|
||||
}
|
||||
}
|
||||
result = async { writer.write(chunk.as_deref().unwrap_or_default()).await }, if chunk.is_some() => {
|
||||
match result {
|
||||
Ok(0) => return,
|
||||
Ok(0) => return ConnectError::ClosedByPeer,
|
||||
Ok(n) => {
|
||||
let written = n as u64;
|
||||
sent += written;
|
||||
@@ -605,12 +670,12 @@ async fn backbone_write_loop(
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(name = %name, error = %e, "backbone write error");
|
||||
return;
|
||||
return ConnectError::from_io(&e);
|
||||
}
|
||||
}
|
||||
}
|
||||
item = rx.recv() => {
|
||||
let Some(data) = item else { return };
|
||||
let Some(data) = item else { return ConnectError::Other };
|
||||
let frame = Bytes::from(hdlc::frame(&data));
|
||||
let len = frame.len() as u64;
|
||||
if control.stalled() || buffered + len > TX_HWM {
|
||||
@@ -633,6 +698,7 @@ async fn backbone_write_loop(
|
||||
|
||||
/// Run one connection: the reader and the egress-controlled writer share a
|
||||
/// task, so either side ending (or the task being aborted) closes the socket.
|
||||
/// Returns how the connection ended.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn backbone_connection(
|
||||
stream: TcpStream,
|
||||
@@ -645,14 +711,17 @@ async fn backbone_connection(
|
||||
name: &str,
|
||||
state: &EgressState,
|
||||
sizing: (u64, usize),
|
||||
) {
|
||||
) -> ConnectError {
|
||||
let (reader, mut writer) = stream.into_split();
|
||||
tokio::select! {
|
||||
_ = backbone_read_loop(reader, interface_id, transport_tx, online.clone(), rxb, sizing) => {}
|
||||
_ = backbone_write_loop(&mut writer, rx, &txb, name, state) => {}
|
||||
}
|
||||
let ended = tokio::select! {
|
||||
ended = backbone_read_loop(reader, interface_id, transport_tx, online.clone(), rxb, sizing) => ended,
|
||||
ended = backbone_write_loop(&mut writer, rx, &txb, name, state) => ended,
|
||||
};
|
||||
// Python's `_dp_ec_reset` before a reconnect (BackboneInterface.py).
|
||||
state.buffered.store(0, Ordering::Relaxed);
|
||||
state.stalled.store(false, Ordering::Relaxed);
|
||||
online.store(false, Ordering::SeqCst);
|
||||
ended
|
||||
}
|
||||
|
||||
/// Resolve `host:port` preferring the configured address family.
|
||||
@@ -729,6 +798,7 @@ fn spawn_backbone_server_on_listener(
|
||||
let name = config.name.clone();
|
||||
let mode = config.mode;
|
||||
let fast_flap_policy = FastFlapPolicy::from(&config);
|
||||
let client_limit = config.client_limit;
|
||||
let sizing = (config.bitrate, config.ifac_size);
|
||||
let active_clients = Arc::new(AtomicU64::new(0));
|
||||
let inspection_runtime = fast_flap_runtime.clone();
|
||||
@@ -773,6 +843,16 @@ fn spawn_backbone_server_on_listener(
|
||||
loop {
|
||||
match listener.accept().await {
|
||||
Ok((stream, peer)) => {
|
||||
// Checked before fast flapping, so a refusal is no flap
|
||||
// (BackboneInterface.py).
|
||||
if task_active_clients.load(Ordering::Relaxed) >= client_limit {
|
||||
tracing::debug!(target: "rns::pathing",
|
||||
remote_ip = %peer.ip(),
|
||||
client_limit,
|
||||
"backbone: client limit reached, closing connection",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let fast_flap_connection =
|
||||
match fast_flap_runtime.admit(peer.ip(), fast_flap_policy) {
|
||||
FastFlapAdmission::Allowed(connection) => connection,
|
||||
@@ -916,20 +996,35 @@ fn spawn_backbone_server_on_listener(
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolve and connect, each step bounded by `timeout`.
|
||||
/// Resolve and connect, each step bounded by `timeout`, naming the failure.
|
||||
async fn connect_backbone_target(
|
||||
config: &BackboneClientConfig,
|
||||
timeout: Duration,
|
||||
) -> std::io::Result<TcpStream> {
|
||||
let target = tokio::time::timeout(
|
||||
) -> Result<TcpStream, (ConnectError, std::io::Error)> {
|
||||
use std::io::{Error, ErrorKind};
|
||||
let target = match tokio::time::timeout(
|
||||
timeout,
|
||||
resolve_target(&config.target_host, config.target_port, config.prefer_ipv6),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| std::io::Error::new(std::io::ErrorKind::TimedOut, "resolve timed out"))??;
|
||||
tokio::time::timeout(timeout, TcpStream::connect(target))
|
||||
.await
|
||||
.map_err(|_| std::io::Error::new(std::io::ErrorKind::TimedOut, "connect timed out"))?
|
||||
{
|
||||
Ok(Ok(target)) => target,
|
||||
Ok(Err(e)) => return Err((ConnectError::Dns, e)),
|
||||
Err(_) => {
|
||||
return Err((
|
||||
ConnectError::Dns,
|
||||
Error::new(ErrorKind::TimedOut, "resolve timed out"),
|
||||
));
|
||||
}
|
||||
};
|
||||
match tokio::time::timeout(timeout, TcpStream::connect(target)).await {
|
||||
Ok(Ok(stream)) => Ok(stream),
|
||||
Ok(Err(e)) => Err((ConnectError::from_io(&e), e)),
|
||||
Err(_) => Err((
|
||||
ConnectError::TimedOut,
|
||||
Error::new(ErrorKind::TimedOut, "connect timed out"),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn spawn_backbone_client(
|
||||
@@ -967,6 +1062,8 @@ pub async fn spawn_backbone_client_observed(
|
||||
let identity = InterfaceIdentity::new(&python_name, &config.name, "BackboneClientInterface");
|
||||
let egress = Arc::new(EgressState::default());
|
||||
let task_egress = egress.clone();
|
||||
let diagnostics = Arc::new(ConnectDiagnostics::default());
|
||||
let task_diagnostics = diagnostics.clone();
|
||||
let (teardown_tx, teardown) = crate::tcp::ClientTeardown::channel();
|
||||
// Python connects once, synchronously, before the interface is handed to
|
||||
// transport (BackboneInterface.py).
|
||||
@@ -977,7 +1074,7 @@ pub async fn spawn_backbone_client_observed(
|
||||
connect_backbone_target(&config, initial_timeout),
|
||||
)
|
||||
.await
|
||||
.unwrap_or_else(|_| Err(std::io::ErrorKind::TimedOut.into())),
|
||||
.unwrap_or_else(|_| Err((ConnectError::TimedOut, std::io::ErrorKind::TimedOut.into()))),
|
||||
);
|
||||
if matches!(initial_attempt, Some(Ok(_))) {
|
||||
online.store(true, Ordering::SeqCst);
|
||||
@@ -1006,23 +1103,22 @@ pub async fn spawn_backbone_client_observed(
|
||||
};
|
||||
let stream = match attempt {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
Err((error, e)) => {
|
||||
tracing::warn!(name = %config.name, error = %e, "backbone connect failed");
|
||||
task_diagnostics.failed(error);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
tune_stream(&stream);
|
||||
attempts = 0;
|
||||
task_diagnostics.connected();
|
||||
// Python synthesizes on every connection (BackboneInterface.py,
|
||||
// :1019).
|
||||
let synthesis = config
|
||||
.tunnel_identity
|
||||
.as_ref()
|
||||
.and_then(|identity| identity.synthesis(&python_name));
|
||||
open_client_connection(&rx, &transport_tx, synthesis, &online2).await;
|
||||
let synthesize = config.tunnel_identity.is_some();
|
||||
open_client_connection(&rx, &transport_tx, synthesize, &online2).await;
|
||||
|
||||
{
|
||||
let ended = {
|
||||
let mut outbound = rx.lock().await;
|
||||
backbone_connection(
|
||||
stream,
|
||||
@@ -1036,9 +1132,10 @@ pub async fn spawn_backbone_client_observed(
|
||||
&task_egress,
|
||||
sizing,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
.await
|
||||
};
|
||||
online2.store(false, Ordering::SeqCst);
|
||||
task_diagnostics.disconnected(ended);
|
||||
|
||||
tracing::info!(
|
||||
name = %config.name,
|
||||
@@ -1068,7 +1165,10 @@ pub async fn spawn_backbone_client_observed(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: Some(EgressState::inspection(egress).with_identity(identity)),
|
||||
inspection: Some(
|
||||
InterfaceInspectionSource::new(move || diagnostics.snapshot(egress.snapshot()))
|
||||
.with_identity(identity),
|
||||
),
|
||||
tx,
|
||||
read_task,
|
||||
},
|
||||
@@ -1328,6 +1428,7 @@ mod tests {
|
||||
FastFlapRuntime {
|
||||
clock: Arc::new(clock.clone()),
|
||||
table: Arc::new(Mutex::new(FastFlapTable::new(capacity))),
|
||||
blocked: BlockedIps::default(),
|
||||
},
|
||||
clock,
|
||||
)
|
||||
@@ -1391,6 +1492,66 @@ mod tests {
|
||||
.snapshot()
|
||||
}
|
||||
|
||||
/// What a client of an upstream hub sees once the hub blocks its IP:
|
||||
/// accepted, then closed at once.
|
||||
#[tokio::test]
|
||||
async fn client_stats_report_a_hub_that_closes_at_once() {
|
||||
let (transport_tx, _transport_rx) = mpsc::channel::<TransportMessage>(8);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let server = tokio::spawn(async move {
|
||||
loop {
|
||||
drop(listener.accept().await.unwrap());
|
||||
}
|
||||
});
|
||||
|
||||
let config = BackboneClientConfig::new("bb-closed", "127.0.0.1", port);
|
||||
let handle = spawn_backbone_client(config, 81, transport_tx)
|
||||
.await
|
||||
.unwrap();
|
||||
handle.owner.mark_registered();
|
||||
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(8);
|
||||
let snapshot = loop {
|
||||
let snapshot = inspection_snapshot(&handle);
|
||||
if snapshot.last_connect_error == Some("closed_by_peer") {
|
||||
break snapshot;
|
||||
}
|
||||
assert!(tokio::time::Instant::now() < deadline, "{snapshot:?}");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
};
|
||||
assert!(snapshot.connect_failures >= 1);
|
||||
assert!(!snapshot.tx_stalled);
|
||||
handle.read_task.abort();
|
||||
server.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn client_stats_report_a_refused_connect() {
|
||||
let (transport_tx, _transport_rx) = mpsc::channel::<TransportMessage>(8);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
drop(listener);
|
||||
|
||||
let config = BackboneClientConfig::new("bb-refused", "127.0.0.1", port);
|
||||
let handle = spawn_backbone_client(config, 82, transport_tx)
|
||||
.await
|
||||
.unwrap();
|
||||
handle.owner.mark_registered();
|
||||
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(8);
|
||||
loop {
|
||||
let snapshot = inspection_snapshot(&handle);
|
||||
if snapshot.last_connect_error == Some("refused") {
|
||||
assert_eq!(snapshot.connect_failures, 1);
|
||||
break;
|
||||
}
|
||||
assert!(tokio::time::Instant::now() < deadline, "{snapshot:?}");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
handle.read_task.abort();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_backbone_server_config() {
|
||||
let cfg = BackboneServerConfig::new("backbone0", "0.0.0.0", 4243);
|
||||
@@ -1404,6 +1565,7 @@ mod tests {
|
||||
cfg.fast_flapping_block_time,
|
||||
Duration::from_secs(12 * 60 * 60)
|
||||
);
|
||||
assert_eq!(cfg.client_limit, 500);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1622,6 +1784,49 @@ mod tests {
|
||||
other.disconnected();
|
||||
}
|
||||
|
||||
/// Reticulum.py 1.6.1 (5f2dbc16): a `blocked_ips` address stands at
|
||||
/// 0xFFFF flaps, never expires, is counted, and binds only listeners that
|
||||
/// block fast flapping.
|
||||
#[test]
|
||||
fn listed_ips_are_refused_for_good_and_counted() {
|
||||
let (runtime, clock) = test_runtime(1);
|
||||
let listed = IpAddr::V4(Ipv4Addr::new(198, 51, 100, 7));
|
||||
runtime.blocked.write().unwrap().insert(listed);
|
||||
let policy = default_policy();
|
||||
let active = AtomicU64::new(0);
|
||||
|
||||
assert_rejected(&runtime, listed, policy);
|
||||
let mapped = IpAddr::V6(Ipv4Addr::new(198, 51, 100, 7).to_ipv6_mapped());
|
||||
assert_rejected(&runtime, mapped, policy);
|
||||
assert_eq!(
|
||||
runtime.inspection_snapshot(policy, &active).blocked_ips,
|
||||
Some(1)
|
||||
);
|
||||
|
||||
// A full table and a long wait change nothing.
|
||||
let mut flapping = policy;
|
||||
flapping.grace = 0;
|
||||
let other = IpAddr::V4(Ipv4Addr::new(198, 51, 100, 8));
|
||||
record_short_connection(&runtime, &clock, other, flapping);
|
||||
clock.advance(policy.block_time * 4);
|
||||
assert_rejected(&runtime, listed, policy);
|
||||
assert_eq!(
|
||||
runtime.inspection_snapshot(flapping, &active).blocked_ips,
|
||||
Some(1)
|
||||
);
|
||||
|
||||
let mut off = policy;
|
||||
off.enabled = false;
|
||||
allow_connection(&runtime, listed, off).disconnected();
|
||||
assert_eq!(
|
||||
runtime.inspection_snapshot(off, &active).blocked_ips,
|
||||
Some(0)
|
||||
);
|
||||
let mut lenient = policy;
|
||||
lenient.grace = BLOCKED_IP_FLAPS;
|
||||
allow_connection(&runtime, listed, lenient).disconnected();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listeners_share_one_process_global_ip_keyspace() {
|
||||
let clock = TestClock::new();
|
||||
@@ -1629,10 +1834,12 @@ mod tests {
|
||||
let first_listener = FastFlapRuntime {
|
||||
clock: Arc::new(clock.clone()),
|
||||
table: Arc::clone(&table),
|
||||
blocked: BlockedIps::default(),
|
||||
};
|
||||
let second_listener = FastFlapRuntime {
|
||||
clock: Arc::new(clock.clone()),
|
||||
table,
|
||||
blocked: BlockedIps::default(),
|
||||
};
|
||||
let policy = default_policy();
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 9));
|
||||
@@ -1761,6 +1968,95 @@ mod tests {
|
||||
parent.read_task.abort();
|
||||
}
|
||||
|
||||
/// Python 1.6.1 closes a connection once `client_limit` clients are
|
||||
/// spawned, before any fast-flap accounting (BackboneInterface.py:696).
|
||||
#[tokio::test]
|
||||
async fn a_listener_closes_connections_past_its_client_limit() {
|
||||
let (runtime, _clock) = test_runtime(16);
|
||||
let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
|
||||
.await
|
||||
.unwrap();
|
||||
let listen_addr = listener.local_addr().unwrap();
|
||||
let mut config = BackboneServerConfig::new("limit-test", "127.0.0.1", listen_addr.port());
|
||||
config.client_limit = 2;
|
||||
let (transport_tx, _transport_rx) = mpsc::channel(8);
|
||||
let (handle_tx, mut handle_rx) = mpsc::channel(8);
|
||||
let parent = spawn_backbone_server_on_listener(
|
||||
config,
|
||||
1,
|
||||
Arc::new(AtomicU64::new(100)),
|
||||
transport_tx,
|
||||
handle_tx,
|
||||
runtime.clone(),
|
||||
listener,
|
||||
)
|
||||
.unwrap();
|
||||
parent.owner.mark_registered();
|
||||
|
||||
async fn accept(handles: &mut mpsc::Receiver<InterfaceHandle>) -> InterfaceHandle {
|
||||
tokio::time::timeout(Duration::from_secs(1), handles.recv())
|
||||
.await
|
||||
.expect("accepted child handle timed out")
|
||||
.expect("child handle channel closed")
|
||||
}
|
||||
let _first = TcpStream::connect(listen_addr).await.unwrap();
|
||||
let first = accept(&mut handle_rx).await;
|
||||
let _second = TcpStream::connect(listen_addr).await.unwrap();
|
||||
let _second_child = accept(&mut handle_rx).await;
|
||||
let flaps = tracked_flaps(&runtime, IpAddr::V4(Ipv4Addr::LOCALHOST));
|
||||
|
||||
let mut third = TcpStream::connect(listen_addr).await.unwrap();
|
||||
let mut byte = [0u8; 1];
|
||||
let closed = tokio::time::timeout(Duration::from_secs(1), third.read(&mut byte))
|
||||
.await
|
||||
.expect("the connection past the limit was not closed");
|
||||
assert!(matches!(closed, Ok(0) | Err(_)));
|
||||
assert!(handle_rx.try_recv().is_err());
|
||||
assert_eq!(
|
||||
tracked_flaps(&runtime, IpAddr::V4(Ipv4Addr::LOCALHOST)),
|
||||
flaps,
|
||||
"a refusal is not a flap"
|
||||
);
|
||||
|
||||
first.read_task.abort();
|
||||
let _ = first.read_task.await;
|
||||
let _fourth = TcpStream::connect(listen_addr).await.unwrap();
|
||||
let _fourth_child = accept(&mut handle_rx).await;
|
||||
parent.read_task.abort();
|
||||
}
|
||||
|
||||
/// Python resets egress control before a client reconnects
|
||||
/// (BackboneInterface.py:1032), so `txstalled` cannot outlive a connection.
|
||||
#[tokio::test]
|
||||
async fn an_ended_connection_clears_its_egress_state() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let peer = TcpStream::connect(listener.local_addr().unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let (stream, _) = listener.accept().await.unwrap();
|
||||
let (transport_tx, _transport_rx) = mpsc::channel(8);
|
||||
let (_tx, mut rx) = mpsc::channel::<Bytes>(8);
|
||||
let state = EgressState::default();
|
||||
state.stalled.store(true, Ordering::Relaxed);
|
||||
state.buffered.store(7, Ordering::Relaxed);
|
||||
drop(peer);
|
||||
backbone_connection(
|
||||
stream,
|
||||
&mut rx,
|
||||
5,
|
||||
InterfaceTransportSender::new(5, transport_tx),
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
ByteCounter::default(),
|
||||
ByteCounter::default(),
|
||||
"ended",
|
||||
&state,
|
||||
(BITRATE_GUESS, crate::tcp::DEFAULT_IFAC_SIZE),
|
||||
)
|
||||
.await;
|
||||
assert!(!state.stalled.load(Ordering::Relaxed));
|
||||
assert_eq!(state.buffered.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
|
||||
/// Spending the retry budget tears the client down like Python's
|
||||
/// initiator: registered, offline, never deregistered.
|
||||
#[tokio::test]
|
||||
|
||||
@@ -8,6 +8,7 @@ use crate::ble_central_lifecycle::{
|
||||
CentralEvent, CentralLifecycle, CentralState, DiscoveryEvent, classify_protocol,
|
||||
};
|
||||
use crate::ble_peer::{COLUMBA_SERVICE_UUID, RATSPEAK_SERVICE_UUID};
|
||||
use objc2::rc::autoreleasepool;
|
||||
use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel};
|
||||
use objc2::{msg_send, sel};
|
||||
use objc2_core_bluetooth::{
|
||||
@@ -144,7 +145,7 @@ pub async fn start_scan(
|
||||
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 {
|
||||
let Some(mgr_cls) = AnyClass::get(c"CBCentralManager") else {
|
||||
tracing::error!("Apple BLE Central: CBCentralManager class not found");
|
||||
return;
|
||||
};
|
||||
@@ -216,12 +217,12 @@ pub async fn stop_scan() -> Result<(), String> {
|
||||
}
|
||||
};
|
||||
|
||||
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.
|
||||
// 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.
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![&*mgr_ptr, stopScan];
|
||||
}
|
||||
});
|
||||
|
||||
finalize_stop();
|
||||
Ok(())
|
||||
@@ -286,8 +287,8 @@ pub fn central_manager_ptr() -> Option<*mut AnyObject> {
|
||||
|
||||
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)
|
||||
let superclass = AnyClass::get(c"NSObject").expect("NSObject must exist");
|
||||
let mut builder = ClassBuilder::new(c"RatspeakBleCentralDelegate", superclass)
|
||||
.expect("ClassBuilder for central delegate must succeed");
|
||||
|
||||
extern "C" fn did_update_state(
|
||||
@@ -720,23 +721,14 @@ unsafe fn scan_with_manager(mgr_raw: *mut AnyObject) -> Result<(), String> {
|
||||
.map_err(|e| format!("scan_services lock poisoned: {e}"))?
|
||||
.clone();
|
||||
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let uuids: Vec<_> = services.iter().map(crate::apple_objc::cbuuid).collect();
|
||||
let refs: Vec<&AnyObject> = uuids.iter().map(|u| &**u).collect();
|
||||
// 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 svc_arr = (!refs.is_empty()).then(|| crate::apple_objc::nsarray(&refs));
|
||||
|
||||
let number_cls = AnyClass::get("NSNumber").ok_or("NSNumber not found")?;
|
||||
let dict_cls = AnyClass::get("NSDictionary").ok_or("NSDictionary not found")?;
|
||||
let number_cls = AnyClass::get(c"NSNumber").ok_or("NSNumber not found")?;
|
||||
let dict_cls = AnyClass::get(c"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,
|
||||
@@ -750,16 +742,16 @@ unsafe fn scan_with_manager(mgr_raw: *mut AnyObject) -> Result<(), String> {
|
||||
"Apple BLE Central: scanForPeripheralsWithServices"
|
||||
);
|
||||
let _: () = msg_send![&*mgr_raw,
|
||||
scanForPeripheralsWithServices: svc_arr,
|
||||
scanForPeripheralsWithServices: svc_arr.as_deref(),
|
||||
options: opts];
|
||||
}
|
||||
Ok(())
|
||||
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 dict_cls = AnyClass::get(c"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,
|
||||
@@ -852,18 +844,6 @@ unsafe fn nsstring_to_string(s: *mut AnyObject) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
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, ()> {
|
||||
|
||||
@@ -5,10 +5,11 @@
|
||||
|
||||
#![cfg(any(target_os = "ios", target_os = "macos"))]
|
||||
|
||||
use crate::apple_objc::{cbuuid, nsarray, nsdata};
|
||||
use crate::ble_tx_queue::PacketQueue;
|
||||
use objc2::rc::{Retained, autoreleasepool};
|
||||
use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel};
|
||||
use objc2::{msg_send, sel};
|
||||
use objc2_foundation::NSString;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
@@ -135,7 +136,7 @@ pub struct ConnectedPeer {
|
||||
|
||||
impl Drop for ConnectedPeer {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
// Clear the (weakly-retained) delegate first so a late callback
|
||||
// can't fire into freed memory after the release below.
|
||||
if !self.peripheral.0.is_null() {
|
||||
@@ -157,7 +158,7 @@ impl Drop for ConnectedPeer {
|
||||
let _: () = msg_send![p.0, release];
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,12 +213,12 @@ pub async fn connect_peer(
|
||||
reason = %reason,
|
||||
"Apple BLE central connect: tearing down partial connection"
|
||||
);
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![&*manager, cancelPeripheralConnection: peripheral];
|
||||
let _: () = msg_send![peripheral, setDelegate: std::ptr::null::<AnyObject>()];
|
||||
let _: () = msg_send![delegate, release];
|
||||
let _: () = msg_send![peripheral, release];
|
||||
}
|
||||
});
|
||||
if let Ok(mut g) = pending().lock() {
|
||||
for kind in [
|
||||
CallbackKind::Connect,
|
||||
@@ -239,11 +240,11 @@ pub async fn connect_peer(
|
||||
"Apple BLE central: connectPeripheral"
|
||||
);
|
||||
let rx = install_pending(&address, CallbackKind::Connect);
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![&*manager.0,
|
||||
connectPeripheral: peripheral.0,
|
||||
options: std::ptr::null::<AnyObject>()];
|
||||
}
|
||||
});
|
||||
if let Err(e) = await_step(rx, "connect", CONNECT_TIMEOUT).await {
|
||||
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &e);
|
||||
return Err(e);
|
||||
@@ -263,17 +264,19 @@ pub async fn connect_peer(
|
||||
// install_pending must run BEFORE the CB call so a fast-path callback
|
||||
// (cached service data) can't race ahead of its own entry.
|
||||
let rx = install_pending(&address, CallbackKind::Services);
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![peripheral.0, setDelegate: delegate.0];
|
||||
let svc_filter = build_cbuuid_array(&[target_service_uuid]);
|
||||
let _: () = msg_send![peripheral.0, discoverServices: svc_filter];
|
||||
}
|
||||
let _: () = msg_send![peripheral.0, discoverServices: &*svc_filter];
|
||||
});
|
||||
if let Err(e) = await_step(rx, "discoverServices", DISCOVERY_TIMEOUT).await {
|
||||
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &e);
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
let service = match unsafe { find_service(peripheral.0, target_service_uuid) } {
|
||||
let service = match autoreleasepool(|_| unsafe {
|
||||
find_service(peripheral.0, target_service_uuid)
|
||||
}) {
|
||||
Some(p) => SendPtr(p),
|
||||
None => {
|
||||
let msg = format!("target service {target_service_uuid} not present after discovery");
|
||||
@@ -295,39 +298,41 @@ pub async fn connect_peer(
|
||||
PeerProtocol::Columba => (COLUMBA_RX_UUID, COLUMBA_TX_UUID),
|
||||
};
|
||||
let rx = install_pending(&address, CallbackKind::Chars);
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let chars_filter = build_cbuuid_array(&[rx_uuid, tx_uuid]);
|
||||
let _: () = msg_send![peripheral.0,
|
||||
discoverCharacteristics: chars_filter,
|
||||
discoverCharacteristics: &*chars_filter,
|
||||
forService: service.0];
|
||||
}
|
||||
});
|
||||
if let Err(e) = await_step(rx, "discoverCharacteristics", DISCOVERY_TIMEOUT).await {
|
||||
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &e);
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
let rx_char = match unsafe { find_char(service.0, rx_uuid) } {
|
||||
Some(p) => SendPtr(p),
|
||||
None => {
|
||||
// The peripheral owns these; retain so they outlive any single
|
||||
// delegate callback frame.
|
||||
let found = autoreleasepool(|_| unsafe {
|
||||
let rx_char = find_char(service.0, rx_uuid);
|
||||
let tx_char = find_char(service.0, tx_uuid);
|
||||
if let (Some(rx), Some(tx)) = (rx_char, tx_char) {
|
||||
let _: *mut AnyObject = msg_send![rx, retain];
|
||||
let _: *mut AnyObject = msg_send![tx, retain];
|
||||
}
|
||||
(rx_char, tx_char)
|
||||
});
|
||||
let (rx_char, tx_char) = match found {
|
||||
(Some(rx), Some(tx)) => (SendPtr(rx), SendPtr(tx)),
|
||||
(None, _) => {
|
||||
let msg = format!("rx characteristic {rx_uuid} missing after discovery");
|
||||
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &msg);
|
||||
return Err(msg);
|
||||
}
|
||||
};
|
||||
let tx_char = match unsafe { find_char(service.0, tx_uuid) } {
|
||||
Some(p) => SendPtr(p),
|
||||
None => {
|
||||
(_, None) => {
|
||||
let msg = format!("tx characteristic {tx_uuid} missing after discovery");
|
||||
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &msg);
|
||||
return Err(msg);
|
||||
}
|
||||
};
|
||||
// The peripheral owns these; retain so they outlive any single
|
||||
// delegate callback frame.
|
||||
unsafe {
|
||||
let _: *mut AnyObject = msg_send![rx_char.0, retain];
|
||||
let _: *mut AnyObject = msg_send![tx_char.0, retain];
|
||||
}
|
||||
tracing::info!(
|
||||
target: "ble_trace",
|
||||
step = "apple_connect.chars_discovered",
|
||||
@@ -339,11 +344,11 @@ pub async fn connect_peer(
|
||||
|
||||
// Step 4: setNotifyValue:YES on tx_char (CB handles CCCD internally).
|
||||
let rx = install_pending(&address, CallbackKind::Notify);
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![peripheral.0,
|
||||
setNotifyValue: true,
|
||||
forCharacteristic: tx_char.0];
|
||||
}
|
||||
});
|
||||
if let Err(e) = await_step(rx, "setNotifyValue", DISCOVERY_TIMEOUT).await {
|
||||
// Balance the rx/tx retains on failure.
|
||||
unsafe {
|
||||
@@ -437,17 +442,19 @@ fn enqueue_packet(peer: &ConnectedPeer, frames: Vec<Vec<u8>>) -> Result<bool, St
|
||||
}
|
||||
|
||||
fn drain_peer_queue(peer: &ConnectedPeer, q: &mut PacketQueue) {
|
||||
while q.drain_one(|data| {
|
||||
if !peer.online.load(Ordering::SeqCst) {
|
||||
return false;
|
||||
}
|
||||
let ready: bool = unsafe { msg_send![peer.peripheral.0, canSendWriteWithoutResponse] };
|
||||
if !ready {
|
||||
return false;
|
||||
}
|
||||
unsafe { issue_write(peer, data) };
|
||||
true
|
||||
}) {}
|
||||
autoreleasepool(|_| {
|
||||
while q.drain_one(|data| {
|
||||
if !peer.online.load(Ordering::SeqCst) {
|
||||
return false;
|
||||
}
|
||||
let ready: bool = unsafe { msg_send![peer.peripheral.0, canSendWriteWithoutResponse] };
|
||||
if !ready {
|
||||
return false;
|
||||
}
|
||||
unsafe { issue_write(peer, data) };
|
||||
true
|
||||
}) {}
|
||||
});
|
||||
}
|
||||
|
||||
/// Caller must have either confirmed `canSendWriteWithoutResponse` or be
|
||||
@@ -457,11 +464,11 @@ fn drain_peer_queue(peer: &ConnectedPeer, q: &mut PacketQueue) {
|
||||
/// `peer.peripheral.0` and `peer.rx_char.0` must be retained, valid CB
|
||||
/// pointers.
|
||||
unsafe fn issue_write(peer: &ConnectedPeer, data: &[u8]) {
|
||||
let value = nsdata(data);
|
||||
const WRITE_WITHOUT_RESPONSE: i64 = 1;
|
||||
unsafe {
|
||||
let nsdata = nsdata_from_slice(data);
|
||||
const WRITE_WITHOUT_RESPONSE: i64 = 1;
|
||||
let _: () = msg_send![peer.peripheral.0,
|
||||
writeValue: nsdata,
|
||||
writeValue: &*value,
|
||||
forCharacteristic: peer.rx_char.0,
|
||||
type: WRITE_WITHOUT_RESPONSE];
|
||||
}
|
||||
@@ -481,10 +488,10 @@ pub fn disconnect_peer(address: &str) {
|
||||
*q = PacketQueue::default();
|
||||
}
|
||||
if let Some(manager_ptr) = crate::ble_central_apple::central_manager_ptr() {
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![&*manager_ptr,
|
||||
cancelPeripheralConnection: peer.peripheral.0];
|
||||
}
|
||||
});
|
||||
}
|
||||
// online_flags entry stays — the disconnect callback flips it.
|
||||
tracing::info!(
|
||||
@@ -575,8 +582,6 @@ pub unsafe fn adopt_restored_peer(
|
||||
Some(p) => SendPtr(p),
|
||||
None => {
|
||||
unsafe {
|
||||
let _: () = msg_send![rx_char.0, retain];
|
||||
let _: () = msg_send![rx_char.0, release];
|
||||
let _: () = msg_send![peripheral, release];
|
||||
}
|
||||
return Err(format!(
|
||||
@@ -824,8 +829,8 @@ async fn await_step(
|
||||
|
||||
fn peripheral_delegate_class() -> &'static AnyClass {
|
||||
DELEGATE_CLASS.get_or_init(|| {
|
||||
let superclass = AnyClass::get("NSObject").expect("NSObject must exist");
|
||||
let mut builder = ClassBuilder::new("RatspeakBlePeripheralDelegate", superclass)
|
||||
let superclass = AnyClass::get(c"NSObject").expect("NSObject must exist");
|
||||
let mut builder = ClassBuilder::new(c"RatspeakBlePeripheralDelegate", superclass)
|
||||
.expect("ClassBuilder for peripheral delegate must succeed");
|
||||
|
||||
extern "C" fn did_discover_services(
|
||||
@@ -1015,41 +1020,11 @@ fn peripheral_delegate_class() -> &'static AnyClass {
|
||||
})
|
||||
}
|
||||
|
||||
/// Autoreleased `NSArray<CBUUID>`; CB retains internally.
|
||||
fn build_cbuuid_array(uuids: &[Uuid]) -> *mut AnyObject {
|
||||
if uuids.is_empty() {
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
let cbuuid_cls = match AnyClass::get("CBUUID") {
|
||||
Some(c) => c,
|
||||
None => return std::ptr::null_mut(),
|
||||
};
|
||||
let nsarr_cls = match AnyClass::get("NSArray") {
|
||||
Some(c) => c,
|
||||
None => return std::ptr::null_mut(),
|
||||
};
|
||||
let mut raw_ptrs: Vec<*const AnyObject> = Vec::with_capacity(uuids.len());
|
||||
for u in uuids {
|
||||
let s = NSString::from_str(&u.to_string());
|
||||
unsafe {
|
||||
let cb: *mut AnyObject = msg_send![cbuuid_cls, UUIDWithString: &*s];
|
||||
raw_ptrs.push(cb as *const AnyObject);
|
||||
}
|
||||
}
|
||||
unsafe {
|
||||
msg_send![nsarr_cls,
|
||||
arrayWithObjects: raw_ptrs.as_ptr(),
|
||||
count: raw_ptrs.len()]
|
||||
}
|
||||
}
|
||||
|
||||
/// Autoreleased `NSData` over a copy of `bytes`; valid for the synchronous
|
||||
/// CB call only.
|
||||
unsafe fn nsdata_from_slice(bytes: &[u8]) -> *mut AnyObject {
|
||||
let cls = AnyClass::get("NSData").expect("NSData class must exist");
|
||||
let ptr = bytes.as_ptr() as *const std::ffi::c_void;
|
||||
let len = bytes.len();
|
||||
unsafe { msg_send![cls, dataWithBytes: ptr, length: len] }
|
||||
/// Call inside `autoreleasepool`: the CBUUIDs autorelease.
|
||||
fn build_cbuuid_array(uuids: &[Uuid]) -> Retained<AnyObject> {
|
||||
let owned: Vec<_> = uuids.iter().map(cbuuid).collect();
|
||||
let refs: Vec<&AnyObject> = owned.iter().map(|u| &**u).collect();
|
||||
nsarray(&refs)
|
||||
}
|
||||
|
||||
unsafe fn find_service(peripheral: *mut AnyObject, uuid: Uuid) -> Option<*mut AnyObject> {
|
||||
@@ -1204,6 +1179,13 @@ unsafe fn nsstring_to_string(s: *mut AnyObject) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cbuuid_filter_holds_no_extra_retains() {
|
||||
assert!(crate::apple_objc::tests::freed_on_drop(|| {
|
||||
autoreleasepool(|_| vec![build_cbuuid_array(&[RATSPEAK_RX_UUID, RATSPEAK_TX_UUID])])
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_short_uuid_round_trip_16bit() {
|
||||
let u = expand_short_uuid("180D").expect("must parse");
|
||||
|
||||
@@ -69,6 +69,12 @@ pub const KEEPALIVE_MAX_MISSES: u32 = 3;
|
||||
pub const FRAGMENT_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
pub const MIN_RSSI: i16 = -85;
|
||||
pub const SCAN_ACTIVE_INTERVAL: Duration = Duration::from_secs(5);
|
||||
/// How often the Linux and Windows Central role looks again for a missing adapter.
|
||||
#[cfg(all(
|
||||
feature = "ble",
|
||||
not(any(target_os = "android", target_os = "ios", target_os = "macos"))
|
||||
))]
|
||||
const ADAPTER_RETRY_INTERVAL: Duration = Duration::from_secs(15);
|
||||
pub const SCAN_IDLE_INTERVAL: Duration = Duration::from_secs(30);
|
||||
pub const BLE_FRAGMENT_PACING: Duration = Duration::from_millis(8);
|
||||
/// Timeout applied while awaiting a single btleplug fragment write. A timeout
|
||||
@@ -392,39 +398,45 @@ fn has_wanted_reconnects(map: &RecentlyDisconnected) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a scan saw a peer the connect loop would try: a free slot, and a
|
||||
/// peer linked neither way and not in reconnect backoff. Pass only addresses
|
||||
/// that clear the connect loop's RSSI gate, so the active scan rate is held
|
||||
/// only for peers it can act on.
|
||||
fn has_connect_candidate<'a>(
|
||||
mut scanned: impl Iterator<Item = &'a str>,
|
||||
connected: &HashMap<String, Arc<AtomicBool>>,
|
||||
linked_to_us: &[String],
|
||||
recently_disc: &RecentlyDisconnected,
|
||||
) -> bool {
|
||||
connected.len() < MAX_PEERS
|
||||
&& scanned.any(|address| {
|
||||
!connected.contains_key(address)
|
||||
&& !linked_to_us.iter().any(|peer| peer == address)
|
||||
&& !reconnect_in_backoff(recently_disc, address)
|
||||
})
|
||||
}
|
||||
|
||||
/// Interval used for background scans with `mobile-throttle`.
|
||||
pub const SCAN_BACKGROUND_INTERVAL: Duration = Duration::from_secs(60);
|
||||
|
||||
const SCAN_SLEEP_SLICE: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Exits early on foreground-resume or `wake` notify.
|
||||
/// Exits early on a `wake` notify, which the owner sends after each change
|
||||
/// of `foreground`. The wait registers before the foreground check, so a
|
||||
/// resume between the scan and this sleep is not lost.
|
||||
async fn scan_sleep(
|
||||
total: Duration,
|
||||
foreground: &Arc<AtomicBool>,
|
||||
was_foreground: bool,
|
||||
wake: &Arc<tokio::sync::Notify>,
|
||||
) {
|
||||
if was_foreground {
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(total) => {}
|
||||
_ = wake.notified() => {}
|
||||
}
|
||||
let notified = wake.notified();
|
||||
tokio::pin!(notified);
|
||||
notified.as_mut().enable();
|
||||
if !was_foreground && foreground.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let deadline = std::time::Instant::now() + total;
|
||||
loop {
|
||||
let now = std::time::Instant::now();
|
||||
if now >= deadline {
|
||||
return;
|
||||
}
|
||||
let remaining = (deadline - now).min(SCAN_SLEEP_SLICE);
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(remaining) => {}
|
||||
_ = wake.notified() => return,
|
||||
}
|
||||
if foreground.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(total) => {}
|
||||
_ = notified => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -690,8 +702,14 @@ pub async fn disconnect_mesh_peer(address: &str) {
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|reg| reg.get(address).map(|entry| entry.connection_id));
|
||||
if let Some(connection_id) = connection_id {
|
||||
disconnect_central_peripheral(address, connection_id).await;
|
||||
if let Some(connection_id) = connection_id
|
||||
&& disconnect_central_peripheral(address, connection_id).await
|
||||
{
|
||||
// The read loop then finds the entry gone and stays quiet, so report it here.
|
||||
dispatch_event(BlePeerEvent::Disconnected {
|
||||
address: address.to_string(),
|
||||
reason: "disconnect requested".into(),
|
||||
});
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(
|
||||
@@ -740,11 +758,13 @@ pub struct BlePeerConfig {
|
||||
}
|
||||
|
||||
impl BlePeerConfig {
|
||||
/// Gateway, as upstream configures a discoverable attach point: a transport
|
||||
/// node then looks up paths its BLE peers ask for and does not know.
|
||||
pub fn new(name: &str, identity_hash: Vec<u8>) -> Self {
|
||||
Self {
|
||||
name: name.to_string(),
|
||||
identity_hash,
|
||||
mode: InterfaceMode::Full,
|
||||
mode: InterfaceMode::Gateway,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1496,8 +1516,15 @@ pub(crate) fn try_push_apple_inbound(peer: String, data: Vec<u8>) -> bool {
|
||||
#[cfg(any(target_os = "ios", target_os = "macos"))]
|
||||
mod apple_peripheral {
|
||||
use super::*;
|
||||
use crate::apple_objc::{cbuuid, nsarray, nsdata};
|
||||
use objc2::rc::{Allocated, Retained, autoreleasepool};
|
||||
use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel};
|
||||
use objc2::{msg_send, sel};
|
||||
use objc2_core_bluetooth::{
|
||||
CBPeripheralManagerOptionRestoreIdentifierKey,
|
||||
CBPeripheralManagerRestoredStateAdvertisementDataKey,
|
||||
CBPeripheralManagerRestoredStateServicesKey,
|
||||
};
|
||||
use objc2_foundation::NSString;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
@@ -1617,15 +1644,6 @@ mod apple_peripheral {
|
||||
/// previously-backgrounded GATT subscriptions.
|
||||
const PERIPHERAL_RESTORE_ID: &str = "org.ratspeak.ios.peripheral";
|
||||
|
||||
// objc2-core-bluetooth 0.2.2 only exports the central-role keys; link
|
||||
// the peripheral-role NSString constants directly.
|
||||
#[link(name = "CoreBluetooth", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
static CBPeripheralManagerOptionRestoreIdentifierKey: &'static NSString;
|
||||
static CBPeripheralManagerRestoredStateServicesKey: &'static NSString;
|
||||
static CBPeripheralManagerRestoredStateAdvertisementDataKey: &'static NSString;
|
||||
}
|
||||
|
||||
/// Ratspeak primary + Columba compat.
|
||||
const EXPECTED_SERVICE_COUNT: usize = 2;
|
||||
|
||||
@@ -1842,8 +1860,8 @@ mod apple_peripheral {
|
||||
|
||||
fn get_delegate_class() -> &'static AnyClass {
|
||||
DELEGATE_CLASS.get_or_init(|| {
|
||||
let superclass = AnyClass::get("NSObject").unwrap();
|
||||
let mut builder = ClassBuilder::new("RatspeakBleDelegate", superclass).unwrap();
|
||||
let superclass = AnyClass::get(c"NSObject").unwrap();
|
||||
let mut builder = ClassBuilder::new(c"RatspeakBleDelegate", superclass).unwrap();
|
||||
|
||||
extern "C" fn did_update_state(
|
||||
_this: *mut AnyObject,
|
||||
@@ -2474,40 +2492,27 @@ mod apple_peripheral {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
unsafe {
|
||||
let arr_cls = match AnyClass::get("NSArray") {
|
||||
Some(c) => c,
|
||||
None => return false,
|
||||
};
|
||||
let data_cls = match AnyClass::get("NSData") {
|
||||
Some(c) => c,
|
||||
None => return false,
|
||||
};
|
||||
let payload: *mut AnyObject = msg_send![data_cls,
|
||||
dataWithBytes: data.as_ptr() as *const std::ffi::c_void,
|
||||
length: data.len()];
|
||||
let centrals: *mut AnyObject = if let Some(peer_id) = to_peer {
|
||||
let map = subscribed_centrals_map().lock().unwrap();
|
||||
let ptr = match map.get(peer_id) {
|
||||
Some(p) => p.0,
|
||||
None => {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let payload = nsdata(data);
|
||||
let centrals = match to_peer {
|
||||
Some(peer_id) => {
|
||||
let map = subscribed_centrals_map().lock().unwrap();
|
||||
let Some(central) = map.get(peer_id) else {
|
||||
tracing::warn!(peer = %peer_id, "Apple BLE notify_tx: peer not in subscribed map");
|
||||
return false;
|
||||
}
|
||||
};
|
||||
let one = [ptr as *const AnyObject];
|
||||
msg_send![arr_cls, arrayWithObjects: one.as_ptr(), count: 1usize]
|
||||
} else {
|
||||
std::ptr::null_mut()
|
||||
};
|
||||
Some(nsarray(&[&*central.0]))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let ok: bool = msg_send![
|
||||
mgr,
|
||||
updateValue: payload,
|
||||
updateValue: &*payload,
|
||||
forCharacteristic: char_ptr,
|
||||
onSubscribedCentrals: centrals,
|
||||
onSubscribedCentrals: centrals.as_deref(),
|
||||
];
|
||||
ok
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// We only need the TX chars from notify_tx, but the registry is keyed
|
||||
@@ -2542,17 +2547,6 @@ mod apple_peripheral {
|
||||
.map(|(uuid, _)| *uuid)
|
||||
}
|
||||
|
||||
/// Returns a raw retained pointer.
|
||||
fn cbuuid(uuid: &Uuid) -> *mut AnyObject {
|
||||
let s = NSString::from_str(&uuid.to_string());
|
||||
unsafe {
|
||||
let cls = AnyClass::get("CBUUID").unwrap();
|
||||
let obj: *mut AnyObject = msg_send![cls, UUIDWithString: &*s];
|
||||
let _: *mut AnyObject = msg_send![obj, retain];
|
||||
obj
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn start_advertising(identity_hash: &[u8]) -> Result<(), String> {
|
||||
// Drive the lifecycle BEFORE any side effects.
|
||||
apply_event(crate::ble_peer_lifecycle::LifecycleEvent::StartRequested);
|
||||
@@ -2594,7 +2588,7 @@ mod apple_peripheral {
|
||||
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("CBPeripheralManager") else {
|
||||
let Some(mgr_cls) = AnyClass::get(c"CBPeripheralManager") else {
|
||||
tracing::error!("iOS BLE Peripheral: CBPeripheralManager class not found");
|
||||
return;
|
||||
};
|
||||
@@ -2603,7 +2597,7 @@ mod apple_peripheral {
|
||||
// background BLE event after the process is killed.
|
||||
let opts: *mut AnyObject = {
|
||||
let dict_cls =
|
||||
AnyClass::get("NSDictionary").expect("NSDictionary must exist at runtime");
|
||||
AnyClass::get(c"NSDictionary").expect("NSDictionary must exist at runtime");
|
||||
let id = NSString::from_str(PERIPHERAL_RESTORE_ID);
|
||||
msg_send![dict_cls,
|
||||
dictionaryWithObject: &*id,
|
||||
@@ -2668,68 +2662,21 @@ mod apple_peripheral {
|
||||
mgr_raw: *mut AnyObject,
|
||||
id_hash: &[u8],
|
||||
) -> Result<(), String> {
|
||||
unsafe {
|
||||
let char_cls = AnyClass::get("CBMutableCharacteristic")
|
||||
.ok_or("CBMutableCharacteristic not found")?;
|
||||
let svc_cls = AnyClass::get("CBMutableService").ok_or("CBMutableService not found")?;
|
||||
let arr_cls = AnyClass::get("NSArray").ok_or("NSArray not found")?;
|
||||
let dict_cls = AnyClass::get("NSDictionary").ok_or("NSDictionary not found")?;
|
||||
|
||||
// RX (write + writeNoResponse)
|
||||
let rx_raw: *mut AnyObject = msg_send![char_cls, alloc];
|
||||
let rx_raw: *mut AnyObject = msg_send![rx_raw,
|
||||
initWithType: cbuuid(&RATSPEAK_RX_UUID), properties: 0x0Cu64,
|
||||
value: std::ptr::null::<AnyObject>(), permissions: 0x02u64];
|
||||
// TX (read + notify)
|
||||
let tx_raw: *mut AnyObject = msg_send![char_cls, alloc];
|
||||
let tx_raw: *mut AnyObject = msg_send![tx_raw,
|
||||
initWithType: cbuuid(&RATSPEAK_TX_UUID), properties: 0x12u64,
|
||||
value: std::ptr::null::<AnyObject>(), permissions: 0x01u64];
|
||||
// Keep the registry pointer valid for notify_tx.
|
||||
let _: *mut AnyObject = msg_send![tx_raw, retain];
|
||||
register_characteristic(RATSPEAK_TX_UUID, tx_raw);
|
||||
// No static ID characteristic: it exposed a MAC-rotation-stable
|
||||
// identity read to any connecting scanner (a tracking vector) and
|
||||
// was never read by this stack — identity is learned from signed
|
||||
// announces instead.
|
||||
|
||||
// Ratspeak service (primary)
|
||||
let svc_raw: *mut AnyObject = msg_send![svc_cls, alloc];
|
||||
let svc_raw: *mut AnyObject = msg_send![svc_raw,
|
||||
initWithType: cbuuid(&RATSPEAK_SERVICE_UUID), primary: true];
|
||||
let char_ptrs = [rx_raw as *const AnyObject, tx_raw as *const AnyObject];
|
||||
let chars: *mut AnyObject = msg_send![arr_cls,
|
||||
arrayWithObjects: char_ptrs.as_ptr(), count: 2usize];
|
||||
let _: () = msg_send![svc_raw, setCharacteristics: chars];
|
||||
let _: () = msg_send![mgr_raw, addService: svc_raw];
|
||||
|
||||
// Columba compat (secondary, omitted from advertising payload).
|
||||
let c_rx_raw: *mut AnyObject = msg_send![char_cls, alloc];
|
||||
let c_rx_raw: *mut AnyObject = msg_send![c_rx_raw,
|
||||
initWithType: cbuuid(&COLUMBA_RX_UUID), properties: 0x0Cu64,
|
||||
value: std::ptr::null::<AnyObject>(), permissions: 0x02u64];
|
||||
let c_tx_raw: *mut AnyObject = msg_send![char_cls, alloc];
|
||||
let c_tx_raw: *mut AnyObject = msg_send![c_tx_raw,
|
||||
initWithType: cbuuid(&COLUMBA_TX_UUID), properties: 0x12u64,
|
||||
value: std::ptr::null::<AnyObject>(), permissions: 0x01u64];
|
||||
let _: *mut AnyObject = msg_send![c_tx_raw, retain];
|
||||
register_characteristic(COLUMBA_TX_UUID, c_tx_raw);
|
||||
let c_svc_raw: *mut AnyObject = msg_send![svc_cls, alloc];
|
||||
let c_svc_raw: *mut AnyObject = msg_send![c_svc_raw,
|
||||
initWithType: cbuuid(&COLUMBA_SERVICE_UUID), primary: false];
|
||||
let c_char_ptrs = [c_rx_raw as *const AnyObject, c_tx_raw as *const AnyObject];
|
||||
let c_chars: *mut AnyObject = msg_send![arr_cls,
|
||||
arrayWithObjects: c_char_ptrs.as_ptr(), count: 2usize];
|
||||
let _: () = msg_send![c_svc_raw, setCharacteristics: c_chars];
|
||||
let _: () = msg_send![mgr_raw, addService: c_svc_raw];
|
||||
autoreleasepool(|_| unsafe {
|
||||
let gatt = build_gatt_services()?;
|
||||
let dict_cls = AnyClass::get(c"NSDictionary").ok_or("NSDictionary not found")?;
|
||||
// The registry owns these +1s until it is drained.
|
||||
register_characteristic(RATSPEAK_TX_UUID, Retained::into_raw(gatt.ratspeak_tx));
|
||||
register_characteristic(COLUMBA_TX_UUID, Retained::into_raw(gatt.columba_tx));
|
||||
// The manager retains each service.
|
||||
let _: () = msg_send![mgr_raw, addService: &*gatt.ratspeak];
|
||||
let _: () = msg_send![mgr_raw, addService: &*gatt.columba];
|
||||
|
||||
// One 128-bit UUID fits in the 31-byte BLE 4.x adv PDU; two do not.
|
||||
let ad_key = NSString::from_str("kCBAdvDataServiceUUIDs");
|
||||
let uuid_ptrs = [cbuuid(&RATSPEAK_SERVICE_UUID) as *const AnyObject];
|
||||
let uuid_arr: *mut AnyObject = msg_send![arr_cls,
|
||||
arrayWithObjects: uuid_ptrs.as_ptr(), count: 1usize];
|
||||
let uuid_arr = nsarray(&[&*cbuuid(&RATSPEAK_SERVICE_UUID)]);
|
||||
let ad_dict: *mut AnyObject = msg_send![dict_cls,
|
||||
dictionaryWithObject: uuid_arr, forKey: &*ad_key];
|
||||
dictionaryWithObject: &*uuid_arr, forKey: &*ad_key];
|
||||
let _: () = msg_send![mgr_raw, startAdvertising: ad_dict];
|
||||
|
||||
tracing::info!(
|
||||
@@ -2741,7 +2688,53 @@ mod apple_peripheral {
|
||||
"Apple BLE Peripheral: advertising started"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
struct GattServices {
|
||||
ratspeak: Retained<AnyObject>,
|
||||
columba: Retained<AnyObject>,
|
||||
ratspeak_tx: Retained<AnyObject>,
|
||||
columba_tx: Retained<AnyObject>,
|
||||
}
|
||||
|
||||
/// Call inside `autoreleasepool`: the CBUUIDs autorelease. No static ID
|
||||
/// characteristic: it exposed a MAC-rotation-stable identity read to any
|
||||
/// connecting scanner (a tracking vector) and was never read by this
|
||||
/// stack — identity is learned from signed announces instead.
|
||||
unsafe fn build_gatt_services() -> Result<GattServices, String> {
|
||||
let char_cls =
|
||||
AnyClass::get(c"CBMutableCharacteristic").ok_or("CBMutableCharacteristic not found")?;
|
||||
let svc_cls = AnyClass::get(c"CBMutableService").ok_or("CBMutableService not found")?;
|
||||
// RX: write + writeNoResponse, writeable. TX: read + notify, readable.
|
||||
let characteristic = |uuid: &Uuid, properties: u64, permissions: u64| unsafe {
|
||||
let obj: Allocated<AnyObject> = msg_send![char_cls, alloc];
|
||||
let obj: Retained<AnyObject> = msg_send![obj,
|
||||
initWithType: &*cbuuid(uuid), properties: properties,
|
||||
value: std::ptr::null::<AnyObject>(), permissions: permissions];
|
||||
obj
|
||||
};
|
||||
let service = |uuid: &Uuid, primary: bool, rx: &AnyObject, tx: &AnyObject| unsafe {
|
||||
let obj: Allocated<AnyObject> = msg_send![svc_cls, alloc];
|
||||
let obj: Retained<AnyObject> =
|
||||
msg_send![obj, initWithType: &*cbuuid(uuid), primary: primary];
|
||||
let chars = nsarray(&[rx, tx]);
|
||||
let _: () = msg_send![&*obj, setCharacteristics: &*chars];
|
||||
obj
|
||||
};
|
||||
let rx = characteristic(&RATSPEAK_RX_UUID, 0x0C, 0x02);
|
||||
let ratspeak_tx = characteristic(&RATSPEAK_TX_UUID, 0x12, 0x01);
|
||||
let ratspeak = service(&RATSPEAK_SERVICE_UUID, true, &rx, &ratspeak_tx);
|
||||
// Columba compat: secondary, omitted from the advertising payload.
|
||||
let c_rx = characteristic(&COLUMBA_RX_UUID, 0x0C, 0x02);
|
||||
let columba_tx = characteristic(&COLUMBA_TX_UUID, 0x12, 0x01);
|
||||
let columba = service(&COLUMBA_SERVICE_UUID, false, &c_rx, &columba_tx);
|
||||
Ok(GattServices {
|
||||
ratspeak,
|
||||
columba,
|
||||
ratspeak_tx,
|
||||
columba_tx,
|
||||
})
|
||||
}
|
||||
|
||||
/// Walks the lifecycle state machine in lockstep with the platform
|
||||
@@ -2815,9 +2808,9 @@ mod apple_peripheral {
|
||||
let mgr_send = SendPtr(mgr_ptr);
|
||||
|
||||
if needs_stop_ad {
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![mgr_send.0, stopAdvertising];
|
||||
}
|
||||
});
|
||||
// CB has no peripheralManagerDidStopAdvertising delegate — poll
|
||||
// `isAdvertising`. Radio flips within ~20ms; 1s budget covers
|
||||
// contended radios and bounce loops.
|
||||
@@ -2841,13 +2834,13 @@ mod apple_peripheral {
|
||||
apply_event(crate::ble_peer_lifecycle::LifecycleEvent::AdvertiseStopped);
|
||||
}
|
||||
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![mgr_send.0, removeAllServices];
|
||||
}
|
||||
});
|
||||
apply_event(crate::ble_peer_lifecycle::LifecycleEvent::ServicesRemoved);
|
||||
|
||||
// Without this, every toggle cycle leaks two CBMutableCharacteristic
|
||||
// pointers and notify_tx can race onto dead characteristics post-teardown.
|
||||
// Releases the registry's TX characteristics, so notify_tx can't race
|
||||
// onto dead characteristics post-teardown.
|
||||
{
|
||||
let mut map = characteristic_registry().lock().unwrap();
|
||||
for (_, ptr) in map.drain() {
|
||||
@@ -2916,6 +2909,15 @@ mod apple_peripheral {
|
||||
mod notify_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn gatt_services_hold_no_extra_retains() {
|
||||
assert!(crate::apple_objc::tests::freed_on_drop(|| {
|
||||
autoreleasepool(|_| {
|
||||
let g = unsafe { build_gatt_services() }.unwrap();
|
||||
vec![g.ratspeak, g.columba, g.ratspeak_tx, g.columba_tx]
|
||||
})
|
||||
}));
|
||||
}
|
||||
#[test]
|
||||
fn readiness_keeps_partial_packet_first_across_characteristics() {
|
||||
let mut state = NotifyState {
|
||||
accepting: true,
|
||||
@@ -3012,10 +3014,10 @@ mod android_peripheral {
|
||||
}
|
||||
|
||||
fn signal_peer_offline(address: &str) {
|
||||
if let Ok(g) = peer_online_map().lock() {
|
||||
if let Some(flag) = g.get(address) {
|
||||
flag.store(false, Ordering::SeqCst);
|
||||
}
|
||||
if let Ok(g) = peer_online_map().lock()
|
||||
&& let Some(flag) = g.get(address)
|
||||
{
|
||||
flag.store(false, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3260,10 +3262,9 @@ mod android_peripheral {
|
||||
return Err("RatspeakBleAvailability returned null".into());
|
||||
}
|
||||
let jstr: jni::objects::JString = result.into();
|
||||
Ok(env
|
||||
.get_string(jstr)
|
||||
env.get_string(jstr)
|
||||
.map(|s| s.to_string_lossy().into_owned())
|
||||
.map_err(|e| format!("availability string: {e}"))?)
|
||||
.map_err(|e| format!("availability string: {e}"))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3392,7 +3393,7 @@ mod android_peripheral {
|
||||
// Close GATT server
|
||||
with_env(|env| {
|
||||
let server_cls = find_app_class(env, "org.ratspeak.android.RatspeakBleServer")
|
||||
.map_err(|e| format!("{e}"))?;
|
||||
.map_err(|e| e.to_string())?;
|
||||
env.call_static_method(server_cls, "closeGattServer", "()V", &[])
|
||||
.map_err(|e| format!("closeGattServer: {e}"))?;
|
||||
Ok(())
|
||||
@@ -3674,9 +3675,10 @@ mod android_peripheral {
|
||||
}
|
||||
}
|
||||
|
||||
/// A peer client connection dropped (centrally-initiated side).
|
||||
/// We emit a Disconnected event so the mesh-state task can prune it
|
||||
/// without waiting for a keepalive miss.
|
||||
/// A live peer client link ended (centrally-initiated side): Android's
|
||||
/// disconnect callback, or our own close, which gets no callback. We emit
|
||||
/// a Disconnected event so the mesh-state task can prune it without
|
||||
/// waiting for a keepalive miss.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "system" fn Java_org_ratspeak_android_RatspeakBlePeerClient_nativePeerClientDisconnected(
|
||||
env: jni::JNIEnv,
|
||||
@@ -5908,14 +5910,20 @@ pub async fn spawn_ble_peer_interface(
|
||||
let mut connected_addrs: HashMap<String, Arc<AtomicBool>> = HashMap::new();
|
||||
let mut scan_interval = SCAN_ACTIVE_INTERVAL;
|
||||
|
||||
// Get adapter once, reuse for all scans.
|
||||
let adapter = match crate::ble_rnode::get_adapter().await {
|
||||
Ok(a) => a,
|
||||
Err(e) => {
|
||||
tracing::error!(error = %e, "BLE mesh: failed to get adapter, Central role disabled");
|
||||
// Keep running (Peripheral role may still work)
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_secs(60)).await;
|
||||
// Get adapter once, reuse for all scans. bluetoothd or the adapter
|
||||
// can come up after us, so keep trying rather than give up for good.
|
||||
let adapter = {
|
||||
let mut warned = false;
|
||||
loop {
|
||||
match crate::ble_rnode::get_adapter().await {
|
||||
Ok(a) => break a,
|
||||
Err(e) => {
|
||||
if !warned {
|
||||
tracing::warn!(error = %e, "BLE mesh: no adapter yet, Central role retrying");
|
||||
warned = true;
|
||||
}
|
||||
tokio::time::sleep(ADAPTER_RETRY_INTERVAL).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -5977,11 +5985,12 @@ pub async fn spawn_ble_peer_interface(
|
||||
// already-connected peers every scan, so gating on "new
|
||||
// peers seen" alone pinned the radio at the active duty
|
||||
// cycle forever.
|
||||
let have_candidate = connected_addrs.len() < MAX_PEERS
|
||||
&& peers.iter().any(|p| {
|
||||
!connected_addrs.contains_key(&p.ble_address)
|
||||
&& !reconnect_in_backoff(&recently_disc, &p.ble_address)
|
||||
});
|
||||
let have_candidate = has_connect_candidate(
|
||||
peers.iter().map(|p| p.ble_address.as_str()),
|
||||
&connected_addrs,
|
||||
&[],
|
||||
&recently_disc,
|
||||
);
|
||||
let next_interval =
|
||||
if have_candidate || has_wanted_reconnects(&recently_disc) {
|
||||
SCAN_ACTIVE_INTERVAL
|
||||
@@ -6261,13 +6270,16 @@ pub async fn spawn_ble_peer_interface(
|
||||
// Connect strongest-RSSI first so a crowded room fills
|
||||
// the MAX_PEERS slots with the nearest peers.
|
||||
peers.sort_by_key(|p| std::cmp::Reverse(p.rssi));
|
||||
let peripheral_peer_addresses =
|
||||
apple_peripheral::subscribed_central_addresses();
|
||||
// Idle down when there is no actionable peer — a stable
|
||||
// mesh keeps seeing its connected peers every scan.
|
||||
let have_candidate = connected_addrs.len() < MAX_PEERS
|
||||
&& peers.iter().any(|p| {
|
||||
!connected_addrs.contains_key(&p.ble_address)
|
||||
&& !reconnect_in_backoff(&recently_disc, &p.ble_address)
|
||||
});
|
||||
let have_candidate = has_connect_candidate(
|
||||
peers.iter().map(|p| p.ble_address.as_str()),
|
||||
&connected_addrs,
|
||||
&peripheral_peer_addresses,
|
||||
&recently_disc,
|
||||
);
|
||||
let next_interval =
|
||||
if have_candidate || has_wanted_reconnects(&recently_disc) {
|
||||
SCAN_ACTIVE_INTERVAL
|
||||
@@ -6288,9 +6300,6 @@ pub async fn spawn_ble_peer_interface(
|
||||
}
|
||||
scan_interval = next_interval;
|
||||
|
||||
let peripheral_peer_addresses =
|
||||
apple_peripheral::subscribed_central_addresses();
|
||||
|
||||
for peer in &peers {
|
||||
dispatch_event(BlePeerEvent::Discovered {
|
||||
address: peer.ble_address.clone(),
|
||||
@@ -6595,19 +6604,6 @@ pub async fn spawn_ble_peer_interface(
|
||||
// MAX_PEERS slots with the nearest peers.
|
||||
scan_results.sort_by_key(|r| std::cmp::Reverse(r.1));
|
||||
|
||||
// Idle down when there is no actionable peer — a stable mesh
|
||||
// keeps seeing its connected peers every scan.
|
||||
let have_candidate = connected_addrs.len() < MAX_PEERS
|
||||
&& scan_results.iter().any(|(addr, _, _)| {
|
||||
!connected_addrs.contains_key(addr)
|
||||
&& !reconnect_in_backoff(&recently_disc, addr)
|
||||
});
|
||||
let scan_interval = if have_candidate || has_wanted_reconnects(&recently_disc) {
|
||||
SCAN_ACTIVE_INTERVAL
|
||||
} else {
|
||||
SCAN_IDLE_INTERVAL
|
||||
};
|
||||
|
||||
let peripheral_peer_addresses = if scan_results.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
@@ -6617,6 +6613,22 @@ pub async fn spawn_ble_peer_interface(
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
};
|
||||
// Idle down when there is no actionable peer — a stable mesh
|
||||
// keeps seeing its connected peers every scan.
|
||||
let have_candidate = has_connect_candidate(
|
||||
scan_results
|
||||
.iter()
|
||||
.filter(|(_, rssi, _)| *rssi >= MIN_RSSI)
|
||||
.map(|(addr, _, _)| addr.as_str()),
|
||||
&connected_addrs,
|
||||
&peripheral_peer_addresses,
|
||||
&recently_disc,
|
||||
);
|
||||
let scan_interval = if have_candidate || has_wanted_reconnects(&recently_disc) {
|
||||
SCAN_ACTIVE_INTERVAL
|
||||
} else {
|
||||
SCAN_IDLE_INTERVAL
|
||||
};
|
||||
|
||||
for (addr, rssi, protocol) in &scan_results {
|
||||
dispatch_event(BlePeerEvent::Discovered {
|
||||
@@ -7401,7 +7413,7 @@ mod tests {
|
||||
let cfg = BlePeerConfig::new("mesh0", vec![0u8; 16]);
|
||||
assert_eq!(cfg.name, "mesh0");
|
||||
assert_eq!(cfg.identity_hash.len(), 16);
|
||||
assert_eq!(cfg.mode, InterfaceMode::Full);
|
||||
assert_eq!(cfg.mode, InterfaceMode::Gateway);
|
||||
}
|
||||
|
||||
// ── BlePeer struct serialization ──
|
||||
@@ -7558,6 +7570,59 @@ mod tests {
|
||||
assert!(!reconnect_in_backoff(&map, "peer-address"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connect_candidates_match_what_the_connect_loop_would_try() {
|
||||
let recent = new_recently_disconnected();
|
||||
let online = || Arc::new(AtomicBool::new(true));
|
||||
let mut connected = HashMap::from([("central".to_owned(), online())]);
|
||||
let linked_to_us = vec!["subscribed".to_owned()];
|
||||
for _ in 0..RECONNECT_BACKOFF_FAILURES {
|
||||
record_reconnect_failure(&recent, "backoff");
|
||||
}
|
||||
let candidate = |scanned: &[&'static str], connected: &HashMap<_, _>| {
|
||||
has_connect_candidate(scanned.iter().copied(), connected, &linked_to_us, &recent)
|
||||
};
|
||||
|
||||
assert!(!candidate(
|
||||
&["central", "subscribed", "backoff"],
|
||||
&connected
|
||||
));
|
||||
assert!(candidate(&["central", "new"], &connected));
|
||||
for index in connected.len()..MAX_PEERS {
|
||||
connected.insert(format!("peer-{index}"), online());
|
||||
}
|
||||
assert!(!candidate(&["new"], &connected));
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn scan_sleep_wakes_on_a_resume_before_or_during_it() {
|
||||
let foreground = Arc::new(AtomicBool::new(true));
|
||||
let wake = Arc::new(tokio::sync::Notify::new());
|
||||
let started = tokio::time::Instant::now();
|
||||
scan_sleep(SCAN_BACKGROUND_INTERVAL, &foreground, false, &wake).await;
|
||||
assert_eq!(
|
||||
started.elapsed(),
|
||||
Duration::ZERO,
|
||||
"a resume before the sleep"
|
||||
);
|
||||
|
||||
foreground.store(false, Ordering::Relaxed);
|
||||
let sleep = tokio::spawn({
|
||||
let (foreground, wake) = (foreground.clone(), wake.clone());
|
||||
async move { scan_sleep(SCAN_BACKGROUND_INTERVAL, &foreground, false, &wake).await }
|
||||
});
|
||||
for _ in 0..8 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
wake.notify_waiters();
|
||||
sleep.await.unwrap();
|
||||
assert_eq!(started.elapsed(), Duration::ZERO, "a wake during the sleep");
|
||||
|
||||
foreground.store(false, Ordering::Relaxed);
|
||||
scan_sleep(SCAN_BACKGROUND_INTERVAL, &foreground, false, &wake).await;
|
||||
assert_eq!(started.elapsed(), SCAN_BACKGROUND_INTERVAL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_status_state_reflects_peer_count() {
|
||||
assert_eq!(peer_state_for_count(0), PeerState::Starting);
|
||||
|
||||
@@ -2691,6 +2691,19 @@ fn project_ble_rnode_frame(
|
||||
/// Apply one active-session frame to both the observer and the generation's
|
||||
/// packet-admission latch. Both desktop GATT and Android's native loopback
|
||||
/// path use this exact boundary.
|
||||
/// Battery, temperature, and channel reports, as the serial RNode keeps them.
|
||||
fn observe_radio_frame(
|
||||
stats: &std::sync::Mutex<rnode::RNodeRadioStats>,
|
||||
command: u8,
|
||||
frame: &[u8],
|
||||
) {
|
||||
stats.lock().unwrap_or_else(|e| e.into_inner()).observe(
|
||||
rnode::RNodeRadioKind::Single,
|
||||
command,
|
||||
frame,
|
||||
);
|
||||
}
|
||||
|
||||
fn project_active_ble_rnode_frame(
|
||||
publisher: &RNodeSnapshotPublisher,
|
||||
protocol_state: &mut RNodeProtocolState,
|
||||
@@ -2865,6 +2878,8 @@ pub async fn spawn_ble_rnode_interface_with_driver_and_options(
|
||||
let shared_rxb = Arc::new(AtomicU64::new(0));
|
||||
let shared_txb = Arc::new(AtomicU64::new(0));
|
||||
let task_rxb = shared_rxb.clone();
|
||||
let radio_stats = Arc::new(std::sync::Mutex::new(rnode::RNodeRadioStats::default()));
|
||||
let task_radio_stats = radio_stats.clone();
|
||||
let task_txb = shared_txb.clone();
|
||||
let (tx, mut outbound_rx) = mpsc::channel::<Bytes>(256);
|
||||
let background = crate::background_announce::register(&tx)?;
|
||||
@@ -3599,6 +3614,7 @@ pub async fn spawn_ble_rnode_interface_with_driver_and_options(
|
||||
match event {
|
||||
GenerationEvent::Notification(Some(n)) if n.uuid == NUS_TX_CHAR_UUID => {
|
||||
for (cmd, frame) in deframer.feed(&n.value) {
|
||||
observe_radio_frame(&task_radio_stats, cmd, &frame);
|
||||
let data_allowed = project_active_ble_rnode_frame(
|
||||
&snapshot_publisher,
|
||||
&mut protocol_state,
|
||||
@@ -3821,7 +3837,10 @@ pub async fn spawn_ble_rnode_interface_with_driver_and_options(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
inspection: Some(rnode::RNodeRadioStats::inspection(
|
||||
radio_stats,
|
||||
rnode::RNodeRadioKind::Single,
|
||||
)),
|
||||
tx,
|
||||
read_task,
|
||||
};
|
||||
@@ -3906,6 +3925,8 @@ pub async fn spawn_ble_rnode_interface_native_with_driver_and_options(
|
||||
let shared_rxb = Arc::new(AtomicU64::new(0));
|
||||
let shared_txb = Arc::new(AtomicU64::new(0));
|
||||
let task_rxb = shared_rxb.clone();
|
||||
let radio_stats = Arc::new(std::sync::Mutex::new(rnode::RNodeRadioStats::default()));
|
||||
let task_radio_stats = radio_stats.clone();
|
||||
let task_txb = shared_txb.clone();
|
||||
let (tx, mut outbound_rx) = mpsc::channel::<Bytes>(256);
|
||||
let background = crate::background_announce::register(&tx)?;
|
||||
@@ -4431,6 +4452,7 @@ pub async fn spawn_ble_rnode_interface_native_with_driver_and_options(
|
||||
.map(|frame| (kiss::CMD_DATA, frame))
|
||||
.chain(startup_active_frames.drain(..));
|
||||
for (command, frame) in startup_ready_frames {
|
||||
observe_radio_frame(&task_radio_stats, command, &frame);
|
||||
let data_allowed = project_active_ble_rnode_frame(
|
||||
&snapshot_publisher,
|
||||
&mut protocol_state,
|
||||
@@ -4548,6 +4570,7 @@ pub async fn spawn_ble_rnode_interface_native_with_driver_and_options(
|
||||
continue;
|
||||
}
|
||||
|
||||
observe_radio_frame(&task_radio_stats, command, &frame);
|
||||
let data_allowed = project_active_ble_rnode_frame(
|
||||
&snapshot_publisher,
|
||||
&mut protocol_state,
|
||||
@@ -4711,7 +4734,10 @@ pub async fn spawn_ble_rnode_interface_native_with_driver_and_options(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
inspection: Some(rnode::RNodeRadioStats::inspection(
|
||||
radio_stats,
|
||||
rnode::RNodeRadioKind::Single,
|
||||
)),
|
||||
tx,
|
||||
read_task,
|
||||
};
|
||||
@@ -6749,8 +6775,8 @@ mod tests {
|
||||
}
|
||||
|
||||
/// Python's `RNodeInterface` also drives BLE: any READY releases the queue
|
||||
/// (RNodeInterface.py), and the last RSSI, SNR and quality stay
|
||||
/// on the interface across packets.
|
||||
/// (RNodeInterface.py), the last RSSI, SNR and quality stay on the
|
||||
/// interface across packets, and battery reports reach its stats.
|
||||
#[tokio::test]
|
||||
async fn native_ble_any_ready_releases_the_queue_and_signal_stats_persist() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
@@ -6798,6 +6824,7 @@ mod tests {
|
||||
let mut ready = native_ready_response(&server_config);
|
||||
ready.extend(kiss::frame_with_command(rnode::CMD_STAT_RSSI, &[92]));
|
||||
ready.extend(kiss::frame_with_command(rnode::CMD_STAT_SNR, &[0xF4]));
|
||||
ready.extend(kiss::frame_with_command(rnode::CMD_STAT_BAT, &[0x01, 63]));
|
||||
ready.extend(kiss::frame(b"first inbound"));
|
||||
ready.extend(kiss::frame(b"second inbound"));
|
||||
stream
|
||||
@@ -6853,6 +6880,21 @@ mod tests {
|
||||
(Some(-65.0), Some(-3.0), Some(40.0))
|
||||
);
|
||||
}
|
||||
let radio = spawned
|
||||
.interface
|
||||
.inspection
|
||||
.as_ref()
|
||||
.expect("BLE RNode stats")
|
||||
.snapshot()
|
||||
.radio;
|
||||
assert!(radio.contains(&(
|
||||
"battery_state",
|
||||
rns_transport::messages::InterfaceStatValue::Str("discharging".into())
|
||||
)));
|
||||
assert!(radio.contains(&(
|
||||
"battery_percent",
|
||||
rns_transport::messages::InterfaceStatValue::Int(63)
|
||||
)));
|
||||
|
||||
let tx = spawned.interface.tx.clone();
|
||||
tx.send(Bytes::from_static(b"first outbound"))
|
||||
|
||||
@@ -549,8 +549,8 @@ pub struct I2PClientConfig {
|
||||
pub max_reconnect_tries: Option<usize>,
|
||||
pub reconnect_delay: u64,
|
||||
pub mode: InterfaceMode,
|
||||
/// Identity used to request a signed tunnel synthesis for each connection.
|
||||
/// `None`, or an identity without signing material, sends no synthesis.
|
||||
/// Set when each connection asks transport for a tunnel synthesis;
|
||||
/// transport signs it with its own wire identity.
|
||||
pub tunnel_identity: Option<TunnelIdentity>,
|
||||
}
|
||||
|
||||
@@ -782,11 +782,8 @@ pub async fn spawn_i2p_client(
|
||||
pacer.reset();
|
||||
// Python synthesizes on every connection (I2PInterface.py,
|
||||
// :533).
|
||||
let synthesis = config
|
||||
.tunnel_identity
|
||||
.as_ref()
|
||||
.and_then(|identity| identity.synthesis(&python_name));
|
||||
open_client_connection(&rx, &transport_tx, synthesis, &online_task).await;
|
||||
let synthesize = config.tunnel_identity.is_some();
|
||||
open_client_connection(&rx, &transport_tx, synthesize, &online_task).await;
|
||||
|
||||
// BufReader may have prefetched past the handshake; flush its tail first.
|
||||
let buffered = stream_buf_reader.buffer().to_vec();
|
||||
@@ -873,6 +870,7 @@ pub async fn spawn_i2p_server(
|
||||
let parent_rxb = server_rxb.clone();
|
||||
let parent_txb = server_txb.clone();
|
||||
let server_identity = InterfaceIdentity::bracketed("I2PInterface", &name);
|
||||
let python_name = server_identity.name.clone();
|
||||
let b32 = config.b32.as_ref().map(|b32| b32.subscribe());
|
||||
|
||||
let online_task = online.clone();
|
||||
@@ -962,8 +960,14 @@ pub async fn spawn_i2p_server(
|
||||
"I2P server: failed to store its private key; its address changes with the next session"
|
||||
);
|
||||
}
|
||||
let address = destination_b32(&our_dest);
|
||||
if let Some(address) = &address {
|
||||
tracing::debug!(
|
||||
"{python_name} endpoint setup complete. Now reachable at: {address}.b32.i2p"
|
||||
);
|
||||
}
|
||||
if let Some(b32) = &config.b32 {
|
||||
b32.send_replace(destination_b32(&our_dest));
|
||||
b32.send_replace(address);
|
||||
}
|
||||
online_task.store(true, Ordering::SeqCst);
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@ pub mod android_usb;
|
||||
mod android_usb_lifecycle;
|
||||
#[cfg(any(target_os = "android", test))]
|
||||
mod android_usb_setup;
|
||||
#[cfg(all(feature = "ble", any(target_os = "ios", target_os = "macos")))]
|
||||
mod apple_objc;
|
||||
pub mod auto;
|
||||
pub mod ax25kiss;
|
||||
pub mod backbone;
|
||||
|
||||
@@ -1471,6 +1471,8 @@ struct RNodeWriterContext {
|
||||
beacon_poll_interval: Duration,
|
||||
idle_probe_interval: Option<Duration>,
|
||||
idle_probes_enabled: Arc<AtomicBool>,
|
||||
/// Wakes an idle writer for cancellation or a newly installed lane.
|
||||
wake: Arc<tokio::sync::Notify>,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
@@ -1572,6 +1574,7 @@ struct RNodeGenerationWriter {
|
||||
ready: Arc<AtomicBool>,
|
||||
cancelled: Arc<AtomicBool>,
|
||||
idle_probes_enabled: Arc<AtomicBool>,
|
||||
wake: Arc<tokio::sync::Notify>,
|
||||
task: RNodeTaskGuard<Result<RNodeWriterExit, RNodeWriteFailure>>,
|
||||
}
|
||||
|
||||
@@ -1579,6 +1582,12 @@ struct RNodeGenerationWriter {
|
||||
impl RNodeGenerationWriter {
|
||||
fn cancel(&self) {
|
||||
self.cancelled.store(true, Ordering::SeqCst);
|
||||
self.wake.notify_one();
|
||||
}
|
||||
|
||||
fn install_background(&self, lane: crate::background_announce::BackgroundAnnounceReceiver) {
|
||||
*self.background.lock().unwrap() = Some(lane);
|
||||
self.wake.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1696,6 +1705,7 @@ enum RNodeWriterEvent {
|
||||
ProbePoll,
|
||||
FlowPoll,
|
||||
BeaconPoll,
|
||||
Wake,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
@@ -1706,6 +1716,16 @@ async fn wait_for_rnode_probe_deadline(deadline: Option<tokio::time::Instant>) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
async fn wait_for_rnode_background_offer(
|
||||
lane: Option<&crate::background_announce::BackgroundAnnounceReceiver>,
|
||||
) {
|
||||
match lane {
|
||||
Some(lane) => lane.offered().await,
|
||||
None => std::future::pending::<()>().await,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
async fn run_rnode_writer<W>(
|
||||
mut writer: W,
|
||||
@@ -1781,8 +1801,8 @@ where
|
||||
&& packet_rx.is_empty()
|
||||
&& context.carrier_online.load(Ordering::SeqCst)
|
||||
&& context.interface_online.load(Ordering::SeqCst)
|
||||
&& let Some(background) = background.filter(|lane| lane.ordinary_is_empty())
|
||||
&& let Some(packet) = background.try_start_when(rns_transport::now_f64(), || {
|
||||
&& let Some(lane) = background.as_ref().filter(|lane| lane.ordinary_is_empty())
|
||||
&& let Some(packet) = lane.try_start_when(rns_transport::now_f64(), || {
|
||||
!context.flow_control
|
||||
|| context
|
||||
.ready
|
||||
@@ -1855,12 +1875,17 @@ where
|
||||
}
|
||||
|
||||
let probe_deadline = idle_probe.as_ref().map(|probe| probe.deadline);
|
||||
// READY and carrier state have no signal, so only waiting work polls.
|
||||
let offer_waiting = background
|
||||
.as_ref()
|
||||
.is_some_and(crate::background_announce::BackgroundAnnounceReceiver::has_offer);
|
||||
let event = if pending_packet.is_some() {
|
||||
tokio::select! {
|
||||
biased;
|
||||
request = control_rx.recv(), if control_lane_open => {
|
||||
RNodeWriterEvent::Control(request)
|
||||
}
|
||||
_ = context.wake.notified() => RNodeWriterEvent::Wake,
|
||||
_ = wait_for_rnode_probe_deadline(probe_deadline) => {
|
||||
RNodeWriterEvent::ProbePoll
|
||||
}
|
||||
@@ -1874,12 +1899,16 @@ where
|
||||
request = control_rx.recv(), if control_lane_open => {
|
||||
RNodeWriterEvent::Control(request)
|
||||
}
|
||||
_ = context.wake.notified() => RNodeWriterEvent::Wake,
|
||||
_ = wait_for_rnode_probe_deadline(probe_deadline) => {
|
||||
RNodeWriterEvent::ProbePoll
|
||||
}
|
||||
_ = tokio::time::sleep(RNODE_FLOW_POLL_INTERVAL) => {
|
||||
_ = tokio::time::sleep(RNODE_FLOW_POLL_INTERVAL), if offer_waiting => {
|
||||
RNodeWriterEvent::FlowPoll
|
||||
}
|
||||
_ = wait_for_rnode_background_offer(background.as_ref()), if !offer_waiting => {
|
||||
RNodeWriterEvent::Wake
|
||||
}
|
||||
packet = packet_rx.recv(), if packet_lane_open => {
|
||||
RNodeWriterEvent::Packet(packet)
|
||||
}
|
||||
@@ -1931,6 +1960,7 @@ where
|
||||
}
|
||||
RNodeWriterEvent::ProbePoll => {}
|
||||
RNodeWriterEvent::FlowPoll => {}
|
||||
RNodeWriterEvent::Wake => {}
|
||||
// Wake the top-of-loop due check even when both input lanes are
|
||||
// idle. Checking there also prevents a continuously ready packet
|
||||
// lane from starving an elapsed station-ID beacon.
|
||||
@@ -1950,6 +1980,7 @@ where
|
||||
let ready = context.ready.clone();
|
||||
let cancelled = context.cancelled.clone();
|
||||
let idle_probes_enabled = context.idle_probes_enabled.clone();
|
||||
let wake = context.wake.clone();
|
||||
let carrier_online = context.carrier_online.clone();
|
||||
let interface_online = context.interface_online.clone();
|
||||
let id = context.id;
|
||||
@@ -1975,6 +2006,7 @@ where
|
||||
ready,
|
||||
cancelled,
|
||||
idle_probes_enabled,
|
||||
wake,
|
||||
task: RNodeTaskGuard::new(task),
|
||||
}
|
||||
}
|
||||
@@ -2015,6 +2047,7 @@ fn spawn_rnode_generation_writer(
|
||||
beacon_poll_interval: RNODE_BEACON_POLL_INTERVAL,
|
||||
idle_probe_interval: port.is_tcp().then_some(RNODE_TCP_IDLE_PROBE_INTERVAL),
|
||||
idle_probes_enabled: Arc::new(AtomicBool::new(options.idle_probes_enabled)),
|
||||
wake: Arc::new(tokio::sync::Notify::new()),
|
||||
},
|
||||
);
|
||||
writer.interrupt = interrupt;
|
||||
@@ -2031,6 +2064,7 @@ async fn finish_rnode_writer(writer: RNodeGenerationWriter) -> RNodeWriterFinish
|
||||
ready: _,
|
||||
cancelled: _,
|
||||
idle_probes_enabled: _,
|
||||
wake: _,
|
||||
mut task,
|
||||
background: _,
|
||||
} = writer;
|
||||
@@ -4225,7 +4259,7 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
let mut port_r = port_r;
|
||||
|
||||
background.retire_generation();
|
||||
*generation_writer.background.lock().unwrap() = Some(background.clone());
|
||||
generation_writer.install_background(background.clone());
|
||||
let ready = generation_writer.ready.clone();
|
||||
let packet_tx = generation_writer.packet_tx.clone();
|
||||
let control_tx = generation_writer.control_tx.clone();
|
||||
@@ -4759,6 +4793,7 @@ mod tests {
|
||||
beacon_poll_interval,
|
||||
idle_probe_interval: None,
|
||||
idle_probes_enabled: Arc::new(AtomicBool::new(true)),
|
||||
wake: Arc::new(tokio::sync::Notify::new()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9323,4 +9358,55 @@ mod tests {
|
||||
tokio::time::advance(RNODE_FLOW_POLL_INTERVAL).await;
|
||||
finish_rnode_writer(writer).await;
|
||||
}
|
||||
|
||||
// The clock never moves here: an idle writer has no poll to fall back on,
|
||||
// so each step proves its wake signal.
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn idle_writer_wakes_for_lane_install_offer_and_cancel_without_polling() {
|
||||
let (outer, _outer_rx) = mpsc::channel(2);
|
||||
let background = crate::background_announce::register(&outer).unwrap();
|
||||
let (actor, actor_control, raw) =
|
||||
crate::background_announce::scheduled_actor(outer.clone());
|
||||
let scripted = ScriptedWriter::default();
|
||||
let context = scripted_writer_context(
|
||||
false,
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
Arc::new(AtomicU64::new(0)),
|
||||
None,
|
||||
Duration::from_millis(5),
|
||||
);
|
||||
let mut writer = spawn_rnode_writer(scripted.clone(), context);
|
||||
yield_to_rnode_tasks().await;
|
||||
|
||||
writer.install_background(background.clone());
|
||||
yield_to_rnode_tasks().await;
|
||||
actor_control
|
||||
.send(TransportMessage::Tick(rns_transport::messages::TimerTick))
|
||||
.await
|
||||
.unwrap();
|
||||
yield_until_rnode_test(
|
||||
|| scripted.flush_calls() == 1,
|
||||
"an offer must wake an idle writer",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(scripted.writes(), vec![kiss::frame(&raw)]);
|
||||
|
||||
writer.cancel();
|
||||
yield_until_rnode_test(
|
||||
|| writer.task.is_finished(),
|
||||
"cancel must wake an idle writer",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
writer.task.take().await.unwrap().unwrap(),
|
||||
RNodeWriterExit::Cancelled
|
||||
);
|
||||
actor_control
|
||||
.send(TransportMessage::Shutdown)
|
||||
.await
|
||||
.unwrap();
|
||||
actor.await.unwrap();
|
||||
}
|
||||
}
|
||||
+276
-35
@@ -195,8 +195,8 @@ pub struct TcpClientConfig {
|
||||
pub bitrate: u64,
|
||||
/// IFAC size in bytes; frames may exceed the hardware MTU by this much.
|
||||
pub ifac_size: usize,
|
||||
/// Identity used to request a signed tunnel synthesis for each non-KISS
|
||||
/// connection. `None`, or an identity without signing material, sends none.
|
||||
/// Set when each non-KISS connection asks transport for a tunnel
|
||||
/// synthesis; transport signs it with its own wire identity.
|
||||
pub tunnel_identity: Option<TunnelIdentity>,
|
||||
}
|
||||
|
||||
@@ -344,6 +344,141 @@ pub fn frame_for_tcp(data: &[u8], kiss_framing: bool) -> Vec<u8> {
|
||||
|
||||
use crate::socket_tuning::set_socket_buffers;
|
||||
|
||||
/// Why a reconnecting client's attempt failed, as its interface stats name it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum ConnectError {
|
||||
Refused,
|
||||
TimedOut,
|
||||
Dns,
|
||||
Unreachable,
|
||||
ClosedByPeer,
|
||||
Other,
|
||||
}
|
||||
|
||||
impl ConnectError {
|
||||
pub(crate) fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Refused => "refused",
|
||||
Self::TimedOut => "timed_out",
|
||||
Self::Dns => "dns",
|
||||
Self::Unreachable => "unreachable",
|
||||
Self::ClosedByPeer => "closed_by_peer",
|
||||
Self::Other => "other",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn from_io(error: &std::io::Error) -> Self {
|
||||
use std::io::ErrorKind;
|
||||
match error.kind() {
|
||||
ErrorKind::ConnectionRefused => Self::Refused,
|
||||
ErrorKind::TimedOut => Self::TimedOut,
|
||||
ErrorKind::HostUnreachable
|
||||
| ErrorKind::NetworkUnreachable
|
||||
| ErrorKind::NetworkDown
|
||||
| ErrorKind::AddrNotAvailable => Self::Unreachable,
|
||||
ErrorKind::ConnectionReset
|
||||
| ErrorKind::ConnectionAborted
|
||||
| ErrorKind::BrokenPipe
|
||||
| ErrorKind::UnexpectedEof => Self::ClosedByPeer,
|
||||
_ => Self::Other,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A connection that ends sooner is a failed attempt, `closed_by_peer` when the
|
||||
/// server ended it: an upstream Backbone hub accepts and at once closes an IP it
|
||||
/// blocks, and counts connections this short as fast flaps.
|
||||
pub(crate) const CONNECTION_STAYS_UP: std::time::Duration =
|
||||
crate::backbone::FAST_FLAPPING_THRESHOLD;
|
||||
|
||||
/// The connect outcome a reconnecting client reports in its interface stats.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct ConnectDiagnostics(std::sync::Mutex<ConnectState>);
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct ConnectState {
|
||||
last_error: Option<ConnectError>,
|
||||
failures: u32,
|
||||
connected_at: Option<std::time::Instant>,
|
||||
}
|
||||
|
||||
impl ConnectState {
|
||||
fn stayed_up(&self) -> bool {
|
||||
self.connected_at
|
||||
.is_some_and(|at| at.elapsed() >= CONNECTION_STAYS_UP)
|
||||
}
|
||||
|
||||
fn fail(&mut self, error: ConnectError) {
|
||||
self.last_error = Some(error);
|
||||
self.failures = self.failures.saturating_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
impl ConnectDiagnostics {
|
||||
fn state(&self) -> std::sync::MutexGuard<'_, ConnectState> {
|
||||
self.0
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
pub(crate) fn failed(&self, error: ConnectError) {
|
||||
self.state().fail(error);
|
||||
}
|
||||
|
||||
pub(crate) fn connected(&self) {
|
||||
self.state().connected_at = Some(std::time::Instant::now());
|
||||
}
|
||||
|
||||
/// `ended` names how the connection closed.
|
||||
pub(crate) fn disconnected(&self, ended: ConnectError) {
|
||||
let mut state = self.state();
|
||||
if state.stayed_up() {
|
||||
state.last_error = None;
|
||||
state.failures = 0;
|
||||
} else {
|
||||
state.fail(ended);
|
||||
}
|
||||
state.connected_at = None;
|
||||
}
|
||||
|
||||
pub(crate) fn snapshot(
|
||||
&self,
|
||||
mut snapshot: InterfaceInspectionSnapshot,
|
||||
) -> InterfaceInspectionSnapshot {
|
||||
let state = self.state();
|
||||
if !state.stayed_up() {
|
||||
snapshot.last_connect_error = state.last_error.map(ConnectError::as_str);
|
||||
snapshot.connect_failures = state.failures;
|
||||
}
|
||||
snapshot
|
||||
}
|
||||
}
|
||||
|
||||
/// `TcpStream::connect(addr)` within [`INITIAL_CONNECT_TIMEOUT`], naming the failure.
|
||||
async fn connect_tcp_target(addr: &str) -> Result<TcpStream, (ConnectError, std::io::Error)> {
|
||||
use std::io::{Error, ErrorKind};
|
||||
let deadline =
|
||||
tokio::time::Instant::now() + std::time::Duration::from_secs(INITIAL_CONNECT_TIMEOUT);
|
||||
let addrs: Vec<std::net::SocketAddr> =
|
||||
match tokio::time::timeout_at(deadline, tokio::net::lookup_host(addr)).await {
|
||||
Ok(Ok(addrs)) => addrs.collect(),
|
||||
Ok(Err(error)) => return Err((ConnectError::Dns, error)),
|
||||
Err(_) => return Err((ConnectError::Dns, ErrorKind::TimedOut.into())),
|
||||
};
|
||||
if addrs.is_empty() {
|
||||
return Err((
|
||||
ConnectError::Dns,
|
||||
Error::new(ErrorKind::NotFound, "could not resolve to any address"),
|
||||
));
|
||||
}
|
||||
match tokio::time::timeout_at(deadline, TcpStream::connect(&addrs[..])).await {
|
||||
Ok(Ok(stream)) => Ok(stream),
|
||||
Ok(Err(error)) => Err((ConnectError::from_io(&error), error)),
|
||||
Err(_) => Err((ConnectError::TimedOut, ErrorKind::TimedOut.into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns how the connection ended.
|
||||
async fn tcp_read_loop(
|
||||
mut reader: tokio::net::tcp::OwnedReadHalf,
|
||||
interface_id: InterfaceId,
|
||||
@@ -352,7 +487,8 @@ async fn tcp_read_loop(
|
||||
kiss_framing: bool,
|
||||
hw_mtu: usize,
|
||||
ifac_size: usize,
|
||||
) {
|
||||
) -> ConnectError {
|
||||
let mut ended = ConnectError::ClosedByPeer;
|
||||
let mut buf = [0u8; 32768];
|
||||
|
||||
if kiss_framing {
|
||||
@@ -378,12 +514,13 @@ async fn tcp_read_loop(
|
||||
});
|
||||
if transport_tx.send(msg).await.is_err() {
|
||||
tracing::warn!(interface_id, "transport channel closed");
|
||||
return;
|
||||
return ConnectError::Other;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(interface_id, error = %e, "TCP read error");
|
||||
ended = ConnectError::from_io(&e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -421,18 +558,20 @@ async fn tcp_read_loop(
|
||||
});
|
||||
if transport_tx.send(msg).await.is_err() {
|
||||
tracing::warn!(interface_id, "transport channel closed");
|
||||
return;
|
||||
return ConnectError::Other;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(interface_id, error = %e, "TCP read error");
|
||||
ended = ConnectError::from_io(&e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
state.online.store(false, Ordering::SeqCst);
|
||||
ended
|
||||
}
|
||||
|
||||
async fn tcp_write_loop(
|
||||
@@ -544,21 +683,17 @@ pub async fn spawn_tcp_client_observed(
|
||||
let python_name = config.python_name();
|
||||
let identity = InterfaceIdentity::new(&python_name, &config.name, "TCPClientInterface");
|
||||
let (teardown_tx, teardown) = ClientTeardown::channel();
|
||||
let diagnostics = Arc::new(ConnectDiagnostics::default());
|
||||
let task_diagnostics = diagnostics.clone();
|
||||
let addr = format!("{}:{}", config.target_host, config.target_port);
|
||||
// Python connects once, synchronously, before the interface is handed to
|
||||
// transport (TCPInterface.py).
|
||||
let mut initial_attempt = Some(
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(INITIAL_CONNECT_TIMEOUT),
|
||||
TcpStream::connect(format!("{}:{}", config.target_host, config.target_port)),
|
||||
)
|
||||
.await,
|
||||
);
|
||||
if matches!(initial_attempt, Some(Ok(Ok(_)))) {
|
||||
let mut initial_attempt = Some(connect_tcp_target(&addr).await);
|
||||
if matches!(initial_attempt, Some(Ok(_))) {
|
||||
online.store(true, Ordering::SeqCst);
|
||||
}
|
||||
let read_task = tokio::spawn(async move {
|
||||
let max_tries = config.max_reconnect_tries;
|
||||
let addr = format!("{}:{}", config.target_host, config.target_port);
|
||||
// Every attempt after the first follows a failure or an outage.
|
||||
let mut attempted = false;
|
||||
// Retries within the current outage (TCPInterface.py).
|
||||
@@ -577,22 +712,13 @@ pub async fn spawn_tcp_client_observed(
|
||||
attempted = true;
|
||||
let attempt = match initial_attempt.take() {
|
||||
Some(attempt) => attempt,
|
||||
None => {
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(INITIAL_CONNECT_TIMEOUT),
|
||||
TcpStream::connect(&addr),
|
||||
)
|
||||
.await
|
||||
}
|
||||
None => connect_tcp_target(&addr).await,
|
||||
};
|
||||
let stream = match attempt {
|
||||
Ok(Ok(s)) => s,
|
||||
Ok(Err(e)) => {
|
||||
Ok(s) => s,
|
||||
Err((error, e)) => {
|
||||
tracing::warn!(name = %config.name, error = %e, "TCP connect failed");
|
||||
continue;
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::warn!(name = %config.name, "TCP connect timed out");
|
||||
task_diagnostics.failed(error);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
@@ -606,14 +732,11 @@ pub async fn spawn_tcp_client_observed(
|
||||
let state = TcpInterfaceState::with_shared_counters(task_rxb.clone(), task_txb.clone());
|
||||
state.online.store(true, Ordering::SeqCst);
|
||||
attempts = 0;
|
||||
task_diagnostics.connected();
|
||||
// Python synthesizes on every non-KISS connection
|
||||
// (TCPInterface.py).
|
||||
let synthesis = config
|
||||
.tunnel_identity
|
||||
.as_ref()
|
||||
.filter(|_| !kiss_framing)
|
||||
.and_then(|identity| identity.synthesis(&python_name));
|
||||
open_client_connection(&rx, &transport_tx, synthesis, &online2).await;
|
||||
let synthesize = config.tunnel_identity.is_some() && !kiss_framing;
|
||||
open_client_connection(&rx, &transport_tx, synthesize, &online2).await;
|
||||
|
||||
let (reader, writer) = stream.into_split();
|
||||
|
||||
@@ -631,7 +754,7 @@ pub async fn spawn_tcp_client_observed(
|
||||
}
|
||||
});
|
||||
|
||||
tcp_read_loop(
|
||||
let ended = tcp_read_loop(
|
||||
reader,
|
||||
id,
|
||||
transport_tx.clone(),
|
||||
@@ -643,6 +766,7 @@ pub async fn spawn_tcp_client_observed(
|
||||
.await;
|
||||
|
||||
online2.store(false, Ordering::SeqCst);
|
||||
task_diagnostics.disconnected(ended);
|
||||
|
||||
fwd_handle.abort();
|
||||
let _ = fwd_handle.await;
|
||||
@@ -673,7 +797,12 @@ pub async fn spawn_tcp_client_observed(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: Some(InterfaceInspectionSource::identified(identity)),
|
||||
inspection: Some(
|
||||
InterfaceInspectionSource::new(move || {
|
||||
diagnostics.snapshot(InterfaceInspectionSnapshot::default())
|
||||
})
|
||||
.with_identity(identity),
|
||||
),
|
||||
tx,
|
||||
read_task,
|
||||
},
|
||||
@@ -1042,6 +1171,118 @@ mod tests {
|
||||
handle.read_task.abort();
|
||||
}
|
||||
|
||||
async fn connect_error(
|
||||
handle: &InterfaceHandle,
|
||||
expected: &str,
|
||||
) -> InterfaceInspectionSnapshot {
|
||||
let source = handle.inspection.as_ref().unwrap();
|
||||
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(8);
|
||||
loop {
|
||||
let snapshot = source.snapshot();
|
||||
if snapshot.last_connect_error == Some(expected) {
|
||||
return snapshot;
|
||||
}
|
||||
assert!(
|
||||
tokio::time::Instant::now() < deadline,
|
||||
"expected {expected}, got {snapshot:?}"
|
||||
);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stats_report_a_refused_connect() {
|
||||
let (transport_tx, _transport_rx) = mpsc::channel::<TransportMessage>(8);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
drop(listener);
|
||||
|
||||
let config = TcpClientConfig::new("tcp-refused", "127.0.0.1", port);
|
||||
let handle = spawn_tcp_client(config, 78, transport_tx).await.unwrap();
|
||||
handle.owner.mark_registered();
|
||||
|
||||
let snapshot = connect_error(&handle, "refused").await;
|
||||
assert_eq!(snapshot.connect_failures, 1);
|
||||
handle.read_task.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stats_report_a_name_that_does_not_resolve() {
|
||||
let (transport_tx, _transport_rx) = mpsc::channel::<TransportMessage>(8);
|
||||
let config = TcpClientConfig::new("tcp-dns", "no-such-host.invalid", 4242);
|
||||
let handle = spawn_tcp_client(config, 80, transport_tx).await.unwrap();
|
||||
handle.owner.mark_registered();
|
||||
|
||||
connect_error(&handle, "dns").await;
|
||||
handle.read_task.abort();
|
||||
}
|
||||
|
||||
/// An upstream Backbone hub accepts a blocked IP and closes it at once.
|
||||
#[tokio::test]
|
||||
async fn stats_report_a_server_that_closes_at_once() {
|
||||
let (transport_tx, _transport_rx) = mpsc::channel::<TransportMessage>(8);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let server = tokio::spawn(async move {
|
||||
loop {
|
||||
drop(listener.accept().await.unwrap());
|
||||
}
|
||||
});
|
||||
|
||||
let config = TcpClientConfig::new("tcp-closed", "127.0.0.1", port);
|
||||
let handle = spawn_tcp_client(config, 79, transport_tx).await.unwrap();
|
||||
handle.owner.mark_registered();
|
||||
|
||||
let snapshot = connect_error(&handle, "closed_by_peer").await;
|
||||
assert!(snapshot.connect_failures >= 1);
|
||||
handle.read_task.abort();
|
||||
server.abort();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connect_diagnostics_clear_once_a_connection_stays_up() {
|
||||
let diagnostics = ConnectDiagnostics::default();
|
||||
let report = |d: &ConnectDiagnostics| {
|
||||
let s = d.snapshot(InterfaceInspectionSnapshot::default());
|
||||
(s.last_connect_error, s.connect_failures)
|
||||
};
|
||||
assert_eq!(report(&diagnostics), (None, 0));
|
||||
|
||||
diagnostics.failed(ConnectError::TimedOut);
|
||||
diagnostics.failed(ConnectError::Refused);
|
||||
assert_eq!(report(&diagnostics), (Some("refused"), 2));
|
||||
|
||||
// Still on probation: the last failure stands until the link stays up.
|
||||
diagnostics.connected();
|
||||
assert_eq!(report(&diagnostics), (Some("refused"), 2));
|
||||
diagnostics.disconnected(ConnectError::ClosedByPeer);
|
||||
assert_eq!(report(&diagnostics), (Some("closed_by_peer"), 3));
|
||||
|
||||
let Some(earlier) = std::time::Instant::now().checked_sub(CONNECTION_STAYS_UP) else {
|
||||
return;
|
||||
};
|
||||
diagnostics.connected();
|
||||
diagnostics.state().connected_at = Some(earlier);
|
||||
assert_eq!(report(&diagnostics), (None, 0));
|
||||
diagnostics.disconnected(ConnectError::ClosedByPeer);
|
||||
assert_eq!(report(&diagnostics), (None, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connect_errors_classify_io_errors() {
|
||||
use std::io::{Error, ErrorKind};
|
||||
for (kind, expected) in [
|
||||
(ErrorKind::ConnectionRefused, "refused"),
|
||||
(ErrorKind::TimedOut, "timed_out"),
|
||||
(ErrorKind::HostUnreachable, "unreachable"),
|
||||
(ErrorKind::NetworkUnreachable, "unreachable"),
|
||||
(ErrorKind::ConnectionReset, "closed_by_peer"),
|
||||
(ErrorKind::PermissionDenied, "other"),
|
||||
] {
|
||||
assert_eq!(ConnectError::from_io(&Error::from(kind)).as_str(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_frame_for_tcp_hdlc() {
|
||||
let data = b"test packet";
|
||||
|
||||
@@ -95,23 +95,12 @@ pub(crate) async fn handoff_accepted_interface(
|
||||
}
|
||||
}
|
||||
|
||||
/// The transport identity a client signs its tunnel syntheses with (Python
|
||||
/// `Transport.identity`). Debug shows only its hash.
|
||||
/// The wire transport identity (Python `Transport.identity`). A client given
|
||||
/// one asks transport for a tunnel synthesis on each connection; transport
|
||||
/// signs it with the identity from `SetTunnelIdentity`. Debug shows only its hash.
|
||||
#[derive(Clone)]
|
||||
pub struct TunnelIdentity(pub Arc<rns_identity::identity::Identity>);
|
||||
|
||||
impl TunnelIdentity {
|
||||
/// Build a fresh synthesis using `python_name` as the Python-compatible
|
||||
/// interface name. Returns `None` when the identity cannot sign.
|
||||
pub fn synthesis(&self, python_name: &str) -> Option<Bytes> {
|
||||
rns_transport::tunnel::build_tunnel_synthesis_packet(
|
||||
&self.0,
|
||||
rns_transport::tunnel::interface_hash(python_name),
|
||||
)
|
||||
.map(Bytes::from)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for TunnelIdentity {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_tuple("TunnelIdentity")
|
||||
@@ -137,19 +126,18 @@ pub(crate) fn python_host(host: &str) -> std::borrow::Cow<'_, str> {
|
||||
pub(crate) async fn open_client_connection(
|
||||
outbound: &tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
|
||||
transport_tx: &rns_transport::messages::InterfaceTransportSender,
|
||||
synthesis: Option<Bytes>,
|
||||
synthesize: bool,
|
||||
online: &AtomicBool,
|
||||
) {
|
||||
if !online.load(std::sync::atomic::Ordering::SeqCst) {
|
||||
let mut queued = outbound.lock().await;
|
||||
while queued.try_recv().is_ok() {}
|
||||
}
|
||||
if let Some(raw_packet) = synthesis {
|
||||
if synthesize {
|
||||
let _ = transport_tx
|
||||
.send(
|
||||
rns_transport::messages::TransportMessage::SynthesizeTunnel {
|
||||
interface_id: transport_tx.interface_id(),
|
||||
raw_packet,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
@@ -288,7 +276,7 @@ pub const AR_MINFREQ_HZ: f64 = 0.1;
|
||||
pub const PR_MINFREQ_HZ: f64 = 0.1;
|
||||
pub const AR_FREQ_DECAY: f64 = 1.0 / AR_MINFREQ_HZ;
|
||||
pub const PR_FREQ_DECAY: f64 = 1.0 / PR_MINFREQ_HZ;
|
||||
pub const MAX_HELD_ANNOUNCES: usize = 256;
|
||||
pub const MAX_HELD_ANNOUNCES: usize = rns_transport::constants::MAX_HELD_ANNOUNCES;
|
||||
/// Duration a new interface stays in "new" state (seconds).
|
||||
pub const IC_NEW_TIME: f64 = 7200.0;
|
||||
/// Burst threshold for new interfaces (announces/sec).
|
||||
@@ -391,7 +379,7 @@ mod tests {
|
||||
let transport_tx = rns_transport::messages::InterfaceTransportSender::new(7, actor_tx);
|
||||
let online = AtomicBool::new(false);
|
||||
|
||||
open_client_connection(&outbound, &transport_tx, None, &online).await;
|
||||
open_client_connection(&outbound, &transport_tx, false, &online).await;
|
||||
|
||||
assert!(
|
||||
outbound.lock().await.try_recv().is_err(),
|
||||
@@ -409,7 +397,7 @@ mod tests {
|
||||
let online = AtomicBool::new(true);
|
||||
frame_tx.send(Bytes::from_static(b"first")).await.unwrap();
|
||||
|
||||
open_client_connection(&outbound, &transport_tx, None, &online).await;
|
||||
open_client_connection(&outbound, &transport_tx, false, &online).await;
|
||||
|
||||
assert_eq!(
|
||||
outbound.lock().await.try_recv().ok(),
|
||||
@@ -418,6 +406,31 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Each connection asks transport for its synthesis before it reports
|
||||
/// online; transport builds and signs it.
|
||||
#[tokio::test]
|
||||
async fn a_connection_asks_for_its_synthesis_before_it_is_online() {
|
||||
let (_frame_tx, frame_rx) = mpsc::channel::<Bytes>(4);
|
||||
let outbound = tokio::sync::Mutex::new(frame_rx);
|
||||
let (actor_tx, mut actor_rx) = mpsc::channel(4);
|
||||
let transport_tx = rns_transport::messages::InterfaceTransportSender::new(7, actor_tx);
|
||||
let owner = transport_tx.owner();
|
||||
owner.mark_registered();
|
||||
let online = AtomicBool::new(false);
|
||||
|
||||
open_client_connection(&outbound, &transport_tx, true, &online).await;
|
||||
|
||||
let message = match actor_rx.try_recv().unwrap() {
|
||||
rns_transport::messages::TransportMessage::InterfaceEvent { message, .. } => *message,
|
||||
message => message,
|
||||
};
|
||||
assert!(matches!(
|
||||
message,
|
||||
rns_transport::messages::TransportMessage::SynthesizeTunnel { interface_id: 7 }
|
||||
));
|
||||
assert!(online.load(Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_interface_mode_repr() {
|
||||
assert_eq!(InterfaceMode::Full as u8, 0x01);
|
||||
|
||||
@@ -1149,13 +1149,18 @@ impl LazyMultiSegmentOutbound {
|
||||
|
||||
/// Collect independently verified Resource segments in order. Use
|
||||
/// `set_segment` with `assemble_segment`, or pass already verified payloads to
|
||||
/// `set_segment_data`. `reassemble` concatenates those payloads; it does not
|
||||
/// recompute or verify `original_hash` or impose a total byte limit.
|
||||
/// `set_segment_data`. Payloads that arrive in order are appended to one
|
||||
/// buffer at once; `take_reassembled` returns it. Neither recomputes or
|
||||
/// verifies `original_hash`.
|
||||
pub struct MultiSegmentInbound {
|
||||
pub original_hash: [u8; 32],
|
||||
pub total_segments: usize,
|
||||
pub segments: Vec<Option<InboundResource>>,
|
||||
/// Payloads that arrived ahead of a missing segment, by 0-based index.
|
||||
pub assembled_segments: Vec<Option<Vec<u8>>>,
|
||||
/// Segments `1..=assembled_through`, concatenated.
|
||||
pub assembled: Vec<u8>,
|
||||
pub assembled_through: usize,
|
||||
pub data_size: usize,
|
||||
/// First metadata supplied through `set_metadata`. Outbound constructors
|
||||
/// can attach metadata to the first segment; the owner must carry it here
|
||||
@@ -1174,6 +1179,8 @@ impl MultiSegmentInbound {
|
||||
total_segments,
|
||||
segments: Vec::new(),
|
||||
assembled_segments: Vec::new(),
|
||||
assembled: Vec::new(),
|
||||
assembled_through: 0,
|
||||
data_size: 0,
|
||||
metadata: None,
|
||||
size_bound: None,
|
||||
@@ -1215,13 +1222,43 @@ impl MultiSegmentInbound {
|
||||
let idx = segment_index - 1;
|
||||
if let Some(Some(resource)) = self.segments.get_mut(idx) {
|
||||
let data = resource.assemble(decrypt_fn)?;
|
||||
*Self::slot(&mut self.assembled_segments, idx) = Some(data);
|
||||
self.store(idx, data);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ResourceError::Incomplete)
|
||||
}
|
||||
}
|
||||
|
||||
fn has_segment(&self, idx: usize) -> bool {
|
||||
idx < self.assembled_through || matches!(self.assembled_segments.get(idx), Some(Some(_)))
|
||||
}
|
||||
|
||||
/// Append the payload when it is next in order, then any parked payloads
|
||||
/// it unblocks; otherwise park it.
|
||||
fn store(&mut self, idx: usize, data: Vec<u8>) {
|
||||
if idx < self.assembled_through {
|
||||
return;
|
||||
}
|
||||
if idx > self.assembled_through {
|
||||
*Self::slot(&mut self.assembled_segments, idx) = Some(data);
|
||||
return;
|
||||
}
|
||||
let mut next = Some(data);
|
||||
while let Some(data) = next.take() {
|
||||
// Grown as data arrives, never from the peer's segment count.
|
||||
if self.assembled_through == 0 {
|
||||
self.assembled = data;
|
||||
} else {
|
||||
self.assembled.extend_from_slice(&data);
|
||||
}
|
||||
self.assembled_through += 1;
|
||||
next = self
|
||||
.assembled_segments
|
||||
.get_mut(self.assembled_through)
|
||||
.and_then(Option::take);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runtime ingest of an assembled segment at 1-based `segment_index`.
|
||||
/// Errors: `InvalidAdvertisement` for out-of-range index;
|
||||
/// `DuplicateSegment` on overwrite (slot already accepted); `TooLarge`
|
||||
@@ -1238,12 +1275,11 @@ impl MultiSegmentInbound {
|
||||
if self.size_bound.is_some_and(|bound| data_size > bound) {
|
||||
return Err(ResourceError::TooLarge);
|
||||
}
|
||||
let slot = Self::slot(&mut self.assembled_segments, segment_index - 1);
|
||||
if slot.is_some() {
|
||||
if self.has_segment(segment_index - 1) {
|
||||
return Err(ResourceError::DuplicateSegment);
|
||||
}
|
||||
self.data_size = data_size;
|
||||
*slot = Some(data);
|
||||
self.store(segment_index - 1, data);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1258,23 +1294,31 @@ impl MultiSegmentInbound {
|
||||
self.assembled_count() == self.total_segments
|
||||
}
|
||||
|
||||
/// Concatenate every assembled segment into the original payload.
|
||||
/// A copy of the original payload. [`Self::take_reassembled`] moves it.
|
||||
pub fn reassemble(&self) -> Result<Vec<u8>, ResourceError> {
|
||||
if !self.is_complete() {
|
||||
return Err(ResourceError::Incomplete);
|
||||
}
|
||||
let mut result = Vec::new();
|
||||
for seg in &self.assembled_segments {
|
||||
result.extend_from_slice(seg.as_ref().ok_or(ResourceError::Incomplete)?);
|
||||
Ok(self.assembled.clone())
|
||||
}
|
||||
|
||||
/// Move out the original payload, leaving this collector empty.
|
||||
pub fn take_reassembled(&mut self) -> Result<Vec<u8>, ResourceError> {
|
||||
if !self.is_complete() {
|
||||
return Err(ResourceError::Incomplete);
|
||||
}
|
||||
Ok(result)
|
||||
let mut payload = std::mem::take(&mut self.assembled);
|
||||
payload.shrink_to_fit();
|
||||
Ok(payload)
|
||||
}
|
||||
|
||||
pub fn assembled_count(&self) -> usize {
|
||||
self.assembled_segments
|
||||
.iter()
|
||||
.filter(|s| s.is_some())
|
||||
.count()
|
||||
self.assembled_through
|
||||
+ self
|
||||
.assembled_segments
|
||||
.iter()
|
||||
.filter(|s| s.is_some())
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Fraction of segments assembled so far, in `0.0..=1.0`.
|
||||
@@ -4440,6 +4484,32 @@ mod tests {
|
||||
assert_eq!(&blob[4..], &[0xCC; 4]);
|
||||
}
|
||||
|
||||
/// In-order payloads join one buffer as they arrive; a later one waits for
|
||||
/// the gap, and a repeat of either is refused.
|
||||
#[test]
|
||||
fn multi_segment_payloads_join_in_order_as_they_arrive() {
|
||||
let mut inbound = MultiSegmentInbound::new(3, [0x11; 32]);
|
||||
inbound.set_segment_data(1, vec![1; 4]).unwrap();
|
||||
assert_eq!(inbound.assembled, [1; 4]);
|
||||
inbound.set_segment_data(3, vec![3; 2]).unwrap();
|
||||
assert_eq!(inbound.assembled_count(), 2);
|
||||
assert!(matches!(
|
||||
inbound.set_segment_data(1, vec![9]),
|
||||
Err(ResourceError::DuplicateSegment)
|
||||
));
|
||||
assert!(matches!(
|
||||
inbound.set_segment_data(3, vec![9]),
|
||||
Err(ResourceError::DuplicateSegment)
|
||||
));
|
||||
assert!(inbound.take_reassembled().is_err());
|
||||
inbound.set_segment_data(2, vec![2; 4]).unwrap();
|
||||
assert!(inbound.assembled_segments.iter().all(Option::is_none));
|
||||
assert_eq!(
|
||||
inbound.take_reassembled().unwrap(),
|
||||
[vec![1; 4], vec![2; 4], vec![3; 2]].concat()
|
||||
);
|
||||
}
|
||||
|
||||
/// Out-of-range indices (`0` and `> total_segments`) must surface as
|
||||
/// `InvalidAdvertisement`, distinct from the duplicate path.
|
||||
#[test]
|
||||
|
||||
@@ -94,14 +94,13 @@ impl ConfigSection {
|
||||
.find(|key| self.has(key) && self.get_bool(key).is_none())
|
||||
}
|
||||
|
||||
/// Parses like Python `int()`, which ConfigObj `as_int` uses.
|
||||
pub fn get_int(&self, key: &str) -> Option<i64> {
|
||||
let v = self.get(key)?;
|
||||
v.parse().ok()
|
||||
python_number_text(self.get(key)?)?.parse().ok()
|
||||
}
|
||||
|
||||
pub fn get_uint(&self, key: &str) -> Option<u64> {
|
||||
let v = self.get(key)?;
|
||||
v.parse().ok()
|
||||
python_number_text(self.get(key)?)?.parse().ok()
|
||||
}
|
||||
|
||||
/// Parses like Python `float()`, which ConfigObj `as_float` uses.
|
||||
@@ -595,9 +594,15 @@ fn strip_comment(line: &str) -> &str {
|
||||
|
||||
/// Python `float()` also accepts single underscores between digits (PEP 515).
|
||||
fn parse_python_float(s: &str) -> Option<f64> {
|
||||
python_number_text(s)?.parse().ok()
|
||||
}
|
||||
|
||||
/// Number text as Python's `int()` and `float()` read it: surrounding
|
||||
/// whitespace dropped, and `_` allowed only between two digits.
|
||||
fn python_number_text(s: &str) -> Option<std::borrow::Cow<'_, str>> {
|
||||
let s = s.trim();
|
||||
if !s.contains('_') {
|
||||
return s.parse().ok();
|
||||
return Some(s.into());
|
||||
}
|
||||
let bytes = s.as_bytes();
|
||||
let grouped = bytes.iter().enumerate().all(|(i, &b)| {
|
||||
@@ -606,10 +611,7 @@ fn parse_python_float(s: &str) -> Option<f64> {
|
||||
&& bytes[i - 1].is_ascii_digit()
|
||||
&& bytes.get(i + 1).is_some_and(u8::is_ascii_digit))
|
||||
});
|
||||
if !grouped {
|
||||
return None;
|
||||
}
|
||||
s.replace('_', "").parse().ok()
|
||||
grouped.then(|| s.replace('_', "").into())
|
||||
}
|
||||
|
||||
fn parse_bool(s: &str) -> Option<bool> {
|
||||
@@ -796,6 +798,32 @@ const DEFAULT_CONFIG: &str = r#"################################################
|
||||
enabled = Yes
|
||||
"#;
|
||||
|
||||
/// A list file in the config directory as Reticulum.py reads one: the whole
|
||||
/// text stripped and split into lines, each line stripped, `#` lines skipped.
|
||||
/// `None` when the file is absent.
|
||||
pub(crate) fn read_list_file(path: &Path) -> std::io::Result<Option<Vec<String>>> {
|
||||
if !path.is_file() {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(list_file_lines(&std::fs::read_to_string(path)?)))
|
||||
}
|
||||
|
||||
/// Python `str.strip().splitlines()`, then per-line `strip()`.
|
||||
fn list_file_lines(text: &str) -> Vec<String> {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
text.replace("\r\n", "\n")
|
||||
.split([
|
||||
'\n', '\r', '\x0b', '\x0c', '\x1c', '\x1d', '\x1e', '\u{85}', '\u{2028}', '\u{2029}',
|
||||
])
|
||||
.map(str::trim)
|
||||
.filter(|line| !line.starts_with('#'))
|
||||
.map(String::from)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -825,12 +853,50 @@ mod tests {
|
||||
assert!(sec.get_float("k").unwrap().is_nan());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_int_accepts_python_int_syntax() {
|
||||
let mut sec = ConfigSection::new();
|
||||
for (raw, expected) in [
|
||||
("1_0", Some(10)),
|
||||
("1_000_000", Some(1_000_000)),
|
||||
("+4", Some(4)),
|
||||
("-1_2", Some(-12)),
|
||||
(" 7 ", Some(7)),
|
||||
("1__0", None),
|
||||
("_1", None),
|
||||
("1_", None),
|
||||
("1.0", None),
|
||||
("", None),
|
||||
] {
|
||||
sec.set("k", raw);
|
||||
assert_eq!(sec.get_int("k"), expected, "{raw:?}");
|
||||
}
|
||||
sec.set("k", "1_0");
|
||||
assert_eq!(sec.get_uint("k"), Some(10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_empty() {
|
||||
let config = Config::parse("").unwrap();
|
||||
assert!(config.sections.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_files_read_like_upstream() {
|
||||
assert_eq!(
|
||||
list_file_lines("\n# names\n lxmf.delivery \r\n\n#x\nnomadnetwork.node\n\n"),
|
||||
["lxmf.delivery", "", "nomadnetwork.node"]
|
||||
);
|
||||
assert!(list_file_lines(" \n\t").is_empty());
|
||||
let dir = std::env::temp_dir().join(format!("rns-list-file-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("known_destination_types");
|
||||
assert!(read_list_file(&path).unwrap().is_none());
|
||||
std::fs::write(&path, "a.b\n#c.d\n").unwrap();
|
||||
assert_eq!(read_list_file(&path).unwrap().unwrap(), ["a.b"]);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filter_section_follows_upstream_keys() {
|
||||
let config = Config::parse(
|
||||
|
||||
@@ -15,7 +15,7 @@ pub const RPC_AUTH_TAG: &[u8] = b"reticulum_rs_rpc_auth_v1";
|
||||
|
||||
/// The Reticulum release this port follows, where upstream gives
|
||||
/// `RNS.__version__`. It is distinct from this package's release version.
|
||||
pub const RETICULUM_COMPAT_VERSION: &str = "1.6.0";
|
||||
pub const RETICULUM_COMPAT_VERSION: &str = "1.6.1";
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
@@ -52,7 +52,7 @@ fn settings() -> Settings {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The configured process stamp policy, or the 1.6.0 defaults.
|
||||
/// The configured process stamp policy, or the defaults.
|
||||
pub fn policy() -> StampPolicy {
|
||||
settings().policy
|
||||
}
|
||||
@@ -236,6 +236,58 @@ fn stamp_for(job: &Job) -> Option<DestinationStamp> {
|
||||
Some(generated)
|
||||
}
|
||||
|
||||
/// A destination stamp being made ahead of the destination's first announce.
|
||||
/// Dropping it cancels a job that has not finished.
|
||||
pub struct PreparedStamp {
|
||||
rx: mpsc::UnboundedReceiver<StampOutcome>,
|
||||
cancel: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl PreparedStamp {
|
||||
/// The stamp once made and saved; `None` when generation failed or was cancelled.
|
||||
pub async fn ready(mut self) -> Option<DestinationStamp> {
|
||||
self.rx.recv().await.and_then(|outcome| outcome.stamp)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PreparedStamp {
|
||||
fn drop(&mut self) {
|
||||
self.cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Make and save `destination`'s stamp on the stamper worker without
|
||||
/// announcing, so its first announce loads it instead of waiting. `None` when
|
||||
/// the policy does not stamp, the destination already holds a stamp at its
|
||||
/// target, or the queue is full.
|
||||
pub fn prepare(destination: &Destination, identity: &Identity) -> Option<PreparedStamp> {
|
||||
let Settings {
|
||||
policy,
|
||||
storage_dir,
|
||||
} = settings();
|
||||
if !policy.stamp_destinations {
|
||||
return None;
|
||||
}
|
||||
let target = destination.target_value(policy.destination_value);
|
||||
if destination.destination_stamp_meets(target) {
|
||||
return None;
|
||||
}
|
||||
let (reply, rx) = mpsc::unbounded_channel();
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let job = Job {
|
||||
owner: NEXT_OWNER.fetch_add(1, Ordering::Relaxed),
|
||||
destination_hash: destination.hash,
|
||||
material: destination
|
||||
.stamp_material(&identity.get_public_key())
|
||||
.to_vec(),
|
||||
target,
|
||||
storage_dir,
|
||||
cancel: cancel.clone(),
|
||||
reply,
|
||||
};
|
||||
submit(job, Priority::Announce).then_some(PreparedStamp { rx, cancel })
|
||||
}
|
||||
|
||||
/// What to do with a requested announce.
|
||||
pub enum Admission<T> {
|
||||
/// Build and send now, with this extension when stamping is on.
|
||||
@@ -246,12 +298,15 @@ pub enum Admission<T> {
|
||||
Dropped(T),
|
||||
}
|
||||
|
||||
/// Per-destination stamp state for an owner's event loop. Parked path
|
||||
/// responses are kept in order; ordinary announces coalesce to the latest.
|
||||
/// Per-destination stamp state for an owner's event loop, shaped like
|
||||
/// Python's stamp queue: the announce that started the job is in progress and
|
||||
/// leaves first; parked path responses follow in order, then the parked
|
||||
/// announce, which coalesces to the latest.
|
||||
pub struct DestinationStamps<T> {
|
||||
owner: u64,
|
||||
tx: mpsc::UnboundedSender<StampOutcome>,
|
||||
rx: mpsc::UnboundedReceiver<StampOutcome>,
|
||||
in_progress: Option<(T, bool)>,
|
||||
parked_path_responses: VecDeque<T>,
|
||||
parked_announce: Option<T>,
|
||||
job: Option<Arc<AtomicBool>>,
|
||||
@@ -264,6 +319,7 @@ impl<T> Default for DestinationStamps<T> {
|
||||
owner: NEXT_OWNER.fetch_add(1, Ordering::Relaxed),
|
||||
tx,
|
||||
rx,
|
||||
in_progress: None,
|
||||
parked_path_responses: VecDeque::new(),
|
||||
parked_announce: None,
|
||||
job: None,
|
||||
@@ -295,18 +351,16 @@ impl<T> DestinationStamps<T> {
|
||||
if destination.destination_stamp_meets(target) {
|
||||
return Admission::Ready(item, destination.announce_stamp_ext(policy.lr_cost));
|
||||
}
|
||||
if path_response {
|
||||
if self.parked_path_responses.len() >= STAMPER_PR_QUEUE_LENGTH {
|
||||
tracing::debug!(dest = %destination, "stamp queue full, dropping announce");
|
||||
return Admission::Dropped(item);
|
||||
}
|
||||
self.parked_path_responses.push_back(item);
|
||||
} else {
|
||||
self.parked_announce = Some(item);
|
||||
}
|
||||
if self.job.is_some() {
|
||||
if path_response {
|
||||
if self.parked_path_responses.len() >= STAMPER_PR_QUEUE_LENGTH {
|
||||
tracing::debug!(dest = %destination, "stamp queue full, dropping announce");
|
||||
return Admission::Dropped(item);
|
||||
}
|
||||
self.parked_path_responses.push_back(item);
|
||||
promote(self.owner);
|
||||
} else {
|
||||
self.parked_announce = Some(item);
|
||||
}
|
||||
return Admission::Queued;
|
||||
}
|
||||
@@ -322,22 +376,18 @@ impl<T> DestinationStamps<T> {
|
||||
cancel: cancel.clone(),
|
||||
reply: self.tx.clone(),
|
||||
};
|
||||
let priority = if self.parked_path_responses.is_empty() {
|
||||
Priority::Announce
|
||||
} else {
|
||||
let priority = if path_response {
|
||||
Priority::PathResponse
|
||||
} else {
|
||||
Priority::Announce
|
||||
};
|
||||
if submit(job, priority) {
|
||||
self.job = Some(cancel);
|
||||
self.in_progress = Some((item, path_response));
|
||||
return Admission::Queued;
|
||||
}
|
||||
tracing::debug!(dest = %destination, "stamp queue full, dropping announce");
|
||||
let dropped = if path_response {
|
||||
self.parked_path_responses.pop_back()
|
||||
} else {
|
||||
self.parked_announce.take()
|
||||
};
|
||||
Admission::Dropped(dropped.expect("item was parked above"))
|
||||
Admission::Dropped(item)
|
||||
}
|
||||
|
||||
/// Wait for the in-flight job. Cancellation safe.
|
||||
@@ -353,8 +403,9 @@ impl<T> DestinationStamps<T> {
|
||||
self.rx.try_recv().ok()
|
||||
}
|
||||
|
||||
/// Install a finished stamp and release the parked announces, path
|
||||
/// responses first. A failed job cancels them, as `_announce` does.
|
||||
/// Install a finished stamp and release the announce in progress, then the
|
||||
/// parked path responses, then the parked announce. A failed job cancels
|
||||
/// them, as `_announce` does.
|
||||
pub fn complete(
|
||||
&mut self,
|
||||
destination: &mut Destination,
|
||||
@@ -362,9 +413,11 @@ impl<T> DestinationStamps<T> {
|
||||
outcome: StampOutcome,
|
||||
) -> Vec<(T, Option<AnnounceStampExt>)> {
|
||||
self.job = None;
|
||||
let in_progress = self.in_progress.take();
|
||||
let Some((stamp, value)) = outcome.stamp else {
|
||||
let cancelled =
|
||||
self.parked_path_responses.len() + usize::from(self.parked_announce.is_some());
|
||||
let cancelled = usize::from(in_progress.is_some())
|
||||
+ self.parked_path_responses.len()
|
||||
+ usize::from(self.parked_announce.is_some());
|
||||
self.parked_path_responses.clear();
|
||||
self.parked_announce = None;
|
||||
if cancelled > 0 {
|
||||
@@ -374,11 +427,12 @@ impl<T> DestinationStamps<T> {
|
||||
return Vec::new();
|
||||
};
|
||||
destination.set_destination_stamp(stamp, value);
|
||||
let mut parked: Vec<(T, bool)> = self
|
||||
.parked_path_responses
|
||||
.drain(..)
|
||||
.map(|item| (item, true))
|
||||
.collect();
|
||||
let mut parked: Vec<(T, bool)> = in_progress.into_iter().collect();
|
||||
parked.extend(
|
||||
self.parked_path_responses
|
||||
.drain(..)
|
||||
.map(|item| (item, true)),
|
||||
);
|
||||
parked.extend(self.parked_announce.take().map(|item| (item, false)));
|
||||
let mut ready = Vec::new();
|
||||
for (item, path_response) in parked {
|
||||
@@ -439,3 +493,248 @@ pub async fn announce_packet(
|
||||
)
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
/// Tests share the process stamp settings. Each `init` writes them, so starts
|
||||
/// run alongside each other but never alongside a test that holds a guard, and
|
||||
/// leave destination stamping off.
|
||||
#[cfg(test)]
|
||||
pub(crate) mod test_settings {
|
||||
use std::future::Future;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use rns_transport::stamps::StampPolicy;
|
||||
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
||||
|
||||
static LOCK: RwLock<()> = RwLock::const_new(());
|
||||
|
||||
fn unstamped_policy() -> StampPolicy {
|
||||
StampPolicy {
|
||||
stamp_destinations: false,
|
||||
..StampPolicy::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Destination stamping off while held.
|
||||
pub(crate) async fn unstamped() -> RwLockWriteGuard<'static, ()> {
|
||||
let guard = LOCK.write().await;
|
||||
super::configure(unstamped_policy(), None);
|
||||
guard
|
||||
}
|
||||
|
||||
pub(crate) fn blocking_unstamped() -> RwLockWriteGuard<'static, ()> {
|
||||
blocking_exclusive(unstamped_policy(), None)
|
||||
}
|
||||
|
||||
/// These settings while held.
|
||||
pub(crate) fn blocking_exclusive(
|
||||
policy: StampPolicy,
|
||||
storage_dir: Option<PathBuf>,
|
||||
) -> RwLockWriteGuard<'static, ()> {
|
||||
let guard = LOCK.blocking_write();
|
||||
super::configure(policy, storage_dir);
|
||||
guard
|
||||
}
|
||||
|
||||
/// Held across a start; dropping it leaves destination stamping off.
|
||||
pub(crate) struct Starting {
|
||||
_guard: RwLockReadGuard<'static, ()>,
|
||||
}
|
||||
|
||||
impl Drop for Starting {
|
||||
fn drop(&mut self) {
|
||||
super::configure(unstamped_policy(), None);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn starting() -> Starting {
|
||||
Starting {
|
||||
_guard: LOCK.read().await,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn around_init<F: Future>(init: F) -> F::Output {
|
||||
let _starting = starting().await;
|
||||
init.await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rns_identity::destination::DestType;
|
||||
|
||||
#[test]
|
||||
fn default_policy_holds_announces_until_a_stamp_meets_the_target() {
|
||||
let _settings = test_settings::blocking_exclusive(StampPolicy::default(), None);
|
||||
let identity = Identity::new();
|
||||
let mut destination = Destination::new(
|
||||
Some(&identity),
|
||||
Direction::In,
|
||||
DestType::Single,
|
||||
"test.default.stamping",
|
||||
)
|
||||
.unwrap();
|
||||
let mut stamps = DestinationStamps::new();
|
||||
assert!(matches!(
|
||||
stamps.admit(&destination, &identity, false, 1u8),
|
||||
Admission::Queued
|
||||
));
|
||||
drop(stamps);
|
||||
|
||||
destination.set_destination_stamp([7; NETWORK_STAMP_SIZE], 24.5);
|
||||
let mut stamps = DestinationStamps::new();
|
||||
assert!(matches!(
|
||||
stamps.admit(&destination, &identity, false, 2u8),
|
||||
Admission::Queued
|
||||
));
|
||||
drop(stamps);
|
||||
|
||||
destination.set_destination_stamp([7; NETWORK_STAMP_SIZE], 25.0);
|
||||
let mut stamps = DestinationStamps::new();
|
||||
let Admission::Ready(3u8, Some(ext)) = stamps.admit(&destination, &identity, false, 3u8)
|
||||
else {
|
||||
panic!("a held stamp at the target announces at once");
|
||||
};
|
||||
assert_eq!(ext.stamp, [7; NETWORK_STAMP_SIZE]);
|
||||
assert_eq!(ext.lr_cost, 12.5);
|
||||
}
|
||||
|
||||
fn quick_policy() -> StampPolicy {
|
||||
StampPolicy {
|
||||
destination_cost: 6.0,
|
||||
destination_value: 8.0,
|
||||
..StampPolicy::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn scratch_dir(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("rns-prepare-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// Python's stamper finishes the announce it is generating for before it
|
||||
/// takes a queued path response, so a registration path response cannot
|
||||
/// overtake the application's own first announce.
|
||||
#[test]
|
||||
fn the_announce_that_started_a_stamp_leaves_first() {
|
||||
let _settings = test_settings::blocking_exclusive(quick_policy(), None);
|
||||
let identity = Identity::new();
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.build()
|
||||
.unwrap();
|
||||
for (first, second) in [
|
||||
((false, "announce"), (true, "path response")),
|
||||
((true, "path response"), (false, "announce")),
|
||||
] {
|
||||
let mut destination = Destination::new(
|
||||
Some(&identity),
|
||||
Direction::In,
|
||||
DestType::Single,
|
||||
"test.stamp.order",
|
||||
)
|
||||
.unwrap();
|
||||
let mut stamps = DestinationStamps::new();
|
||||
for (path_response, name) in [first, second] {
|
||||
assert!(matches!(
|
||||
stamps.admit(&destination, &identity, path_response, name),
|
||||
Admission::Queued
|
||||
));
|
||||
}
|
||||
let outcome = runtime.block_on(stamps.recv());
|
||||
let order: Vec<_> = stamps
|
||||
.complete(&mut destination, &identity, outcome)
|
||||
.into_iter()
|
||||
.map(|(name, _)| name)
|
||||
.collect();
|
||||
assert_eq!(order, [first.1, second.1]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_saves_a_stamp_the_first_announce_loads_without_waiting() {
|
||||
let dir = scratch_dir("saves");
|
||||
let _settings = test_settings::blocking_exclusive(quick_policy(), Some(dir.clone()));
|
||||
let identity = Identity::new();
|
||||
let app = "test.prepare.saves";
|
||||
let destination =
|
||||
Destination::new(Some(&identity), Direction::In, DestType::Single, app).unwrap();
|
||||
let prepared = prepare(&destination, &identity).expect("a stamp to make");
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.build()
|
||||
.unwrap();
|
||||
let (_, value) = runtime.block_on(prepared.ready()).expect("made");
|
||||
assert!(value >= 8.0);
|
||||
|
||||
// A destination built after it loads the saved stamp and announces at once.
|
||||
let mut later =
|
||||
Destination::new(Some(&identity), Direction::In, DestType::Single, app).unwrap();
|
||||
load_stored_stamp(&mut later, &identity);
|
||||
assert!(matches!(
|
||||
DestinationStamps::new().admit(&later, &identity, false, ()),
|
||||
Admission::Ready((), Some(_))
|
||||
));
|
||||
assert!(prepare(&later, &identity).is_none(), "nothing left to make");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stamp_made_before_the_network_starts_is_saved_where_init_loads_it() {
|
||||
let _settings = test_settings::blocking_unstamped();
|
||||
let dir = scratch_dir("early");
|
||||
std::fs::write(
|
||||
dir.join("config"),
|
||||
"[stamps]\n destination_value = 8\n destination_cost = 6\n",
|
||||
)
|
||||
.unwrap();
|
||||
let configdir = dir.to_str().unwrap();
|
||||
crate::reticulum::configure_destination_stamper(
|
||||
Some(configdir),
|
||||
&crate::reticulum::InitOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(policy().destination_value, 8.0);
|
||||
let identity = Identity::new();
|
||||
let app = "test.prepare.early";
|
||||
let destination =
|
||||
Destination::new(Some(&identity), Direction::In, DestType::Single, app).unwrap();
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.build()
|
||||
.unwrap();
|
||||
runtime
|
||||
.block_on(prepare(&destination, &identity).unwrap().ready())
|
||||
.unwrap();
|
||||
let material = destination.stamp_material(&identity.get_public_key());
|
||||
assert!(
|
||||
load_destination_stamp(&dir.join("storage"), &destination.hash, &material, 6.0)
|
||||
.is_some()
|
||||
);
|
||||
|
||||
// Without a config the defaults apply, and none is written.
|
||||
let bare = scratch_dir("bare");
|
||||
crate::reticulum::configure_destination_stamper(
|
||||
bare.to_str(),
|
||||
&crate::reticulum::InitOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(policy().destination_value, 25.0);
|
||||
assert!(!bare.join("config").exists());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
let _ = std::fs::remove_dir_all(bare);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_does_nothing_when_destinations_are_not_stamped() {
|
||||
let _settings = test_settings::blocking_unstamped();
|
||||
let identity = Identity::new();
|
||||
let destination = Destination::new(
|
||||
Some(&identity),
|
||||
Direction::In,
|
||||
DestType::Single,
|
||||
"test.prepare.unstamped",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(prepare(&destination, &identity).is_none());
|
||||
}
|
||||
}
|
||||
@@ -315,6 +315,9 @@ pub struct BackboneInterfaceConfig {
|
||||
/// Listener-only block duration. The configuration file uses minutes;
|
||||
/// the runtime field is a `Duration`. Parser default: 720 minutes.
|
||||
pub fast_flapping_block_time: Duration,
|
||||
/// Listener-only `client_limit`: absent or 0 means 500, and a negative
|
||||
/// value refuses every client, as Python's `len(spawned) >= limit` does.
|
||||
pub client_limit: u64,
|
||||
/// Bitrate the hardware MTU is optimised for. Parser default: the Backbone guess.
|
||||
pub bitrate: u64,
|
||||
/// IFAC size in bytes a frame may add to the hardware MTU.
|
||||
@@ -396,7 +399,6 @@ fn parse_uint_strict(
|
||||
}
|
||||
|
||||
/// Python `int(c[field])`: a non-integer is a config error (Python raises).
|
||||
#[cfg(feature = "serial")]
|
||||
fn parse_int_strict(
|
||||
name: &str,
|
||||
field: &str,
|
||||
@@ -1944,6 +1946,10 @@ fn synthesize_backbone(
|
||||
60.0,
|
||||
rns_interface::backbone::FAST_FLAPPING_BLOCK_TIME,
|
||||
)?;
|
||||
let client_limit = match parse_int_strict(name, "client_limit", section, 0)? {
|
||||
0 => rns_interface::backbone::CLIENT_LIMIT,
|
||||
limit => u64::try_from(limit).unwrap_or(0),
|
||||
};
|
||||
let post_init = InterfacePostInit::try_from_section(section)?.with_default_ifac_size(16);
|
||||
let (bitrate, ifac_size) =
|
||||
receive_sizing(section, &post_init, rns_interface::backbone::BITRATE_GUESS);
|
||||
@@ -1963,6 +1969,7 @@ fn synthesize_backbone(
|
||||
fast_flapping_threshold,
|
||||
fast_flapping_grace,
|
||||
fast_flapping_block_time,
|
||||
client_limit,
|
||||
bitrate,
|
||||
ifac_size,
|
||||
}))
|
||||
@@ -2009,6 +2016,9 @@ pub struct InterfacePostInit {
|
||||
/// Serial, KISS, AX.25 KISS, RNode and RNodeMulti interfaces never hold
|
||||
/// announces in Python; they override `should_ingress_limit`.
|
||||
pub announce_ingress_exempt: bool,
|
||||
/// The interface classes Python marks `shared_medium`: Serial, KISS,
|
||||
/// AX.25 KISS, RNode (every port), RNodeMulti, UDP and Pipe.
|
||||
pub shared_medium: bool,
|
||||
/// Per-interface ingress/egress overrides parsed from `ic_*`, `ec_pr_freq`
|
||||
/// and `egress_control` settings.
|
||||
pub ingress_overrides: rns_transport::ingress::IngressOverrides,
|
||||
@@ -2024,6 +2034,12 @@ pub struct InterfacePostInit {
|
||||
pub announces_to_internal: Option<bool>,
|
||||
/// Configured `gravity`; `None` takes `[reticulum] default_gravity`.
|
||||
pub gravity: Option<i64>,
|
||||
/// Configured `hop_limiter`, clamped to `0..=PATHFINDER_M`; 0 is `None`, off.
|
||||
pub hop_limiter: Option<u8>,
|
||||
/// Whether connections this interface accepts copy `hop_limiter`: TCP
|
||||
/// server, Backbone and I2P listeners do, AutoInterface peers do not
|
||||
/// (TCPInterface.py, BackboneInterface.py, I2PInterface.py).
|
||||
pub spawned_hop_limiter: bool,
|
||||
/// Required announce stamp value on this interface, clamped to the stamp
|
||||
/// cost cap. `None` follows the global `[stamps] destination_cost`.
|
||||
pub destination_cost: Option<f64>,
|
||||
@@ -2112,11 +2128,30 @@ impl InterfacePostInit {
|
||||
| "RNodeMultiInterface"
|
||||
)
|
||||
),
|
||||
shared_medium: matches!(
|
||||
section.get("type"),
|
||||
Some(
|
||||
"SerialInterface"
|
||||
| "KISSInterface"
|
||||
| "AX25KISSInterface"
|
||||
| "RNodeInterface"
|
||||
| "RNodeMultiInterface"
|
||||
| "UDPInterface"
|
||||
| "PipeInterface"
|
||||
)
|
||||
),
|
||||
ingress_overrides,
|
||||
recursive_prs,
|
||||
announces_from_internal,
|
||||
announces_to_internal: config_bool(section, "announces_to_internal")?,
|
||||
gravity: config_int(section, "gravity")?,
|
||||
hop_limiter: config_int(section, "hop_limiter")?
|
||||
.map(rns_transport::destination_filter::FilterPolicy::clamp_hop_limiter)
|
||||
.filter(|limit| *limit > 0),
|
||||
spawned_hop_limiter: matches!(
|
||||
section.get("type"),
|
||||
Some("TCPServerInterface" | "BackboneInterface" | "I2PInterface")
|
||||
),
|
||||
destination_cost: section
|
||||
.get_float("destination_cost")
|
||||
.map(rns_transport::stamps::StampPolicy::clamp_cost),
|
||||
@@ -2170,6 +2205,33 @@ pub fn default_ifac_size_for(config: &InterfaceConfig) -> usize {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
/// The classes that set `shared_medium = True` in Python 1.6.1
|
||||
/// (`RNS/Interfaces/*.py`); the base class leaves it false.
|
||||
#[test]
|
||||
fn shared_medium_follows_the_python_interface_class() {
|
||||
for (kind, shared) in [
|
||||
("SerialInterface", true),
|
||||
("KISSInterface", true),
|
||||
("AX25KISSInterface", true),
|
||||
("RNodeInterface", true),
|
||||
("RNodeMultiInterface", true),
|
||||
("UDPInterface", true),
|
||||
("PipeInterface", true),
|
||||
("TCPClientInterface", false),
|
||||
("TCPServerInterface", false),
|
||||
("BackboneInterface", false),
|
||||
("BackboneClientInterface", false),
|
||||
("AutoInterface", false),
|
||||
("LocalInterface", false),
|
||||
("I2PInterface", false),
|
||||
] {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", kind);
|
||||
let post_init = InterfacePostInit::try_from_section(§ion).unwrap();
|
||||
assert_eq!(post_init.shared_medium, shared, "{kind}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serial")]
|
||||
#[test]
|
||||
fn android_usb_serial_ports_are_refused_off_android() {
|
||||
@@ -3700,11 +3762,41 @@ mod tests {
|
||||
assert_eq!(c.fast_flapping_threshold, Duration::from_secs(20));
|
||||
assert_eq!(c.fast_flapping_grace, 5);
|
||||
assert_eq!(c.fast_flapping_block_time, Duration::from_secs(720 * 60));
|
||||
assert_eq!(c.client_limit, 500);
|
||||
}
|
||||
_ => panic!("expected Backbone"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `int(c["client_limit"]) or CLIENT_LIMIT` (BackboneInterface.py:140,
|
||||
/// :160): 0 is the default, and a negative limit refuses every client.
|
||||
#[test]
|
||||
fn test_synthesize_backbone_client_limit() {
|
||||
for (value, expected) in [
|
||||
("0", Some(500)),
|
||||
("12", Some(12)),
|
||||
(" 7 ", Some(7)),
|
||||
("-3", Some(0)),
|
||||
("1.5", None),
|
||||
("many", None),
|
||||
] {
|
||||
let mut section = enabled_section();
|
||||
section.set("type", "BackboneInterface");
|
||||
section.set("listen_on", "0.0.0.0");
|
||||
section.set("port", "4242");
|
||||
section.set("client_limit", value);
|
||||
match (synthesize_interface("backbone_limit", §ion), expected) {
|
||||
(Ok(InterfaceConfig::Backbone(c)), Some(limit)) => {
|
||||
assert_eq!(c.client_limit, limit, "{value}")
|
||||
}
|
||||
(Err(InterfaceFactoryError::InvalidValue { field, .. }), None) => {
|
||||
assert_eq!(field, "backbone_limit.client_limit")
|
||||
}
|
||||
(other, _) => panic!("client_limit={value}: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_synthesize_backbone_fast_flap_overrides_allow_fractions() {
|
||||
let mut section = enabled_section();
|
||||
@@ -4128,14 +4220,15 @@ mod tests {
|
||||
crate::lifecycle::ShutdownSignal,
|
||||
) {
|
||||
let shutdown = crate::lifecycle::ShutdownSignal::new();
|
||||
let handle = crate::reticulum::init(
|
||||
Some(dir.path().to_str().unwrap()),
|
||||
Some(dir.path().join("sockets")),
|
||||
shutdown.clone(),
|
||||
std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let handle =
|
||||
crate::destination_stamper::test_settings::around_init(crate::reticulum::init(
|
||||
Some(dir.path().to_str().unwrap()),
|
||||
Some(dir.path().join("sockets")),
|
||||
shutdown.clone(),
|
||||
std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
(handle, shutdown)
|
||||
}
|
||||
|
||||
|
||||
@@ -53,6 +53,13 @@ impl InterfaceKind {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runtime-spawned radios and the BLE peer mesh share their medium; every
|
||||
/// other directly registered interface (TCP, Backbone, I2P, Local and
|
||||
/// Auto peers, listener children) does not (Python `shared_medium`).
|
||||
pub(crate) fn shared_medium(self) -> bool {
|
||||
self != Self::Standard
|
||||
}
|
||||
|
||||
fn requires_exact_driver(self) -> bool {
|
||||
match self {
|
||||
#[cfg(feature = "ble")]
|
||||
@@ -1691,4 +1698,19 @@ mod tests {
|
||||
InterfaceShutdownStrategy::ExactRNodeDriver
|
||||
);
|
||||
}
|
||||
|
||||
/// The BLE peer mesh is one interface whose peers cannot hear each other,
|
||||
/// so it must keep rebroadcasting what one of them sent.
|
||||
#[test]
|
||||
fn only_standard_registrations_are_off_a_shared_medium() {
|
||||
assert!(!InterfaceKind::Standard.shared_medium());
|
||||
#[cfg(feature = "ble")]
|
||||
assert!(InterfaceKind::BlePeer.shared_medium() && InterfaceKind::BleRNode.shared_medium());
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
assert!(InterfaceKind::RNode.shared_medium());
|
||||
#[cfg(feature = "serial")]
|
||||
assert!(InterfaceKind::RNodeMulti.shared_medium());
|
||||
#[cfg(target_os = "android")]
|
||||
assert!(InterfaceKind::AndroidUsbRNode.shared_medium());
|
||||
}
|
||||
}
|
||||
@@ -4731,7 +4731,7 @@ impl LinkManager {
|
||||
if coordinator.is_complete() {
|
||||
let total_segments = coordinator.total_segments;
|
||||
coordinator
|
||||
.reassemble()
|
||||
.take_reassembled()
|
||||
.map(|blob| {
|
||||
Some((
|
||||
blob,
|
||||
@@ -9799,6 +9799,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn path_response_announce_request_sends_attached_path_response() {
|
||||
let _stamps = crate::destination_stamper::test_settings::blocking_unstamped();
|
||||
let (tx, mut rx) = mpsc::channel(16);
|
||||
let (_event_tx, event_rx) = mpsc::channel(16);
|
||||
|
||||
@@ -9864,6 +9865,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn path_response_announce_retries_after_transport_ingress_saturation() {
|
||||
let _stamps = crate::destination_stamper::test_settings::blocking_unstamped();
|
||||
let (tx, mut rx) = mpsc::channel(1);
|
||||
tx.try_send(TransportMessage::DeregisterDestination { hash: [0x44; 16] })
|
||||
.unwrap();
|
||||
@@ -9912,6 +9914,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn path_response_announces_carry_default_app_data() {
|
||||
let _stamps = crate::destination_stamper::test_settings::blocking_unstamped();
|
||||
let (tx, mut rx) = mpsc::channel(16);
|
||||
let (_event_tx, event_rx) = mpsc::channel(16);
|
||||
|
||||
@@ -9969,6 +9972,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn destination_commands_announce_and_change_link_acceptance() {
|
||||
let _stamps = crate::destination_stamper::test_settings::blocking_unstamped();
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(16);
|
||||
let (_event_tx, event_rx) = mpsc::channel(16);
|
||||
let identity = Identity::new();
|
||||
@@ -10027,6 +10031,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn default_announce_command_uses_owned_destination() {
|
||||
let _stamps = crate::destination_stamper::test_settings::blocking_unstamped();
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(16);
|
||||
let (_event_tx, event_rx) = mpsc::channel(16);
|
||||
let identity = Identity::new();
|
||||
|
||||
@@ -3552,7 +3552,7 @@ async fn complete_inbound_segment(
|
||||
coordinator.set_metadata(metadata);
|
||||
}
|
||||
if coordinator.is_complete() {
|
||||
match coordinator.reassemble() {
|
||||
match coordinator.take_reassembled() {
|
||||
Ok(data) => {
|
||||
complete_data = Some(data);
|
||||
complete_metadata = coordinator.metadata.take();
|
||||
|
||||
@@ -714,6 +714,7 @@ mod tests {
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn responder_sends_attached_path_response_announce() {
|
||||
let _stamps = crate::destination_stamper::test_settings::unstamped().await;
|
||||
let (tx, mut rx) = mpsc::channel::<TransportMessage>(16);
|
||||
|
||||
let identity = Identity::new();
|
||||
|
||||
@@ -194,9 +194,11 @@ fn handle_path(tx: &mpsc::Sender<TransportMessage>, data: &[u8]) -> Option<Vec<u
|
||||
hops: e.hops,
|
||||
expires: e.expires,
|
||||
value: e.value,
|
||||
used: e.used,
|
||||
used: Some(e.used),
|
||||
lr_cost: e.lr_cost,
|
||||
interface: e.interface,
|
||||
interface_hash: Some(e.interface_hash.to_vec()),
|
||||
state: Some(e.state as u8),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -455,6 +457,8 @@ mod tests {
|
||||
entry.used = 0.0;
|
||||
entry.lr_cost = None;
|
||||
entry.interface = "MockIf".to_string();
|
||||
entry.interface_hash = rns_crypto::sha::sha256(b"MockIf");
|
||||
entry.state = rns_transport::constants::PathState::Responsive;
|
||||
entry.interface_id = 1;
|
||||
entry.interface_mode =
|
||||
rns_transport::constants::InterfaceMode::Full;
|
||||
@@ -754,6 +758,29 @@ mod tests {
|
||||
.1
|
||||
.as_u64();
|
||||
assert_eq!(hops, Some(2));
|
||||
// Transport.py 1.6.1: remote `/path` uses get_path_table's keys.
|
||||
let keys: Vec<&str> = entry.iter().filter_map(|(k, _)| k.as_str()).collect();
|
||||
assert_eq!(
|
||||
keys,
|
||||
[
|
||||
"hash",
|
||||
"timestamp",
|
||||
"via",
|
||||
"hops",
|
||||
"expires",
|
||||
"value",
|
||||
"used",
|
||||
"lr_cost",
|
||||
"interface",
|
||||
"interface_hash",
|
||||
"state"
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
entry[9].1.as_slice(),
|
||||
Some(&rns_crypto::sha::sha256(b"MockIf")[..])
|
||||
);
|
||||
assert_eq!(entry[10].1.as_u64(), Some(2));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -74,10 +74,18 @@ async fn start_two_unreachable_clients(
|
||||
client("Reachable", "127.0.0.1", port),
|
||||
),
|
||||
);
|
||||
// Time the start alone, not the wait for the stamp settings.
|
||||
let _starting = crate::destination_stamper::test_settings::starting().await;
|
||||
let started = std::time::Instant::now();
|
||||
let handle = start(&dir, options)
|
||||
.await
|
||||
.expect("unreachable servers do not fail start-up");
|
||||
let handle = super::super::init_with_options(
|
||||
Some(dir.to_str().unwrap()),
|
||||
None,
|
||||
ShutdownSignal::new(),
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
options,
|
||||
)
|
||||
.await
|
||||
.expect("unreachable servers do not fail start-up");
|
||||
let elapsed = started.elapsed();
|
||||
assert!(
|
||||
handle.startup_interface_failures().is_empty(),
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
//! Runtime wiring for the path table and traffic filters: the config
|
||||
//! directory's list files, per-interface hop limits and filter registrations.
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn config_dir_type_lists_fill_the_filter_policy() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(
|
||||
dir.path().join("known_destination_types"),
|
||||
"# known\nlxmf.delivery\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(dir.path().join("flagged_destination_types"), "spam.type\n").unwrap();
|
||||
let mut rc = ReticulumConfig::default();
|
||||
load_config_dir_lists(dir.path(), &mut rc);
|
||||
assert_eq!(rc.filter.known_types, ["lxmf.delivery"]);
|
||||
assert_eq!(rc.filter.flagged_types, ["spam.type"]);
|
||||
|
||||
let empty = tempfile::tempdir().unwrap();
|
||||
let mut rc = ReticulumConfig::default();
|
||||
load_config_dir_lists(empty.path(), &mut rc);
|
||||
assert!(rc.filter.known_types.is_empty() && rc.filter.flagged_types.is_empty());
|
||||
}
|
||||
|
||||
fn post_init(kind: &str, hop_limiter: &str) -> interface_factory::InterfacePostInit {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", kind);
|
||||
section.set("hop_limiter", hop_limiter);
|
||||
interface_factory::InterfacePostInit::try_from_section(§ion).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hop_limiter_parses_like_upstream() {
|
||||
for (value, expected) in [
|
||||
("3", Some(3)),
|
||||
("300", Some(128)),
|
||||
("0", None),
|
||||
("-2", None),
|
||||
] {
|
||||
assert_eq!(
|
||||
post_init("TCPClientInterface", value).hop_limiter,
|
||||
expected,
|
||||
"{value}"
|
||||
);
|
||||
}
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("hop_limiter", "many");
|
||||
assert!(interface_factory::InterfacePostInit::try_from_section(§ion).is_err());
|
||||
for (kind, spawned) in [
|
||||
("TCPServerInterface", true),
|
||||
("BackboneInterface", true),
|
||||
("I2PInterface", true),
|
||||
("AutoInterface", false),
|
||||
("RNodeMultiInterface", false),
|
||||
] {
|
||||
assert_eq!(post_init(kind, "3").spawned_hop_limiter, spawned, "{kind}");
|
||||
}
|
||||
}
|
||||
|
||||
async fn registered_hop_limiter(transport_rx: &mut mpsc::Receiver<TransportMessage>) -> Option<u8> {
|
||||
let msg = transport_rx
|
||||
.recv()
|
||||
.await
|
||||
.map(unwrap_owned_event)
|
||||
.expect("registration");
|
||||
let TransportMessage::RegisterInterface { entry, .. } = msg else {
|
||||
panic!("expected RegisterInterface");
|
||||
};
|
||||
entry.hop_limiter
|
||||
}
|
||||
|
||||
/// Reticulum.py sets `hop_limiter` on the configured interface; TCP server,
|
||||
/// Backbone and I2P listeners copy it to accepted connections, while
|
||||
/// AutoInterface peers, RNodeMulti subinterfaces and configured I2P peers
|
||||
/// go without (bb63dd44).
|
||||
#[tokio::test]
|
||||
async fn hop_limiter_reaches_the_interfaces_upstream_gives_it() {
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel::<TransportMessage>(4);
|
||||
let interface_controls: InterfaceControlMap = Arc::new(std::sync::Mutex::new(HashMap::new()));
|
||||
let interface_registry = InterfaceRegistry::default();
|
||||
for (parent_id, kind, child_limit) in [
|
||||
(940_001, "TCPServerInterface", Some(3)),
|
||||
(940_011, "AutoInterface", None),
|
||||
] {
|
||||
register_interface_with_post_init(
|
||||
&transport_tx,
|
||||
test_interface_handle(parent_id, None, kind),
|
||||
&post_init(kind, "3"),
|
||||
None,
|
||||
&interface_controls,
|
||||
&interface_registry,
|
||||
InterfaceKind::Standard,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
registered_hop_limiter(&mut transport_rx).await,
|
||||
Some(3),
|
||||
"{kind}"
|
||||
);
|
||||
|
||||
let (role, inherited, ifac_key, ifac_size) =
|
||||
child_registration_from_parent(&interface_controls, Some(parent_id));
|
||||
register_interface_handle_with_role_and_overrides(
|
||||
&transport_tx,
|
||||
test_interface_handle(parent_id + 1, Some(parent_id), "child"),
|
||||
role,
|
||||
inherited,
|
||||
ifac_key,
|
||||
ifac_size,
|
||||
&interface_controls,
|
||||
&interface_registry,
|
||||
InterfaceKind::Standard,
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
registered_hop_limiter(&mut transport_rx).await,
|
||||
child_limit,
|
||||
"{kind}"
|
||||
);
|
||||
}
|
||||
|
||||
register_interface_with_post_init(
|
||||
&transport_tx,
|
||||
test_interface_handle(940_021, Some(940_020), "RNodeMulti subinterface"),
|
||||
&post_init("RNodeMultiInterface", "3"),
|
||||
None,
|
||||
&interface_controls,
|
||||
&interface_registry,
|
||||
InterfaceKind::Standard,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(registered_hop_limiter(&mut transport_rx).await, None);
|
||||
|
||||
register_owned_interface_with_post_init(
|
||||
&transport_tx,
|
||||
OwnedInterfaceHandle {
|
||||
configured_peer: true,
|
||||
..test_interface_handle(940_031, None, "I2P to peer").into()
|
||||
},
|
||||
&post_init("I2PInterface", "3"),
|
||||
None,
|
||||
&interface_controls,
|
||||
&interface_registry,
|
||||
InterfaceKind::Standard,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(registered_hop_limiter(&mut transport_rx).await, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocked_ips_lines_parse_like_upstream() {
|
||||
let lines: Vec<String> = [
|
||||
"198.51.100.7",
|
||||
"2001:db8::1",
|
||||
"0:0:0:0:0:0:0:1",
|
||||
"198.51.100.0/24",
|
||||
"example.org",
|
||||
"198.51.100.8 # spammer",
|
||||
"",
|
||||
]
|
||||
.map(String::from)
|
||||
.into();
|
||||
let parsed: Vec<String> = parse_blocked_ips(&lines)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect();
|
||||
assert_eq!(parsed, ["198.51.100.7", "2001:db8::1", "::1"]);
|
||||
}
|
||||
|
||||
/// Discovery.py 1.6.1 (884f109b): the receiver wants its announce type, so
|
||||
/// `required_only` does not drop discovery announces.
|
||||
#[tokio::test]
|
||||
async fn interface_discovery_registers_its_announce_type() {
|
||||
let (mut handle, _actor) = discovery_actor();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
handle
|
||||
.install_discovery_store_for_tests(Arc::new(DiscoveryStore::open(dir.path()).unwrap()))
|
||||
.await;
|
||||
handle.config.discover_interfaces = true;
|
||||
handle
|
||||
.enable_on_network_discovery(Arc::new(StaticStamper))
|
||||
.await;
|
||||
assert!(
|
||||
handle
|
||||
.unwants_destination_type(rns_transport::discovery::constants::DISCOVERY_ASPECT_FILTER)
|
||||
.await
|
||||
);
|
||||
}
|
||||
|
||||
/// A shared instance's path table keeps 1.6.1's keys; a 1.6.0 instance's
|
||||
/// hash is upstream's, of the interface string.
|
||||
#[test]
|
||||
fn shared_instance_path_tables_carry_interface_hash_and_state() {
|
||||
let entry = |interface_hash: Option<Vec<u8>>, state| crate::rpc::PathTableEntry {
|
||||
hash: vec![0x51; 16],
|
||||
timestamp: 1.0,
|
||||
via: None,
|
||||
hops: 1,
|
||||
expires: 2.0,
|
||||
value: None,
|
||||
used: Some(0.0),
|
||||
lr_cost: None,
|
||||
interface: "TCPInterface[test]".into(),
|
||||
interface_hash,
|
||||
state,
|
||||
};
|
||||
let response = crate::rpc::RpcResponse::PathTable(vec![
|
||||
entry(Some(vec![0x77; 32]), Some(1)),
|
||||
entry(None, None),
|
||||
]);
|
||||
let Some(TransportQueryResponse::PathTable(entries)) =
|
||||
rpc_response_to_transport_response(response)
|
||||
else {
|
||||
panic!("expected a path table");
|
||||
};
|
||||
assert_eq!(entries[0].interface_hash, [0x77; 32]);
|
||||
assert_eq!(
|
||||
entries[0].state,
|
||||
rns_transport::constants::PathState::Unresponsive
|
||||
);
|
||||
assert_eq!(
|
||||
entries[1].interface_hash,
|
||||
rns_crypto::sha::sha256(b"TCPInterface[test]")
|
||||
);
|
||||
assert_eq!(
|
||||
entries[1].state,
|
||||
rns_transport::constants::PathState::Unknown
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Runtime wiring for tunnel synthesis, server interface ids and accepted
|
||||
//! clients' routing state, observed from the wire and the public handle.
|
||||
use super::*;
|
||||
use rns_transport::messages::InterfaceStatRpcEntry;
|
||||
use rns_transport::messages::{DetachReason, InterfaceStatRpcEntry};
|
||||
use rns_transport::path_table::{PathEntry, PathTable};
|
||||
use rns_transport::tunnel::TunnelSynthesisData;
|
||||
use rns_wire::context::PacketContext;
|
||||
@@ -855,22 +855,26 @@ fn synthesis_in(frame: &[u8]) -> Option<TunnelSynthesisData> {
|
||||
&& header.flags.destination_type == DestinationType::Plain
|
||||
&& header.flags.packet_type == PacketType::Data
|
||||
&& header.hops == 0
|
||||
&& header.context == PacketContext::None
|
||||
&& frame.len() == offset + 176;
|
||||
&& header.context == PacketContext::None;
|
||||
shape
|
||||
.then(|| TunnelSynthesisData::unpack(&frame[offset..]))
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Python 1.6.1 signs the extension too, and a Rust node sends it always.
|
||||
fn assert_signed(synthesis: &TunnelSynthesisData) {
|
||||
let signer = Identity::from_public_key(&synthesis.public_key).unwrap();
|
||||
let mut signed = synthesis.public_key.to_vec();
|
||||
signed.extend_from_slice(&synthesis.interface_hash);
|
||||
signed.extend_from_slice(&synthesis.random_hash);
|
||||
signed.extend_from_slice(&synthesis.ext);
|
||||
assert!(
|
||||
signer.verify(&signed, &synthesis.signature),
|
||||
"the synthesis verifies under its own Ed25519 key"
|
||||
);
|
||||
let ext = rns_transport::tunnel::RemoteTransportInfo::decode(&synthesis.ext)
|
||||
.expect("an extended synthesis");
|
||||
assert_eq!(ext.implementation, "rsRNS");
|
||||
}
|
||||
|
||||
/// Python `Interface.get_hash()`: the full hash of `str(interface)`.
|
||||
@@ -1177,6 +1181,7 @@ async fn a_rust_hub_restores_a_reconnecting_rust_clients_paths() {
|
||||
.is_some(),
|
||||
"the client connects"
|
||||
);
|
||||
let _stamps = crate::destination_stamper::test_settings::unstamped().await;
|
||||
let destination = client
|
||||
.register_destination(
|
||||
Identity::new(),
|
||||
@@ -1211,3 +1216,325 @@ async fn a_rust_hub_restores_a_reconnecting_rust_clients_paths() {
|
||||
let _ = std::fs::remove_dir_all(client_dir);
|
||||
let _ = std::fs::remove_dir_all(hub_dir);
|
||||
}
|
||||
|
||||
fn hub_answer(identity: &Identity) -> Vec<u8> {
|
||||
rns_transport::tunnel::build_tunnel_synthesis_packet_with_ext(
|
||||
identity,
|
||||
python_interface_hash("TCPInterface[Client on Hub/127.0.0.1:4242]"),
|
||||
&rns_transport::tunnel::TunnelExt::local(true, 23.5, 15.8),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn tcp_client_config(port: u16) -> String {
|
||||
format!(
|
||||
"[reticulum]\n share_instance = No\n\n[interfaces]\n [[Uplink]]\n type = TCPClientInterface\n enabled = yes\n target_host = 127.0.0.1\n target_port = {port}\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// A Rust client learns its hub from the hub's answer, and its own synthesis
|
||||
/// names the tunnel (Transport.py:3205, :3290-3292).
|
||||
#[tokio::test]
|
||||
async fn a_tcp_client_records_the_hub_that_answers_its_synthesis() {
|
||||
let hub = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = hub.local_addr().unwrap().port();
|
||||
let dir = config_dir("tcp-answer", &tcp_client_config(port));
|
||||
let handle = start(&dir).await;
|
||||
|
||||
let mut connection = Frames::accept(&hub, false).await;
|
||||
let opening = connection
|
||||
.next(Duration::from_secs(5))
|
||||
.await
|
||||
.and_then(|frame| synthesis_in(&frame))
|
||||
.expect("the client synthesizes");
|
||||
let hub_identity = Identity::new();
|
||||
connection
|
||||
.reader
|
||||
.get_mut()
|
||||
.write_all(&rns_interface::hdlc::frame(&hub_answer(&hub_identity)))
|
||||
.await
|
||||
.unwrap();
|
||||
let entry = wait_for_interface(&handle, |entry| {
|
||||
entry.name == "Uplink" && entry.remote_transport_id == Some(hub_identity.hash)
|
||||
})
|
||||
.await
|
||||
.expect("the client records its hub");
|
||||
assert_eq!(entry.tunnel_id, Some(opening.tunnel_id()));
|
||||
assert_eq!(
|
||||
entry.remote_transport.map(|remote| remote.implementation),
|
||||
Some("rsRNS".to_string())
|
||||
);
|
||||
|
||||
handle.shutdown_and_wait().await;
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// A tunnel synthesis whose signature fails.
|
||||
fn bad_synthesis() -> Vec<u8> {
|
||||
let mut synthesis = hub_answer(&Identity::new());
|
||||
synthesis[rns_wire::constants::HEADER_MINSIZE + 120] ^= 0x01;
|
||||
synthesis
|
||||
}
|
||||
|
||||
async fn next_detach(
|
||||
detaches: &mut tokio::sync::broadcast::Receiver<InterfaceDetach>,
|
||||
) -> InterfaceDetach {
|
||||
tokio::time::timeout(Duration::from_secs(10), detaches.recv())
|
||||
.await
|
||||
.expect("the detach is published")
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// An answer with a bad signature tears the client down for good, with
|
||||
/// interface management off and nobody subscribed to detaches
|
||||
/// (Transport.py:3245-3248, Reticulum.py:976-1015).
|
||||
#[tokio::test]
|
||||
async fn a_client_answered_with_a_bad_signature_is_torn_down() {
|
||||
let hub = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = hub.local_addr().unwrap().port();
|
||||
let dir = config_dir(
|
||||
"tcp-bad-answer",
|
||||
&tcp_client_config(port).replace(
|
||||
"share_instance = No\n",
|
||||
"share_instance = No\n enable_interface_management = No\n",
|
||||
),
|
||||
);
|
||||
let handle = start(&dir).await;
|
||||
assert!(!handle.config.enable_interface_management);
|
||||
|
||||
let mut connection = Frames::accept(&hub, false).await;
|
||||
assert!(
|
||||
connection
|
||||
.next(Duration::from_secs(5))
|
||||
.await
|
||||
.is_some_and(|frame| synthesis_in(&frame).is_some())
|
||||
);
|
||||
connection
|
||||
.reader
|
||||
.get_mut()
|
||||
.write_all(&rns_interface::hdlc::frame(&bad_synthesis()))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
|
||||
while interfaces(&handle)
|
||||
.await
|
||||
.iter()
|
||||
.any(|entry| entry.name == "Uplink")
|
||||
{
|
||||
assert!(
|
||||
tokio::time::Instant::now() < deadline,
|
||||
"the client is detached"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
assert!(
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(rns_interface::tcp::RECONNECT_WAIT + 2),
|
||||
hub.accept()
|
||||
)
|
||||
.await
|
||||
.is_err(),
|
||||
"a detached client does not reconnect"
|
||||
);
|
||||
|
||||
handle.shutdown_and_wait().await;
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// The hub answers badly as the client connects, while the runtime starts:
|
||||
/// that detach, made before anyone subscribes, reaches the first subscriber,
|
||||
/// and a later one hears only what follows.
|
||||
#[tokio::test]
|
||||
async fn a_start_up_detach_reaches_the_first_subscriber() {
|
||||
let hub = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = hub.local_addr().unwrap().port();
|
||||
let torn_down = tokio::spawn(async move {
|
||||
let (mut stream, _) = hub.accept().await.unwrap();
|
||||
stream
|
||||
.write_all(&rns_interface::hdlc::frame(&bad_synthesis()))
|
||||
.await
|
||||
.unwrap();
|
||||
let _ = stream.read_to_end(&mut Vec::new()).await;
|
||||
});
|
||||
let dir = config_dir("detach-start-up", &tcp_client_config(port));
|
||||
let handle = start(&dir).await;
|
||||
tokio::time::timeout(Duration::from_secs(10), torn_down)
|
||||
.await
|
||||
.expect("the runtime detaches the client before anyone subscribes")
|
||||
.unwrap();
|
||||
|
||||
let detach = next_detach(&mut handle.subscribe_interface_detaches()).await;
|
||||
assert_eq!(
|
||||
(detach.name.as_str(), detach.parent_id, detach.reason),
|
||||
("Uplink", None, DetachReason::InvalidSynthesis)
|
||||
);
|
||||
assert!(
|
||||
interfaces(&handle)
|
||||
.await
|
||||
.iter()
|
||||
.all(|entry| entry.id != detach.interface_id)
|
||||
);
|
||||
assert!(matches!(
|
||||
handle.subscribe_interface_detaches().try_recv(),
|
||||
Err(tokio::sync::broadcast::error::TryRecvError::Empty)
|
||||
));
|
||||
|
||||
handle.shutdown_and_wait().await;
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_later_detach_reaches_every_subscriber() {
|
||||
let hub = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = hub.local_addr().unwrap().port();
|
||||
let dir = config_dir("detach-later", &tcp_client_config(port));
|
||||
let handle = start(&dir).await;
|
||||
let mut subscribers = [
|
||||
handle.subscribe_interface_detaches(),
|
||||
handle.subscribe_interface_detaches(),
|
||||
];
|
||||
|
||||
let mut connection = Frames::accept(&hub, false).await;
|
||||
assert!(
|
||||
connection
|
||||
.next(Duration::from_secs(5))
|
||||
.await
|
||||
.is_some_and(|frame| synthesis_in(&frame).is_some())
|
||||
);
|
||||
let uplink = wait_for_interface(&handle, |entry| entry.name == "Uplink")
|
||||
.await
|
||||
.unwrap();
|
||||
connection
|
||||
.reader
|
||||
.get_mut()
|
||||
.write_all(&rns_interface::hdlc::frame(&bad_synthesis()))
|
||||
.await
|
||||
.unwrap();
|
||||
for subscriber in &mut subscribers {
|
||||
assert_eq!(
|
||||
next_detach(subscriber).await,
|
||||
InterfaceDetach {
|
||||
name: "Uplink".to_string(),
|
||||
interface_id: uplink.id,
|
||||
parent_id: None,
|
||||
reason: DetachReason::InvalidSynthesis,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
handle.shutdown_and_wait().await;
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// A server's accepted client that fails verification goes on its own, and
|
||||
/// the detach names the server it came from.
|
||||
#[tokio::test]
|
||||
async fn a_detached_accepted_client_names_its_server() {
|
||||
let port = unused_port().await;
|
||||
let dir = config_dir(
|
||||
"detach-accepted",
|
||||
&format!(
|
||||
"[reticulum]\n share_instance = No\n enable_transport = Yes\n\n[interfaces]\n [[Hub]]\n type = TCPServerInterface\n enabled = yes\n listen_ip = 127.0.0.1\n listen_port = {port}\n"
|
||||
),
|
||||
);
|
||||
let handle = start(&dir).await;
|
||||
let mut detaches = handle.subscribe_interface_detaches();
|
||||
let server = wait_for_interface(&handle, |entry| entry.name == "Hub")
|
||||
.await
|
||||
.unwrap();
|
||||
let mut client = TcpStream::connect(("127.0.0.1", port)).await.unwrap();
|
||||
let accepted = wait_for_interface(&handle, |entry| entry.parent_id == Some(server.id))
|
||||
.await
|
||||
.expect("the client registers");
|
||||
client
|
||||
.write_all(&rns_interface::hdlc::frame(&bad_synthesis()))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let detach = next_detach(&mut detaches).await;
|
||||
assert_eq!(
|
||||
(detach.interface_id, detach.parent_id, detach.reason),
|
||||
(accepted.id, Some(server.id), DetachReason::InvalidSynthesis)
|
||||
);
|
||||
assert_eq!(detach.name, "Client on Hub");
|
||||
assert!(
|
||||
interfaces(&handle)
|
||||
.await
|
||||
.iter()
|
||||
.any(|entry| entry.id == server.id),
|
||||
"the server stays"
|
||||
);
|
||||
|
||||
handle.shutdown_and_wait().await;
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Python 1.6.1 `_detach_interface`: text that names no interface but spells a
|
||||
/// tunnel id in hex, as `bytes.fromhex` reads it, detaches the interface whose
|
||||
/// `tunnel_id or local_tunnel_id` it is (Reticulum.py:976-1015).
|
||||
#[tokio::test]
|
||||
async fn detach_by_tunnel_id_finds_either_end_of_the_tunnel() {
|
||||
let hub_port = unused_port().await;
|
||||
let hub_dir = config_dir(
|
||||
"detach-hub",
|
||||
&format!(
|
||||
"[reticulum]\n share_instance = No\n enable_transport = Yes\n\n[interfaces]\n [[Hub]]\n type = TCPServerInterface\n enabled = yes\n listen_ip = 127.0.0.1\n listen_port = {hub_port}\n"
|
||||
),
|
||||
);
|
||||
let hub = start(&hub_dir).await;
|
||||
let client_dir = config_dir("detach-client", &tcp_client_config(hub_port));
|
||||
let client = start(&client_dir).await;
|
||||
let accepted = wait_for_interface(&hub, |entry| {
|
||||
entry.parent_id.is_some() && entry.tunnel_id.is_some()
|
||||
})
|
||||
.await
|
||||
.expect("the hub takes the client's synthesis");
|
||||
let uplink = wait_for_interface(&client, |entry| {
|
||||
entry.name == "Uplink" && entry.tunnel_id.is_some()
|
||||
})
|
||||
.await
|
||||
.expect("the client names its tunnel");
|
||||
assert_eq!(accepted.tunnel_id, uplink.tunnel_id);
|
||||
let tunnel = hex::encode(accepted.tunnel_id.unwrap());
|
||||
|
||||
assert_eq!(hub.detach_interface("not hex").await.unwrap(), None);
|
||||
assert_eq!(hub.detach_interface(&"00".repeat(32)).await.unwrap(), None);
|
||||
let spaced: Vec<String> = tunnel
|
||||
.to_uppercase()
|
||||
.as_bytes()
|
||||
.chunks(2)
|
||||
.map(|pair| String::from_utf8(pair.to_vec()).unwrap())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
hub.detach_interface(&spaced.join(" ")).await.unwrap(),
|
||||
Some(true)
|
||||
);
|
||||
assert!(
|
||||
interfaces(&hub)
|
||||
.await
|
||||
.iter()
|
||||
.all(|entry| entry.id != accepted.id),
|
||||
"the accepted client is gone"
|
||||
);
|
||||
assert!(
|
||||
interfaces(&hub)
|
||||
.await
|
||||
.iter()
|
||||
.any(|entry| entry.name == "Hub"),
|
||||
"its listener stays"
|
||||
);
|
||||
assert_eq!(client.detach_interface(&tunnel).await.unwrap(), Some(true));
|
||||
assert!(
|
||||
interfaces(&client)
|
||||
.await
|
||||
.iter()
|
||||
.all(|entry| entry.name != "Uplink"),
|
||||
"the client's own end goes by its local tunnel id"
|
||||
);
|
||||
|
||||
client.shutdown_and_wait().await;
|
||||
hub.shutdown_and_wait().await;
|
||||
let _ = std::fs::remove_dir_all(client_dir);
|
||||
let _ = std::fs::remove_dir_all(hub_dir);
|
||||
}
|
||||
+151
-25
@@ -300,34 +300,11 @@ async fn run_rnsh_listener_inner(
|
||||
tokio::select! {
|
||||
maybe_link = established_rx.recv() => {
|
||||
let Some(link_id) = maybe_link else { break };
|
||||
file_allowed = read_allowed_identity_files(&cfg.allowed_identity_files);
|
||||
// or_insert (not insert) so a rare identification processed ahead
|
||||
// of this establishment event is never clobbered.
|
||||
sessions.entry(link_id).or_insert_with(|| ListenerSession::new(cfg.allow_all));
|
||||
on_link_established(&cfg, &mut sessions, &mut file_allowed, link_id);
|
||||
}
|
||||
maybe_identified = identified_rx.recv() => {
|
||||
let Some((link_id, identity_hash)) = maybe_identified else { break };
|
||||
// Identification may race ahead of the establishment event.
|
||||
let session = sessions
|
||||
.entry(link_id)
|
||||
.or_insert_with(|| ListenerSession::new(cfg.allow_all));
|
||||
if session.state == ListenerState::Closed {
|
||||
continue;
|
||||
}
|
||||
if !matches!(session.state, ListenerState::WaitIdent | ListenerState::WaitVersion) {
|
||||
terminate_session(&command_tx, link_id, session, Some("Protocol error (LSSTATE_WAIT_IDENT)")).await;
|
||||
} else if cfg.allow_all
|
||||
|| cfg.allowed.contains(&identity_hash)
|
||||
|| file_allowed.contains(&identity_hash)
|
||||
{
|
||||
session.authorized = true;
|
||||
session.remote_identity_hash = Some(identity_hash);
|
||||
session.state = ListenerState::WaitVersion;
|
||||
} else {
|
||||
session.authorized = false;
|
||||
terminate_session(&command_tx, link_id, session, Some("Identity not allowed")).await;
|
||||
tracing::info!(identity = %hex::encode(identity_hash), "rnsh identity not allowed");
|
||||
}
|
||||
on_link_identified(&command_tx, &cfg, &mut sessions, &file_allowed, link_id, identity_hash).await;
|
||||
}
|
||||
maybe_closed = closed_rx.recv() => {
|
||||
let Some(link_id) = maybe_closed else { break };
|
||||
@@ -335,6 +312,15 @@ async fn run_rnsh_listener_inner(
|
||||
}
|
||||
maybe_msg = channel_rx.recv() => {
|
||||
let Some(msg) = maybe_msg else { break };
|
||||
apply_queued_link_events(
|
||||
&command_tx,
|
||||
&cfg,
|
||||
&mut sessions,
|
||||
&mut file_allowed,
|
||||
&mut established_rx,
|
||||
&mut identified_rx,
|
||||
)
|
||||
.await;
|
||||
let link_id = msg.link_id;
|
||||
match handle_listener_channel_message(
|
||||
&command_tx,
|
||||
@@ -409,6 +395,88 @@ async fn run_rnsh_listener_inner(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn on_link_established(
|
||||
cfg: &RnshListenerConfig,
|
||||
sessions: &mut HashMap<[u8; 16], ListenerSession>,
|
||||
file_allowed: &mut HashSet<[u8; 16]>,
|
||||
link_id: [u8; 16],
|
||||
) {
|
||||
*file_allowed = read_allowed_identity_files(&cfg.allowed_identity_files);
|
||||
// or_insert (not insert) so a rare identification processed ahead
|
||||
// of this establishment event is never clobbered.
|
||||
sessions
|
||||
.entry(link_id)
|
||||
.or_insert_with(|| ListenerSession::new(cfg.allow_all));
|
||||
}
|
||||
|
||||
async fn on_link_identified(
|
||||
command_tx: &mpsc::Sender<LinkManagerCommand>,
|
||||
cfg: &RnshListenerConfig,
|
||||
sessions: &mut HashMap<[u8; 16], ListenerSession>,
|
||||
file_allowed: &HashSet<[u8; 16]>,
|
||||
link_id: [u8; 16],
|
||||
identity_hash: [u8; 16],
|
||||
) {
|
||||
// Identification may race ahead of the establishment event.
|
||||
let session = sessions
|
||||
.entry(link_id)
|
||||
.or_insert_with(|| ListenerSession::new(cfg.allow_all));
|
||||
if session.state == ListenerState::Closed {
|
||||
return;
|
||||
}
|
||||
if !matches!(
|
||||
session.state,
|
||||
ListenerState::WaitIdent | ListenerState::WaitVersion
|
||||
) {
|
||||
terminate_session(
|
||||
command_tx,
|
||||
link_id,
|
||||
session,
|
||||
Some("Protocol error (LSSTATE_WAIT_IDENT)"),
|
||||
)
|
||||
.await;
|
||||
} else if cfg.allow_all
|
||||
|| cfg.allowed.contains(&identity_hash)
|
||||
|| file_allowed.contains(&identity_hash)
|
||||
{
|
||||
session.authorized = true;
|
||||
session.remote_identity_hash = Some(identity_hash);
|
||||
session.state = ListenerState::WaitVersion;
|
||||
} else {
|
||||
session.authorized = false;
|
||||
terminate_session(command_tx, link_id, session, Some("Identity not allowed")).await;
|
||||
tracing::info!(identity = %hex::encode(identity_hash), "rnsh identity not allowed");
|
||||
}
|
||||
}
|
||||
|
||||
/// The link manager queues a link's establishment and identification before its
|
||||
/// later channel messages; upstream handles all three in arrival order on one
|
||||
/// thread (`Link.py` LINKIDENTIFY, `Channel._run_callbacks`). Apply them before a
|
||||
/// channel message, or a VersionInfo sent right behind LINKIDENTIFY overtakes it.
|
||||
async fn apply_queued_link_events(
|
||||
command_tx: &mpsc::Sender<LinkManagerCommand>,
|
||||
cfg: &RnshListenerConfig,
|
||||
sessions: &mut HashMap<[u8; 16], ListenerSession>,
|
||||
file_allowed: &mut HashSet<[u8; 16]>,
|
||||
established_rx: &mut mpsc::Receiver<[u8; 16]>,
|
||||
identified_rx: &mut mpsc::Receiver<([u8; 16], [u8; 16])>,
|
||||
) {
|
||||
while let Ok(link_id) = established_rx.try_recv() {
|
||||
on_link_established(cfg, sessions, file_allowed, link_id);
|
||||
}
|
||||
while let Ok((link_id, identity_hash)) = identified_rx.try_recv() {
|
||||
on_link_identified(
|
||||
command_tx,
|
||||
cfg,
|
||||
sessions,
|
||||
file_allowed,
|
||||
link_id,
|
||||
identity_hash,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// End one listener session as `ListenerSession.terminate` does: report a fatal
|
||||
/// error if given, stop the process, and tear the link down after the prune delay.
|
||||
async fn terminate_session(
|
||||
@@ -2937,6 +3005,64 @@ mod tests {
|
||||
let _ = std::fs::remove_file(&marker);
|
||||
}
|
||||
|
||||
// An upstream initiator sends VersionInfo right behind LINKIDENTIFY, so both
|
||||
// can be queued when the listener wakes. Identification goes first, with and
|
||||
// without an allow list; otherwise the session ends with a protocol error or
|
||||
// drops the VersionInfo while it still waits for identification.
|
||||
#[tokio::test]
|
||||
async fn identification_queued_ahead_of_version_info_is_applied_first() {
|
||||
let identity_hash = [0xAB; 16];
|
||||
for allow_all in [true, false] {
|
||||
let mut cfg = marker_listener_config(&unique_marker("order"));
|
||||
cfg.allow_all = allow_all;
|
||||
cfg.allowed = vec![identity_hash];
|
||||
let (command_tx, command_rx) = mpsc::channel(64);
|
||||
let messages = Arc::new(Mutex::new(Vec::new()));
|
||||
spawn_ack_manager(command_rx, messages.clone());
|
||||
let (established_tx, mut established_rx) = mpsc::channel(4);
|
||||
let (identified_tx, mut identified_rx) = mpsc::channel(4);
|
||||
let link_id = [0x58; 16];
|
||||
established_tx.try_send(link_id).unwrap();
|
||||
identified_tx.try_send((link_id, identity_hash)).unwrap();
|
||||
|
||||
let mut sessions = HashMap::new();
|
||||
let mut file_allowed = HashSet::new();
|
||||
apply_queued_link_events(
|
||||
&command_tx,
|
||||
&cfg,
|
||||
&mut sessions,
|
||||
&mut file_allowed,
|
||||
&mut established_rx,
|
||||
&mut identified_rx,
|
||||
)
|
||||
.await;
|
||||
handle_listener_channel_message(
|
||||
&command_tx,
|
||||
&cfg,
|
||||
&mut sessions,
|
||||
version_channel_msg(link_id),
|
||||
&mpsc::unbounded_channel().0,
|
||||
)
|
||||
.await
|
||||
.expect("handler ok");
|
||||
|
||||
let session = &sessions[&link_id];
|
||||
assert_eq!(
|
||||
session.state,
|
||||
ListenerState::WaitCommand,
|
||||
"allow_all={allow_all}"
|
||||
);
|
||||
assert_eq!(session.remote_identity_hash, Some(identity_hash));
|
||||
let messages = messages.lock().unwrap();
|
||||
assert!(
|
||||
messages
|
||||
.iter()
|
||||
.any(|m| matches!(m, RnshMessage::VersionInfo(_)))
|
||||
);
|
||||
assert!(!messages.iter().any(|m| matches!(m, RnshMessage::Error(_))));
|
||||
}
|
||||
}
|
||||
|
||||
// Positive control: an authorized session in WaitCommand DOES run the command,
|
||||
// proving the harness can reach process spawn — so the negative results above
|
||||
// are due to authorization, not an impotent test setup.
|
||||
|
||||
+670
-38
@@ -8,6 +8,7 @@
|
||||
|
||||
use rns_transport::inbound_queues::InboundQueueSnapshot;
|
||||
use rns_transport::messages::{InterfaceIdentity, InterfaceStatRpcEntry};
|
||||
use rns_transport::tunnel::RemoteTransportInfo;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub(crate) const MP_CHALLENGE: &[u8] = b"#CHALLENGE#";
|
||||
@@ -119,8 +120,12 @@ pub enum RpcRequest {
|
||||
/// Reply: seconds as a float, or integer 0 without a known bitrate.
|
||||
GetMediumPathTimeout,
|
||||
GetActiveLinkCount,
|
||||
/// Reply: a dictionary; upstream's implementation is a stub answering `{}`.
|
||||
/// Reply: `{destination: {"active", "pending", "traffic", "from_ifs"}}`.
|
||||
GetLinkDistribution,
|
||||
/// Python 1.6.1 `Reticulum.get_known_destinations`; reply:
|
||||
/// `{destination: [last_heard, packet_hash, public_key, app_data, used,
|
||||
/// stamp, stamp_value, lr_cost]}`.
|
||||
GetKnownDestinations,
|
||||
/// Reply: profiler results, or nil when no profiler ran.
|
||||
GetProfilingResults,
|
||||
/// Reply: true, false, or nil when the interface does not exist.
|
||||
@@ -184,6 +189,8 @@ pub enum RpcResponse {
|
||||
/// True, False or None, as upstream's blackhole mutations answer.
|
||||
OptBoolResult(Option<bool>),
|
||||
BlackholeList(Vec<BlackholeEntry>),
|
||||
LinkDistribution(Vec<LinkDistributionEntry>),
|
||||
KnownDestinations(Vec<KnownDestinationEntry>),
|
||||
Ok,
|
||||
Error(String),
|
||||
}
|
||||
@@ -199,12 +206,20 @@ pub struct PathTableEntry {
|
||||
/// known but unstamped (Reticulum.py).
|
||||
#[serde(default)]
|
||||
pub value: Option<f64>,
|
||||
/// Last use in Unix seconds; 0 when never used.
|
||||
/// Last use in Unix seconds; 0 when never used, `None` from a peer
|
||||
/// before 1.6.0.
|
||||
#[serde(default)]
|
||||
pub used: f64,
|
||||
pub used: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub lr_cost: Option<f64>,
|
||||
pub interface: String,
|
||||
/// SHA-256 of upstream's `str(interface)`; `None` from a peer before 1.6.1.
|
||||
#[serde(default)]
|
||||
pub interface_hash: Option<Vec<u8>>,
|
||||
/// Path state: 0 unknown, 1 unresponsive, 2 responsive (Transport.py);
|
||||
/// `None` from a peer before 1.6.1.
|
||||
#[serde(default)]
|
||||
pub state: Option<u8>,
|
||||
}
|
||||
|
||||
/// One interface of Python's `get_interface_stats()` (Reticulum.py), field for
|
||||
@@ -327,6 +342,31 @@ struct InterfaceStatWire {
|
||||
tx_stalled: bool,
|
||||
#[serde(default)]
|
||||
tx_buffered: u64,
|
||||
/// Python 1.6.1 `frxb`, `ftxb` and `afrxc`.
|
||||
#[serde(default)]
|
||||
filtered_rx_bytes: u64,
|
||||
#[serde(default)]
|
||||
filtered_tx_bytes: u64,
|
||||
#[serde(default)]
|
||||
announces_filtered: u64,
|
||||
/// Python `frxs` and `ftxs`; `None` before the first traffic count.
|
||||
#[serde(default)]
|
||||
filtered_speeds: Option<[f64; 2]>,
|
||||
#[serde(default)]
|
||||
tunnel_id: Option<Vec<u8>>,
|
||||
#[serde(default)]
|
||||
remote_transport_id: Option<Vec<u8>>,
|
||||
/// Python `rem_impl`, `rem_vers`, `rem_is_tn`, `rem_dst_cost` and `rem_pr_cost`.
|
||||
#[serde(default)]
|
||||
remote_implementation: Option<String>,
|
||||
#[serde(default)]
|
||||
remote_version: Option<Vec<u64>>,
|
||||
#[serde(default)]
|
||||
remote_is_transport: Option<bool>,
|
||||
#[serde(default)]
|
||||
remote_destination_cost: Option<f64>,
|
||||
#[serde(default)]
|
||||
remote_pr_cost: Option<f64>,
|
||||
}
|
||||
|
||||
impl From<&InterfaceStatRpcEntry> for InterfaceStatWire {
|
||||
@@ -406,6 +446,20 @@ impl From<&InterfaceStatRpcEntry> for InterfaceStatWire {
|
||||
.map(|state| i2p_tunnel_state_text(state).to_string()),
|
||||
tx_stalled: e.tx_stalled,
|
||||
tx_buffered: e.tx_buffered,
|
||||
filtered_rx_bytes: e.filtered_rx_bytes,
|
||||
filtered_tx_bytes: e.filtered_tx_bytes,
|
||||
announces_filtered: e.announces_filtered,
|
||||
filtered_speeds: e.filtered_speeds,
|
||||
tunnel_id: e.tunnel_id.map(|id| id.to_vec()),
|
||||
remote_transport_id: e.remote_transport_id.map(|id| id.to_vec()),
|
||||
remote_implementation: e
|
||||
.remote_transport
|
||||
.as_ref()
|
||||
.map(|r| r.implementation.clone()),
|
||||
remote_version: e.remote_transport.as_ref().map(|r| r.version.clone()),
|
||||
remote_is_transport: e.remote_transport.as_ref().map(|r| r.transport),
|
||||
remote_destination_cost: e.remote_transport.as_ref().map(|r| r.destination_cost),
|
||||
remote_pr_cost: e.remote_transport.as_ref().map(|r| r.pr_cost),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -483,6 +537,25 @@ impl From<InterfaceStatWire> for InterfaceStatRpcEntry {
|
||||
e.i2p_tunnel_state = w.tunnel_state.as_deref().map(i2p_tunnel_state_code);
|
||||
e.tx_stalled = w.tx_stalled;
|
||||
e.tx_buffered = w.tx_buffered;
|
||||
e.filtered_rx_bytes = w.filtered_rx_bytes;
|
||||
e.filtered_tx_bytes = w.filtered_tx_bytes;
|
||||
e.announces_filtered = w.announces_filtered;
|
||||
e.filtered_speeds = w.filtered_speeds;
|
||||
e.tunnel_id = w.tunnel_id.and_then(|id| id.try_into().ok());
|
||||
e.remote_transport_id = w.remote_transport_id.and_then(|id| id.try_into().ok());
|
||||
// Python sets the five together from one synthesis extension (Transport.py).
|
||||
e.remote_transport = match (
|
||||
w.remote_implementation,
|
||||
w.remote_version,
|
||||
w.remote_is_transport,
|
||||
w.remote_destination_cost,
|
||||
w.remote_pr_cost,
|
||||
) {
|
||||
(Some(implementation), Some(version), Some(transport), Some(dst), Some(pr)) => Some(
|
||||
RemoteTransportInfo::new(implementation, version, transport, dst, pr),
|
||||
),
|
||||
_ => None,
|
||||
};
|
||||
e
|
||||
}
|
||||
}
|
||||
@@ -565,6 +638,81 @@ pub struct BlackholeEntry {
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
/// Relayed Links toward one destination (Python `Transport.link_distribution`).
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct LinkDistributionEntry {
|
||||
pub destination_hash: Vec<u8>,
|
||||
pub active: u64,
|
||||
pub pending: u64,
|
||||
pub traffic: u64,
|
||||
/// `Interface.get_hash()` of each interface a link request arrived on.
|
||||
pub from_interfaces: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl From<&rns_transport::messages::LinkDistributionRpcEntry> for LinkDistributionEntry {
|
||||
fn from(e: &rns_transport::messages::LinkDistributionRpcEntry) -> Self {
|
||||
Self {
|
||||
destination_hash: e.destination_hash.to_vec(),
|
||||
active: e.active,
|
||||
pending: e.pending,
|
||||
traffic: e.traffic,
|
||||
from_interfaces: e.from_interfaces.iter().map(|hash| hash.to_vec()).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One `Identity.known_destinations` entry under its destination hash.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct KnownDestinationEntry {
|
||||
pub destination_hash: Vec<u8>,
|
||||
pub last_heard: f64,
|
||||
pub packet_hash: Option<Vec<u8>>,
|
||||
pub public_key: Vec<u8>,
|
||||
pub app_data: Option<Vec<u8>>,
|
||||
/// 0 never used, -1 retained, otherwise the Unix time of last use.
|
||||
pub used: f64,
|
||||
pub stamp: Option<Vec<u8>>,
|
||||
pub stamp_value: f64,
|
||||
pub lr_cost: Option<f64>,
|
||||
}
|
||||
|
||||
impl From<&rns_transport::store::KnownDestinationRow> for KnownDestinationEntry {
|
||||
fn from(row: &rns_transport::store::KnownDestinationRow) -> Self {
|
||||
Self {
|
||||
destination_hash: row.destination_hash.to_vec(),
|
||||
last_heard: row.last_heard,
|
||||
packet_hash: row.packet_hash.map(|hash| hash.to_vec()),
|
||||
public_key: row.public_key.to_vec(),
|
||||
app_data: row.app_data.clone(),
|
||||
used: row.used,
|
||||
stamp: row.stamp.clone(),
|
||||
stamp_value: row.stamp_value,
|
||||
lr_cost: row.lr_cost,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl KnownDestinationEntry {
|
||||
/// The store row, or `None` for a malformed hash or key.
|
||||
pub fn to_row(&self) -> Option<rns_transport::store::KnownDestinationRow> {
|
||||
let mut row = rns_transport::store::KnownDestinationRow::new(
|
||||
self.destination_hash.as_slice().try_into().ok()?,
|
||||
self.last_heard,
|
||||
self.public_key.as_slice().try_into().ok()?,
|
||||
);
|
||||
row.packet_hash = match &self.packet_hash {
|
||||
Some(hash) => Some(hash.as_slice().try_into().ok()?),
|
||||
None => None,
|
||||
};
|
||||
row.app_data = self.app_data.clone();
|
||||
row.used = self.used;
|
||||
row.stamp = self.stamp.clone();
|
||||
row.stamp_value = self.stamp_value;
|
||||
row.lr_cost = self.lr_cost;
|
||||
Some(row)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encode_request(req: &RpcRequest) -> Result<Vec<u8>, RpcError> {
|
||||
encode_umsgpack(&request_to_py_value(req))
|
||||
}
|
||||
@@ -745,6 +893,7 @@ fn request_to_py_value(req: &RpcRequest) -> PyValue {
|
||||
RpcRequest::GetMediumPathTimeout => py_get("medium_path_timeout"),
|
||||
RpcRequest::GetActiveLinkCount => py_get("active_link_count"),
|
||||
RpcRequest::GetLinkDistribution => py_get("link_distribution"),
|
||||
RpcRequest::GetKnownDestinations => py_get("known_destinations"),
|
||||
RpcRequest::GetProfilingResults => py_get("profiling_results"),
|
||||
RpcRequest::ManageInterface { operation, name } => py_dict(vec![
|
||||
("manage", PyValue::String(operation.as_str().to_string())),
|
||||
@@ -835,6 +984,7 @@ fn py_value_to_request(value: &PyValue) -> Result<RpcRequest, RpcError> {
|
||||
"medium_path_timeout" => Ok(RpcRequest::GetMediumPathTimeout),
|
||||
"active_link_count" => Ok(RpcRequest::GetActiveLinkCount),
|
||||
"link_distribution" => Ok(RpcRequest::GetLinkDistribution),
|
||||
"known_destinations" => Ok(RpcRequest::GetKnownDestinations),
|
||||
"profiling_results" => Ok(RpcRequest::GetProfilingResults),
|
||||
other => Err(RpcError::Deserialize(format!(
|
||||
"unknown Python RPC get path: {other}"
|
||||
@@ -998,18 +1148,14 @@ pub(crate) fn encode_medium_path_timeout(seconds: Option<f64>) -> Result<Vec<u8>
|
||||
encode_umsgpack(&seconds.map(PyValue::Float).unwrap_or(PyValue::Int(0)))
|
||||
}
|
||||
|
||||
/// An empty dictionary, as upstream's stub `link_distribution` answers.
|
||||
pub(crate) fn encode_empty_dict() -> Result<Vec<u8>, RpcError> {
|
||||
encode_umsgpack(&PyValue::Dict(Vec::new()))
|
||||
}
|
||||
|
||||
fn response_to_py_value(resp: &RpcResponse) -> PyValue {
|
||||
match resp {
|
||||
RpcResponse::PathTable(entries) => PyValue::List(
|
||||
entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
py_dict(vec![
|
||||
// A key an older peer lacks stays absent, as in its dict.
|
||||
let mut fields = vec![
|
||||
("hash", PyValue::Bytes(e.hash.clone())),
|
||||
("timestamp", PyValue::Float(e.timestamp)),
|
||||
(
|
||||
@@ -1019,13 +1165,23 @@ fn response_to_py_value(resp: &RpcResponse) -> PyValue {
|
||||
("hops", PyValue::Int(i128::from(e.hops))),
|
||||
("expires", PyValue::Float(e.expires)),
|
||||
("value", e.value.map(py_number).unwrap_or(PyValue::None)),
|
||||
("used", py_number(e.used)),
|
||||
(
|
||||
"lr_cost",
|
||||
e.lr_cost.map(PyValue::Float).unwrap_or(PyValue::None),
|
||||
),
|
||||
("interface", PyValue::String(e.interface.clone())),
|
||||
])
|
||||
];
|
||||
fields.extend(e.used.map(|used| ("used", py_number(used))));
|
||||
fields.push((
|
||||
"lr_cost",
|
||||
e.lr_cost.map(PyValue::Float).unwrap_or(PyValue::None),
|
||||
));
|
||||
fields.push(("interface", PyValue::String(e.interface.clone())));
|
||||
fields.extend(
|
||||
e.interface_hash
|
||||
.clone()
|
||||
.map(|hash| ("interface_hash", PyValue::Bytes(hash))),
|
||||
);
|
||||
fields.extend(
|
||||
e.state
|
||||
.map(|state| ("state", PyValue::Int(i128::from(state)))),
|
||||
);
|
||||
py_dict(fields)
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
@@ -1091,6 +1247,60 @@ fn response_to_py_value(resp: &RpcResponse) -> PyValue {
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
RpcResponse::LinkDistribution(entries) => PyValue::Dict(
|
||||
entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let int = |value: u64| PyValue::Int(i128::from(value));
|
||||
(
|
||||
PyDictKey::Bytes(e.destination_hash.clone()),
|
||||
py_dict(vec![
|
||||
("active", int(e.active)),
|
||||
("pending", int(e.pending)),
|
||||
("traffic", int(e.traffic)),
|
||||
(
|
||||
"from_ifs",
|
||||
PyValue::List(
|
||||
e.from_interfaces
|
||||
.iter()
|
||||
.map(|hash| PyValue::Bytes(hash.clone()))
|
||||
.collect(),
|
||||
),
|
||||
),
|
||||
]),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
RpcResponse::KnownDestinations(entries) => PyValue::Dict(
|
||||
entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let bytes = |value: &Option<Vec<u8>>| {
|
||||
value.clone().map(PyValue::Bytes).unwrap_or(PyValue::None)
|
||||
};
|
||||
// Upstream keeps the never-used and retained markers as ints.
|
||||
let used = if e.used == -1.0 {
|
||||
PyValue::Int(-1)
|
||||
} else {
|
||||
py_number(e.used)
|
||||
};
|
||||
(
|
||||
PyDictKey::Bytes(e.destination_hash.clone()),
|
||||
PyValue::List(vec![
|
||||
PyValue::Float(e.last_heard),
|
||||
bytes(&e.packet_hash),
|
||||
PyValue::Bytes(e.public_key.clone()),
|
||||
bytes(&e.app_data),
|
||||
used,
|
||||
bytes(&e.stamp),
|
||||
py_number(e.stamp_value),
|
||||
e.lr_cost.map(PyValue::Float).unwrap_or(PyValue::None),
|
||||
]),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
RpcResponse::Ok => PyValue::Bool(true),
|
||||
RpcResponse::Error(e) => py_dict(vec![("error", PyValue::String(e.clone()))]),
|
||||
}
|
||||
@@ -1205,6 +1415,14 @@ fn interface_stats_value(
|
||||
("txb", int(t.txb)),
|
||||
("rxs", speed(t.rxs)),
|
||||
("txs", speed(t.txs)),
|
||||
("lrxb", int(t.lrxb)),
|
||||
("ltxb", int(t.ltxb)),
|
||||
("lrxs", speed(t.lrxs)),
|
||||
("ltxs", speed(t.ltxs)),
|
||||
("frxb", int(t.frxb)),
|
||||
("ftxb", int(t.ftxb)),
|
||||
("frxs", speed(t.frxs)),
|
||||
("ftxs", speed(t.ftxs)),
|
||||
("arxb", int(t.arxb)),
|
||||
("atxb", int(t.atxb)),
|
||||
("arxs", speed(t.arxs)),
|
||||
@@ -1238,9 +1456,9 @@ fn interface_stats_value(
|
||||
("txs", PyValue::Int(i128::from(sum(|e| e.tx_rate)))),
|
||||
]);
|
||||
for key in [
|
||||
"arxb", "atxb", "arxs", "atxs", "arxf", "atxf", "prxb", "ptxb", "prxs", "ptxs",
|
||||
"prxf", "ptxf", "rxpps", "txpps", "rxpkts", "txpkts", "arxpkts", "atxpkts",
|
||||
"prxpkts", "ptxpkts",
|
||||
"lrxb", "ltxb", "lrxs", "ltxs", "frxb", "ftxb", "frxs", "ftxs", "arxb", "atxb",
|
||||
"arxs", "atxs", "arxf", "atxf", "prxb", "ptxb", "prxs", "ptxs", "prxf", "ptxf",
|
||||
"rxpps", "txpps", "rxpkts", "txpkts", "arxpkts", "atxpkts", "prxpkts", "ptxpkts",
|
||||
] {
|
||||
stats.push((key, PyValue::Int(0)));
|
||||
}
|
||||
@@ -1290,6 +1508,10 @@ fn interface_stat_value(e: &InterfaceStatWire) -> PyValue {
|
||||
Some(speeds) => PyValue::Float(speeds[index]),
|
||||
None => int(fallback),
|
||||
};
|
||||
let filtered_speed = |index: usize| match e.filtered_speeds {
|
||||
Some(speeds) => PyValue::Float(speeds[index]),
|
||||
None => int(0),
|
||||
};
|
||||
let mut fields = vec![
|
||||
("id", int(e.id)),
|
||||
("name", PyValue::String(e.name.clone())),
|
||||
@@ -1307,8 +1529,12 @@ fn interface_stat_value(e: &InterfaceStatWire) -> PyValue {
|
||||
),
|
||||
("rxb", int(e.rx_bytes)),
|
||||
("txb", int(e.tx_bytes)),
|
||||
("frxb", int(e.filtered_rx_bytes)),
|
||||
("ftxb", int(e.filtered_tx_bytes)),
|
||||
("rxs", speed(0, e.rx_rate)),
|
||||
("txs", speed(1, e.tx_rate)),
|
||||
("frxs", filtered_speed(0)),
|
||||
("ftxs", filtered_speed(1)),
|
||||
("arxb", int(e.announce_rx_bytes)),
|
||||
("atxb", int(e.announce_tx_bytes)),
|
||||
("arxs", speed(2, 0)),
|
||||
@@ -1325,6 +1551,7 @@ fn interface_stat_value(e: &InterfaceStatWire) -> PyValue {
|
||||
),
|
||||
("arxc", int(e.announces_received)),
|
||||
("atxc", int(e.announces_sent)),
|
||||
("afrxc", int(e.announces_filtered)),
|
||||
("prxc", int(e.path_requests_received)),
|
||||
("ptxc", int(e.path_requests_sent)),
|
||||
("status", PyValue::Bool(e.online)),
|
||||
@@ -1400,6 +1627,41 @@ fn interface_stat_value(e: &InterfaceStatWire) -> PyValue {
|
||||
("protocol_violations", int(e.protocol_violations)),
|
||||
("ifac_violations", int(e.ifac_violations)),
|
||||
("packet_filter_hits", int(e.packet_filter_hits)),
|
||||
(
|
||||
"tunnel_id",
|
||||
optional(e.tunnel_id.clone().map(PyValue::Bytes)),
|
||||
),
|
||||
(
|
||||
"remote_transport_id",
|
||||
optional(e.remote_transport_id.clone().map(PyValue::Bytes)),
|
||||
),
|
||||
(
|
||||
"rem_impl",
|
||||
optional(e.remote_implementation.clone().map(PyValue::String)),
|
||||
),
|
||||
(
|
||||
"rem_vers",
|
||||
optional(e.remote_version.as_ref().map(|version| {
|
||||
PyValue::List(
|
||||
version
|
||||
.iter()
|
||||
.map(|v| PyValue::Int(i128::from(*v)))
|
||||
.collect(),
|
||||
)
|
||||
})),
|
||||
),
|
||||
(
|
||||
"rem_is_tn",
|
||||
optional(e.remote_is_transport.map(PyValue::Bool)),
|
||||
),
|
||||
(
|
||||
"rem_dst_cost",
|
||||
optional(e.remote_destination_cost.map(PyValue::Float)),
|
||||
),
|
||||
(
|
||||
"rem_pr_cost",
|
||||
optional(e.remote_pr_cost.map(PyValue::Float)),
|
||||
),
|
||||
];
|
||||
if let Some(parent) = &e.parent_interface_name {
|
||||
fields.push(("parent_interface_name", PyValue::String(parent.clone())));
|
||||
@@ -1502,13 +1764,12 @@ fn py_value_to_response_for_request(
|
||||
py_optional_float(value)?.unwrap_or(0.0),
|
||||
))),
|
||||
RpcRequest::GetActiveLinkCount => Ok(RpcResponse::IntResult(py_required_int(value)?)),
|
||||
// Upstream's link distribution is a stub that answers `{}`.
|
||||
RpcRequest::GetLinkDistribution => match value {
|
||||
PyValue::Dict(_) => Ok(RpcResponse::Ok),
|
||||
_ => Err(RpcError::Deserialize(
|
||||
"expected link distribution dictionary".to_string(),
|
||||
)),
|
||||
},
|
||||
RpcRequest::GetLinkDistribution => Ok(RpcResponse::LinkDistribution(
|
||||
parse_link_distribution(value)?,
|
||||
)),
|
||||
RpcRequest::GetKnownDestinations => Ok(RpcResponse::KnownDestinations(
|
||||
parse_known_destinations(value)?,
|
||||
)),
|
||||
// `None` means no profiler ran; results themselves are not decoded.
|
||||
RpcRequest::GetProfilingResults => Ok(match value {
|
||||
PyValue::None => RpcResponse::StringResult(None),
|
||||
@@ -1578,11 +1839,16 @@ fn parse_path_table(value: &PyValue) -> Result<Vec<PathTableEntry>, RpcError> {
|
||||
hops: dict_get(m, "hops").and_then(py_u8).unwrap_or(0),
|
||||
expires: dict_get(m, "expires").and_then(py_f64).unwrap_or(0.0),
|
||||
value: dict_get(m, "value").and_then(py_f64),
|
||||
used: dict_get(m, "used").and_then(py_f64).unwrap_or(0.0),
|
||||
used: dict_get(m, "used").and_then(py_f64),
|
||||
lr_cost: dict_get(m, "lr_cost").and_then(py_f64),
|
||||
interface: dict_get(m, "interface")
|
||||
.and_then(py_string)
|
||||
.unwrap_or_default(),
|
||||
interface_hash: match dict_get(m, "interface_hash") {
|
||||
Some(PyValue::Bytes(v)) => Some(v.clone()),
|
||||
_ => None,
|
||||
},
|
||||
state: dict_get(m, "state").and_then(py_u8),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
@@ -1736,6 +2002,29 @@ fn parse_interface_stats(value: &PyValue) -> Result<Vec<InterfaceStatRpcEntry>,
|
||||
tunnel_state: dict_get(m, "tunnelstate").and_then(py_string),
|
||||
tx_stalled: dict_get(m, "txstalled").and_then(py_bool).unwrap_or(false),
|
||||
tx_buffered: dict_get(m, "txbuffered").and_then(py_u64).unwrap_or(0),
|
||||
filtered_rx_bytes: dict_get(m, "frxb").and_then(py_u64).unwrap_or(0),
|
||||
filtered_tx_bytes: dict_get(m, "ftxb").and_then(py_u64).unwrap_or(0),
|
||||
announces_filtered: dict_get(m, "afrxc").and_then(py_u64).unwrap_or(0),
|
||||
filtered_speeds: match (dict_get(m, "frxs"), dict_get(m, "ftxs")) {
|
||||
(Some(PyValue::Float(rx)), Some(tx)) => Some([*rx, py_f64(tx).unwrap_or(0.0)]),
|
||||
_ => None,
|
||||
},
|
||||
tunnel_id: match dict_get(m, "tunnel_id") {
|
||||
Some(PyValue::Bytes(id)) => Some(id.clone()),
|
||||
_ => None,
|
||||
},
|
||||
remote_transport_id: match dict_get(m, "remote_transport_id") {
|
||||
Some(PyValue::Bytes(id)) => Some(id.clone()),
|
||||
_ => None,
|
||||
},
|
||||
remote_implementation: dict_get(m, "rem_impl").and_then(py_string),
|
||||
remote_version: match dict_get(m, "rem_vers") {
|
||||
Some(PyValue::List(parts)) => parts.iter().map(py_u64).collect(),
|
||||
_ => None,
|
||||
},
|
||||
remote_is_transport: dict_get(m, "rem_is_tn").and_then(py_bool),
|
||||
remote_destination_cost: dict_get(m, "rem_dst_cost").and_then(py_f64),
|
||||
remote_pr_cost: dict_get(m, "rem_pr_cost").and_then(py_f64),
|
||||
}))
|
||||
})
|
||||
.collect()
|
||||
@@ -1811,6 +2100,86 @@ fn parse_blackhole_list(value: &PyValue) -> Result<Vec<BlackholeEntry>, RpcError
|
||||
}
|
||||
}
|
||||
|
||||
/// `{destination: {"active", "pending", "traffic", "from_ifs"}}`; nil, a
|
||||
/// Python client's failed call, reads as empty.
|
||||
fn parse_link_distribution(value: &PyValue) -> Result<Vec<LinkDistributionEntry>, RpcError> {
|
||||
let entries = match value {
|
||||
PyValue::None => return Ok(Vec::new()),
|
||||
PyValue::Dict(entries) => entries,
|
||||
_ => {
|
||||
return Err(RpcError::Deserialize(
|
||||
"expected link distribution dictionary".to_string(),
|
||||
));
|
||||
}
|
||||
};
|
||||
entries
|
||||
.iter()
|
||||
.map(|(key, entry)| {
|
||||
let PyDictKey::Bytes(hash) = key else {
|
||||
return Err(RpcError::Deserialize(
|
||||
"expected destination hash key".to_string(),
|
||||
));
|
||||
};
|
||||
let m = as_dict(entry)?;
|
||||
let count = |key: &str| dict_get(m, key).and_then(py_u64).unwrap_or(0);
|
||||
Ok(LinkDistributionEntry {
|
||||
destination_hash: hash.clone(),
|
||||
active: count("active"),
|
||||
pending: count("pending"),
|
||||
traffic: count("traffic"),
|
||||
from_interfaces: match dict_get(m, "from_ifs") {
|
||||
Some(PyValue::List(hashes)) => hashes
|
||||
.iter()
|
||||
.filter_map(|hash| match hash {
|
||||
PyValue::Bytes(hash) => Some(hash.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
},
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `{destination: [last_heard, packet_hash, public_key, app_data, used, stamp,
|
||||
/// stamp_value, lr_cost]}` (Identity.py); an entry without a key is skipped.
|
||||
fn parse_known_destinations(value: &PyValue) -> Result<Vec<KnownDestinationEntry>, RpcError> {
|
||||
let entries = match value {
|
||||
PyValue::None => return Ok(Vec::new()),
|
||||
PyValue::Dict(entries) => entries,
|
||||
_ => {
|
||||
return Err(RpcError::Deserialize(
|
||||
"expected known destinations dictionary".to_string(),
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok(entries
|
||||
.iter()
|
||||
.filter_map(|(key, entry)| {
|
||||
let (PyDictKey::Bytes(hash), PyValue::List(fields)) = (key, entry) else {
|
||||
return None;
|
||||
};
|
||||
let field = |index: usize| fields.get(index).unwrap_or(&PyValue::None);
|
||||
let bytes = |index: usize| match field(index) {
|
||||
PyValue::Bytes(bytes) => Some(bytes.clone()),
|
||||
_ => None,
|
||||
};
|
||||
Some(KnownDestinationEntry {
|
||||
destination_hash: hash.clone(),
|
||||
last_heard: py_f64(field(0)).unwrap_or(0.0),
|
||||
packet_hash: bytes(1),
|
||||
public_key: bytes(2)?,
|
||||
app_data: bytes(3),
|
||||
used: py_f64(field(4)).unwrap_or(0.0),
|
||||
stamp: bytes(5),
|
||||
stamp_value: py_f64(field(6)).unwrap_or(0.0),
|
||||
lr_cost: py_f64(field(7)),
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn as_dict(value: &PyValue) -> Result<&[(PyDictKey, PyValue)], RpcError> {
|
||||
match value {
|
||||
PyValue::Dict(entries) => Ok(entries),
|
||||
@@ -2685,7 +3054,7 @@ pub enum RpcError {
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
/// Keys Python 1.5.5 `get_interface_stats()` gives every interface
|
||||
/// Keys Python 1.6.1 `get_interface_stats()` gives every interface
|
||||
/// (Reticulum.py); `rnstatus` indexes most of them unguarded.
|
||||
#[cfg(test)]
|
||||
pub(crate) const PYTHON_INTERFACE_KEYS: &[&str] = &[
|
||||
@@ -2741,9 +3110,22 @@ pub(crate) const PYTHON_INTERFACE_KEYS: &[&str] = &[
|
||||
"protocol_violations",
|
||||
"ifac_violations",
|
||||
"packet_filter_hits",
|
||||
"frxs",
|
||||
"ftxs",
|
||||
"frxb",
|
||||
"ftxb",
|
||||
"afrxc",
|
||||
"announce_queue",
|
||||
"tunnel_id",
|
||||
"remote_transport_id",
|
||||
"rem_impl",
|
||||
"rem_vers",
|
||||
"rem_is_tn",
|
||||
"rem_dst_cost",
|
||||
"rem_pr_cost",
|
||||
];
|
||||
|
||||
/// Totals in every Python 1.5.5 stats dict (Reticulum.py).
|
||||
/// Totals in every Python 1.6.1 stats dict (Reticulum.py).
|
||||
#[cfg(test)]
|
||||
pub(crate) const PYTHON_TOTAL_KEYS: &[&str] = &[
|
||||
"interfaces",
|
||||
@@ -2751,6 +3133,14 @@ pub(crate) const PYTHON_TOTAL_KEYS: &[&str] = &[
|
||||
"txb",
|
||||
"rxs",
|
||||
"txs",
|
||||
"lrxb",
|
||||
"ltxb",
|
||||
"lrxs",
|
||||
"ltxs",
|
||||
"frxb",
|
||||
"ftxb",
|
||||
"frxs",
|
||||
"ftxs",
|
||||
"arxb",
|
||||
"atxb",
|
||||
"arxs",
|
||||
@@ -2841,9 +3231,11 @@ mod tests {
|
||||
hops: 3,
|
||||
expires: 1234567890.0 + 604800.0,
|
||||
value: None,
|
||||
used: 0.0,
|
||||
used: Some(0.0),
|
||||
lr_cost: None,
|
||||
interface: "TCPInterface[test]".to_string(),
|
||||
interface_hash: None,
|
||||
state: None,
|
||||
};
|
||||
let resp = RpcResponse::PathTable(vec![entry]);
|
||||
let encoded = encode_response(&resp).unwrap();
|
||||
@@ -2908,7 +3300,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interface_stats_carry_every_python_155_key() {
|
||||
fn interface_stats_carry_every_python_161_key() {
|
||||
let encoded =
|
||||
encode_response(&RpcResponse::InterfaceStats(vec![interface_stat_entry()])).unwrap();
|
||||
let stats = stats_dict(&encoded);
|
||||
@@ -3237,6 +3629,199 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Python 1.6.1's filtered, tunnel and remote transport keys decode and
|
||||
/// encode again unchanged; without a remote transport all `rem_*` are nil.
|
||||
#[test]
|
||||
fn python_161_tunnel_and_filtered_keys_round_trip() {
|
||||
let sent = vec![
|
||||
("name", PyValue::String("TCPInterface[Hub]".to_string())),
|
||||
("type", PyValue::String("TCPInterface".to_string())),
|
||||
("status", PyValue::Bool(true)),
|
||||
("frxb", PyValue::Int(31)),
|
||||
("ftxb", PyValue::Int(0)),
|
||||
("frxs", PyValue::Float(8.5)),
|
||||
("ftxs", PyValue::Float(0.0)),
|
||||
("afrxc", PyValue::Int(3)),
|
||||
("tunnel_id", PyValue::Bytes(vec![0xab; 32])),
|
||||
("remote_transport_id", PyValue::Bytes(vec![0xcd; 16])),
|
||||
("rem_impl", PyValue::String("rns".to_string())),
|
||||
(
|
||||
"rem_vers",
|
||||
PyValue::List(vec![PyValue::Int(1), PyValue::Int(6), PyValue::Int(1)]),
|
||||
),
|
||||
("rem_is_tn", PyValue::Bool(true)),
|
||||
("rem_dst_cost", PyValue::Float(8.0)),
|
||||
("rem_pr_cost", PyValue::Float(0.5)),
|
||||
];
|
||||
let upstream = py_dict(vec![(
|
||||
"interfaces",
|
||||
PyValue::List(vec![py_dict(sent.clone())]),
|
||||
)]);
|
||||
let decoded = decode_response_for_request(
|
||||
&encode_umsgpack(&upstream).unwrap(),
|
||||
&RpcRequest::GetInterfaceStats,
|
||||
)
|
||||
.unwrap();
|
||||
let RpcResponse::InterfaceStats(entries) = &decoded else {
|
||||
panic!("wrong variant");
|
||||
};
|
||||
assert_eq!(entries[0].announces_filtered, 3);
|
||||
assert_eq!(entries[0].tunnel_id, Some([0xab; 32]));
|
||||
assert_eq!(
|
||||
entries[0]
|
||||
.remote_transport
|
||||
.as_ref()
|
||||
.map(|r| r.version.clone()),
|
||||
Some(vec![1, 6, 1])
|
||||
);
|
||||
let reencoded = encode_response(&decoded).unwrap();
|
||||
let interface = &interface_dicts(&stats_dict(&reencoded))[0];
|
||||
for (key, value) in &sent {
|
||||
assert_eq!(dict_get(interface, key), Some(value), "{key}");
|
||||
}
|
||||
|
||||
let encoded =
|
||||
encode_response(&RpcResponse::InterfaceStats(vec![interface_stat_entry()])).unwrap();
|
||||
let interface = &interface_dicts(&stats_dict(&encoded))[0];
|
||||
for key in [
|
||||
"tunnel_id",
|
||||
"remote_transport_id",
|
||||
"rem_impl",
|
||||
"rem_vers",
|
||||
"rem_is_tn",
|
||||
"rem_dst_cost",
|
||||
"rem_pr_cost",
|
||||
] {
|
||||
assert_eq!(dict_get(interface, key), Some(&PyValue::None), "{key}");
|
||||
}
|
||||
assert_eq!(dict_get(interface, "frxs"), Some(&PyValue::Int(0)));
|
||||
}
|
||||
|
||||
/// The link and filtered totals follow the transport's counters.
|
||||
#[test]
|
||||
fn interface_stats_totals_carry_link_and_filtered_traffic() {
|
||||
let mut totals = TrafficTotals::default();
|
||||
totals.measured = true;
|
||||
totals.lrxb = 41;
|
||||
totals.ltxb = 42;
|
||||
totals.lrxs = 4.5;
|
||||
totals.frxb = 43;
|
||||
totals.frxs = 1.5;
|
||||
totals.rx_packets = 44;
|
||||
let encoded = encode_interface_stats(&[], None, Some(&totals), None).unwrap();
|
||||
let stats = stats_dict(&encoded);
|
||||
for (key, value) in [
|
||||
("lrxb", PyValue::Int(41)),
|
||||
("ltxb", PyValue::Int(42)),
|
||||
("lrxs", PyValue::Float(4.5)),
|
||||
("ltxs", PyValue::Float(0.0)),
|
||||
("frxb", PyValue::Int(43)),
|
||||
("ftxb", PyValue::Int(0)),
|
||||
("frxs", PyValue::Float(1.5)),
|
||||
("ftxs", PyValue::Float(0.0)),
|
||||
("rxpkts", PyValue::Int(44)),
|
||||
] {
|
||||
assert_eq!(dict_get(&stats, key), Some(&value), "{key}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Expected bytes are upstream 1.6.1 `umsgpack.packb` of the same values.
|
||||
#[test]
|
||||
fn link_distribution_and_known_destinations_round_trip_as_upstream() {
|
||||
for (request, hex) in [
|
||||
(
|
||||
RpcRequest::GetKnownDestinations,
|
||||
"81a3676574b26b6e6f776e5f64657374696e6174696f6e73",
|
||||
),
|
||||
(
|
||||
RpcRequest::GetLinkDistribution,
|
||||
"81a3676574b16c696e6b5f646973747269627574696f6e",
|
||||
),
|
||||
] {
|
||||
let encoded = encode_request(&request).unwrap();
|
||||
assert_eq!(hex::encode(&encoded), hex);
|
||||
let decoded = decode_request(&encoded).unwrap();
|
||||
assert_eq!(format!("{decoded:?}"), format!("{request:?}"));
|
||||
}
|
||||
|
||||
let distribution = vec![LinkDistributionEntry {
|
||||
destination_hash: vec![0x11; 16],
|
||||
active: 2,
|
||||
pending: 1,
|
||||
traffic: 4096,
|
||||
from_interfaces: vec![vec![0x22; 32]],
|
||||
}];
|
||||
let encoded =
|
||||
encode_response(&RpcResponse::LinkDistribution(distribution.clone())).unwrap();
|
||||
assert_eq!(
|
||||
hex::encode(&encoded),
|
||||
"81c4101111111111111111111111111111111184a661637469766502a770656e64696e6701a77472616666\
|
||||
6963cd1000a866726f6d5f69667391c42022222222222222222222222222222222222222222222222222\
|
||||
22222222222222"
|
||||
);
|
||||
match decode_response_for_request(&encoded, &RpcRequest::GetLinkDistribution).unwrap() {
|
||||
RpcResponse::LinkDistribution(decoded) => assert_eq!(decoded, distribution),
|
||||
other => panic!("unexpected {other:?}"),
|
||||
}
|
||||
|
||||
let known = vec![
|
||||
KnownDestinationEntry {
|
||||
destination_hash: vec![0x33; 16],
|
||||
last_heard: 1_700_000_000.5,
|
||||
packet_hash: Some(vec![0x44; 32]),
|
||||
public_key: vec![0x55; 64],
|
||||
app_data: Some(b"app".to_vec()),
|
||||
used: 0.0,
|
||||
stamp: None,
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
},
|
||||
KnownDestinationEntry {
|
||||
destination_hash: vec![0x66; 16],
|
||||
last_heard: 1_700_000_001.25,
|
||||
packet_hash: None,
|
||||
public_key: vec![0x77; 64],
|
||||
app_data: None,
|
||||
used: -1.0,
|
||||
stamp: Some(vec![0x88; 32]),
|
||||
stamp_value: 8.5,
|
||||
lr_cost: Some(3.25),
|
||||
},
|
||||
];
|
||||
let encoded = encode_response(&RpcResponse::KnownDestinations(known.clone())).unwrap();
|
||||
assert_eq!(
|
||||
hex::encode(&encoded),
|
||||
"82c4103333333333333333333333333333333398cb41d954fc40200000c420444444444444444444\
|
||||
4444444444444444444444444444444444444444444444c440555555555555555555555555555555\
|
||||
55555555555555555555555555555555555555555555555555555555555555555555555555555555\
|
||||
555555555555555555c40361707000c000c0c4106666666666666666666666666666666698cb41d9\
|
||||
54fc40500000c0c44077777777777777777777777777777777777777777777777777777777777777\
|
||||
777777777777777777777777777777777777777777777777777777777777777777c0ffc420888888\
|
||||
8888888888888888888888888888888888888888888888888888888888cb4021000000000000cb40\
|
||||
0a000000000000"
|
||||
);
|
||||
match decode_response_for_request(&encoded, &RpcRequest::GetKnownDestinations).unwrap() {
|
||||
RpcResponse::KnownDestinations(decoded) => assert_eq!(decoded, known),
|
||||
other => panic!("unexpected {other:?}"),
|
||||
}
|
||||
let row = known[1].to_row().unwrap();
|
||||
assert_eq!(KnownDestinationEntry::from(&row), known[1]);
|
||||
|
||||
// nil, a Python client's failed call, and an empty table read as empty.
|
||||
for (request, bytes) in [
|
||||
(RpcRequest::GetLinkDistribution, [0xc0]),
|
||||
(RpcRequest::GetKnownDestinations, [0x80]),
|
||||
] {
|
||||
let decoded = decode_response_for_request(&bytes, &request).unwrap();
|
||||
assert!(
|
||||
matches!(
|
||||
decoded,
|
||||
RpcResponse::LinkDistribution(ref e) if e.is_empty()
|
||||
) || matches!(decoded, RpcResponse::KnownDestinations(ref e) if e.is_empty())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Serde sees the wire entry, not the transport type.
|
||||
#[test]
|
||||
fn interface_stats_serialize_as_the_wire_entry() {
|
||||
@@ -3343,6 +3928,16 @@ mod tests {
|
||||
assert!(!contains_string_key(&raw, "blocked_ips"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connect_diagnostics_stay_off_the_python_rpc() {
|
||||
let plain = encode_response(&RpcResponse::InterfaceStats(vec![interface_stat_entry()]));
|
||||
let mut entry = interface_stat_entry();
|
||||
entry.last_connect_error = Some("closed_by_peer".to_string());
|
||||
entry.connect_failures = 4;
|
||||
let encoded = encode_response(&RpcResponse::InterfaceStats(vec![entry])).unwrap();
|
||||
assert_eq!(encoded, plain.unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interface_stats_ignore_blocked_ip_lists_and_never_reencode_them() {
|
||||
let upstream = py_dict(vec![(
|
||||
@@ -3517,8 +4112,14 @@ mod tests {
|
||||
const FX_REQ_IDENTITY_DATA_RETAIN: &str = "82ad6964656e746974795f64617461a672657461696ead6964656e746974795f68617368c410dddddddddddddddddddddddddddddddd";
|
||||
// Path-table replies: RNS 1.6.0 umsgpack over the dict get_path_table builds
|
||||
// (Reticulum.py), unknown and stamped destinations.
|
||||
const FX_RESP_PATH_TABLE: &str = "9189a468617368c410aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa974696d657374616d70cb41d26580b4800000a3766961c410bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbba4686f707303a765787069726573cb41d267cf54800000a576616c7565c0a47573656400a76c725f636f7374c0a9696e74657266616365b2544350496e746572666163655b746573745d";
|
||||
const FX_RESP_PATH_TABLE_STAMPED: &str = "9189a468617368c410aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa974696d657374616d70cb41d26580b4800000a3766961c410bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbba4686f707303a765787069726573cb41d267cf54800000a576616c7565cb4018500000000000a475736564cb41d26580cfe00000a76c725f636f7374cb400a000000000000a9696e74657266616365b2544350496e746572666163655b746573745d";
|
||||
const FX_RESP_PATH_TABLE_160: &str = "9189a468617368c410aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa974696d657374616d70cb41d26580b4800000a3766961c410bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbba4686f707303a765787069726573cb41d267cf54800000a576616c7565c0a47573656400a76c725f636f7374c0a9696e74657266616365b2544350496e746572666163655b746573745d";
|
||||
const FX_RESP_PATH_TABLE_STAMPED_160: &str = "9189a468617368c410aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa974696d657374616d70cb41d26580b4800000a3766961c410bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbba4686f707303a765787069726573cb41d267cf54800000a576616c7565cb4018500000000000a475736564cb41d26580cfe00000a76c725f636f7374cb400a000000000000a9696e74657266616365b2544350496e746572666163655b746573745d";
|
||||
// The same from RNS 1.6.1, which adds `interface_hash` and `state`:
|
||||
// `Reticulum.get_path_table` run on a Transport.path_table entry whose
|
||||
// interface prints as "TCPInterface[test]", with path state 0 and 2,
|
||||
// packed with RNS.vendor.umsgpack.packb.
|
||||
const FX_RESP_PATH_TABLE: &str = "918ba468617368c410aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa974696d657374616d70cb41d26580b4800000a3766961c410bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbba4686f707303a765787069726573cb41d267cf54800000a576616c7565c0a47573656400a76c725f636f7374c0a9696e74657266616365b2544350496e746572666163655b746573745dae696e746572666163655f68617368c4206e5082481873def8612282d21b981c90430ecd80bf5a877711f83dabb06ae938a5737461746500";
|
||||
const FX_RESP_PATH_TABLE_STAMPED: &str = "918ba468617368c410aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa974696d657374616d70cb41d26580b4800000a3766961c410bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbba4686f707303a765787069726573cb41d267cf54800000a576616c7565cb4018500000000000a475736564cb41d26580cfe00000a76c725f636f7374cb400a000000000000a9696e74657266616365b2544350496e746572666163655b746573745dae696e746572666163655f68617368c4206e5082481873def8612282d21b981c90430ecd80bf5a877711f83dabb06ae938a5737461746502";
|
||||
const FX_RESP_BLACKHOLE_DICT: &str = "81c4104242424242424242424242424242424283a6736f75726365c410aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa5756e74696ccb4093480000000000a6726561736f6ea6706172697479";
|
||||
const FX_INT_EDGES: &str = "dc0014007fcc80ccffcd0100cdffffce00010000ceffffffffcf0000000100000000cfffffffffffffffffffe0d0dfd080d1ff7fd18000d2ffff7fffd280000000d3ffffffff7fffffffd38000000000000000";
|
||||
const FX_STR_EDGES: &str = "93a0bf61616161616161616161616161616161616161616161616161616161616161d9206161616161616161616161616161616161616161616161616161616161616161";
|
||||
@@ -3614,9 +4215,11 @@ mod tests {
|
||||
hops: 3,
|
||||
expires: 1235172690.0,
|
||||
value: None,
|
||||
used: 0.0,
|
||||
used: Some(0.0),
|
||||
lr_cost: None,
|
||||
interface: "TCPInterface[test]".to_string(),
|
||||
interface_hash: Some(rns_crypto::sha::sha256(b"TCPInterface[test]").to_vec()),
|
||||
state: Some(0),
|
||||
}]);
|
||||
assert_eq!(
|
||||
hex::encode(encode_response(&resp).unwrap()),
|
||||
@@ -3634,9 +4237,28 @@ mod tests {
|
||||
assert_eq!(entries[0].interface, "TCPInterface[test]");
|
||||
assert_eq!(entries[0].value, None);
|
||||
assert_eq!(entries[0].lr_cost, None);
|
||||
assert_eq!(entries[0].state, Some(0));
|
||||
}
|
||||
other => panic!("wrong variant: {other:?}"),
|
||||
}
|
||||
// A 1.6.0 instance sends neither key.
|
||||
for fixture in [FX_RESP_PATH_TABLE_160, FX_RESP_PATH_TABLE_STAMPED_160] {
|
||||
match decode_response_for_request(
|
||||
&hex::decode(fixture).unwrap(),
|
||||
&RpcRequest::GetPathTable { max_hops: None },
|
||||
)
|
||||
.unwrap()
|
||||
{
|
||||
RpcResponse::PathTable(entries) => {
|
||||
assert_eq!(entries[0].interface, "TCPInterface[test]");
|
||||
assert_eq!(
|
||||
(&entries[0].interface_hash, entries[0].state),
|
||||
(&None, None)
|
||||
);
|
||||
}
|
||||
other => panic!("wrong variant: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -3648,9 +4270,11 @@ mod tests {
|
||||
hops: 3,
|
||||
expires: 1235172690.0,
|
||||
value: Some(6.078125),
|
||||
used: 1234567999.5,
|
||||
used: Some(1234567999.5),
|
||||
lr_cost: Some(3.25),
|
||||
interface: "TCPInterface[test]".to_string(),
|
||||
interface_hash: Some(rns_crypto::sha::sha256(b"TCPInterface[test]").to_vec()),
|
||||
state: Some(2),
|
||||
};
|
||||
let resp = RpcResponse::PathTable(vec![entry]);
|
||||
assert_eq!(
|
||||
@@ -3665,8 +4289,13 @@ mod tests {
|
||||
{
|
||||
RpcResponse::PathTable(entries) => {
|
||||
assert_eq!(entries[0].value, Some(6.078125));
|
||||
assert_eq!(entries[0].used, 1234567999.5);
|
||||
assert_eq!(entries[0].used, Some(1234567999.5));
|
||||
assert_eq!(entries[0].lr_cost, Some(3.25));
|
||||
assert_eq!(entries[0].state, Some(2));
|
||||
assert_eq!(
|
||||
entries[0].interface_hash.as_deref(),
|
||||
Some(&rns_crypto::sha::sha256(b"TCPInterface[test]")[..])
|
||||
);
|
||||
}
|
||||
other => panic!("wrong variant: {other:?}"),
|
||||
}
|
||||
@@ -3996,7 +4625,10 @@ mod tests {
|
||||
hex::encode(encode_medium_path_timeout(Some(22.0)).unwrap()),
|
||||
"cb4036000000000000"
|
||||
);
|
||||
assert_eq!(hex::encode(encode_empty_dict().unwrap()), "80");
|
||||
assert_eq!(
|
||||
hex::encode(encode_response(&RpcResponse::LinkDistribution(Vec::new())).unwrap()),
|
||||
"80"
|
||||
);
|
||||
assert_eq!(hex::encode(encode_none().unwrap()), "c0");
|
||||
assert_eq!(hex::encode(encode_optional_bool(Some(true)).unwrap()), "c3");
|
||||
assert_eq!(
|
||||
@@ -4033,7 +4665,7 @@ mod tests {
|
||||
));
|
||||
assert!(matches!(
|
||||
decode("80", RpcRequest::GetLinkDistribution),
|
||||
RpcResponse::Ok
|
||||
RpcResponse::LinkDistribution(ref e) if e.is_empty()
|
||||
));
|
||||
assert!(matches!(
|
||||
decode("c0", RpcRequest::GetProfilingResults),
|
||||
|
||||
@@ -372,7 +372,6 @@ async fn respond(request: RpcRequest, backend: &RpcBackend) -> Result<Vec<u8>, R
|
||||
Err(response) => rpc::encode_response(&response),
|
||||
};
|
||||
}
|
||||
RpcRequest::GetLinkDistribution => return rpc::encode_empty_dict(),
|
||||
RpcRequest::GetProfilingResults => return rpc::encode_none(),
|
||||
RpcRequest::ManageInterface { operation, name } => {
|
||||
let Some(handle) = backend.interface_manager.as_ref().and_then(|m| m.get()) else {
|
||||
@@ -613,9 +612,11 @@ async fn process_rpc_request(
|
||||
hops: e.hops,
|
||||
expires: e.expires,
|
||||
value: e.value,
|
||||
used: e.used,
|
||||
used: Some(e.used),
|
||||
lr_cost: e.lr_cost,
|
||||
interface: e.interface,
|
||||
interface_hash: Some(e.interface_hash.to_vec()),
|
||||
state: Some(e.state as u8),
|
||||
})
|
||||
.collect();
|
||||
RpcResponse::PathTable(rpc_entries)
|
||||
@@ -665,9 +666,27 @@ async fn process_rpc_request(
|
||||
_ => unexpected_transport_response("active link count query"),
|
||||
}
|
||||
}
|
||||
// Upstream answers `{}` when the table cannot be read (Transport.py).
|
||||
RpcRequest::GetLinkDistribution => {
|
||||
match query_transport(transport_tx, TransportQuery::GetLinkDistribution).await {
|
||||
Ok(TransportQueryResponse::LinkDistribution(entries)) => {
|
||||
RpcResponse::LinkDistribution(entries.iter().map(Into::into).collect())
|
||||
}
|
||||
_ => RpcResponse::LinkDistribution(Vec::new()),
|
||||
}
|
||||
}
|
||||
// An error dictionary would become a Python client's table, so a
|
||||
// failure answers `{}` too.
|
||||
RpcRequest::GetKnownDestinations => {
|
||||
match query_transport(transport_tx, TransportQuery::GetKnownDestinations).await {
|
||||
Ok(TransportQueryResponse::KnownDestinations(rows)) => {
|
||||
RpcResponse::KnownDestinations(rows.iter().map(Into::into).collect())
|
||||
}
|
||||
_ => RpcResponse::KnownDestinations(Vec::new()),
|
||||
}
|
||||
}
|
||||
RpcRequest::GetLowestInterfaceBitrate
|
||||
| RpcRequest::GetMediumPathTimeout
|
||||
| RpcRequest::GetLinkDistribution
|
||||
| RpcRequest::GetProfilingResults
|
||||
| RpcRequest::ManageInterface { .. } => {
|
||||
RpcResponse::Error("request needs the control server's state".to_string())
|
||||
@@ -1108,6 +1127,8 @@ mod tests {
|
||||
RpcRequest::UnretainDestination {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::GetLinkDistribution,
|
||||
RpcRequest::GetKnownDestinations,
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1290,7 +1311,13 @@ mod tests {
|
||||
let rpc_key = b"closed_actor_key".to_vec();
|
||||
let port = spawn_test_rpc_server(rpc_key.clone(), tx, shutdown.clone()).await;
|
||||
|
||||
for request in all_rpc_requests() {
|
||||
// The table getters answer `{}` instead, as upstream's do.
|
||||
for request in all_rpc_requests().into_iter().filter(|request| {
|
||||
!matches!(
|
||||
request,
|
||||
RpcRequest::GetLinkDistribution | RpcRequest::GetKnownDestinations
|
||||
)
|
||||
}) {
|
||||
let response = rpc_client_request(port, &rpc_key, request).await;
|
||||
assert!(
|
||||
matches!(response, RpcResponse::Error(_)),
|
||||
@@ -1621,6 +1648,20 @@ listener.close()
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
TransportQuery::GetLinkDistribution => {
|
||||
let mut entry =
|
||||
rns_transport::messages::LinkDistributionRpcEntry::default();
|
||||
entry.destination_hash = [0x11; 16];
|
||||
entry.active = 1;
|
||||
TransportQueryResponse::LinkDistribution(vec![entry])
|
||||
}
|
||||
TransportQuery::GetKnownDestinations => {
|
||||
let mut row = rns_transport::store::KnownDestinationRow::new(
|
||||
[0x22; 16], 7.5, [3; 64],
|
||||
);
|
||||
row.used = -1.0;
|
||||
TransportQueryResponse::KnownDestinations(vec![row])
|
||||
}
|
||||
_ => TransportQueryResponse::Error("unexpected".into()),
|
||||
};
|
||||
let _ = response_tx.send(response);
|
||||
@@ -1629,6 +1670,41 @@ listener.close()
|
||||
tx
|
||||
}
|
||||
|
||||
/// The link table and known destinations come from the transport; a
|
||||
/// transport that cannot answer leaves `{}`, as upstream's fallbacks do.
|
||||
#[tokio::test]
|
||||
async fn link_distribution_and_known_destinations_answer_from_the_transport() {
|
||||
let backend = RpcBackend::new(stats_transport(Vec::new()));
|
||||
for request in [
|
||||
RpcRequest::GetLinkDistribution,
|
||||
RpcRequest::GetKnownDestinations,
|
||||
] {
|
||||
let reply = respond(request.clone(), &backend).await.unwrap();
|
||||
match rpc::decode_response_for_request(&reply, &request).unwrap() {
|
||||
RpcResponse::LinkDistribution(entries) => {
|
||||
assert_eq!(entries.len(), 1);
|
||||
assert_eq!(entries[0].destination_hash, vec![0x11; 16]);
|
||||
assert_eq!(entries[0].active, 1);
|
||||
}
|
||||
RpcResponse::KnownDestinations(entries) => {
|
||||
assert_eq!(entries.len(), 1);
|
||||
assert_eq!(entries[0].destination_hash, vec![0x22; 16]);
|
||||
assert_eq!((entries[0].last_heard, entries[0].used), (7.5, -1.0));
|
||||
}
|
||||
other => panic!("unexpected {other:?}"),
|
||||
}
|
||||
}
|
||||
let (closed, _) = mpsc::channel(1);
|
||||
let backend = RpcBackend::new(closed);
|
||||
for request in [
|
||||
RpcRequest::GetLinkDistribution,
|
||||
RpcRequest::GetKnownDestinations,
|
||||
] {
|
||||
let reply = respond(request, &backend).await.unwrap();
|
||||
assert_eq!(hex::encode(reply), "80");
|
||||
}
|
||||
}
|
||||
|
||||
/// Expected bytes are upstream 1.6.0 replies.
|
||||
#[tokio::test]
|
||||
async fn lowest_bitrate_and_medium_path_timeout_answer_as_upstream() {
|
||||
@@ -1682,10 +1758,6 @@ listener.close()
|
||||
async fn stub_replies_match_upstream() {
|
||||
let backend = RpcBackend::new(stats_transport(Vec::new()));
|
||||
let reply = |request| respond(request, &backend);
|
||||
assert_eq!(
|
||||
hex::encode(reply(RpcRequest::GetLinkDistribution).await.unwrap()),
|
||||
"80"
|
||||
);
|
||||
assert_eq!(
|
||||
hex::encode(reply(RpcRequest::GetProfilingResults).await.unwrap()),
|
||||
"c0"
|
||||
|
||||
@@ -531,7 +531,7 @@ mod tests {
|
||||
policy: InstancePolicy,
|
||||
options: InitOptions,
|
||||
) -> Result<ReticulumHandle, InstanceStartupError> {
|
||||
reticulum::init_with_policy(
|
||||
crate::destination_stamper::test_settings::around_init(reticulum::init_with_policy(
|
||||
self.0.to_str(),
|
||||
None,
|
||||
ShutdownSignal::new(),
|
||||
@@ -539,7 +539,7 @@ mod tests {
|
||||
options,
|
||||
Default::default(),
|
||||
policy,
|
||||
)
|
||||
))
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -508,7 +508,7 @@ async fn wait_for_path(
|
||||
) -> Duration {
|
||||
let deadline = Instant::now() + path_timeout(handle, timeout).await;
|
||||
let h = pretty_hex_rep(&dest_hash);
|
||||
let has_path = || async { handle.has_path(dest_hash).await.unwrap_or(false) };
|
||||
let has_path = || async { rns_tools::has_local_path(handle, dest_hash).await };
|
||||
if !has_path().await {
|
||||
let _ = handle
|
||||
.transport_tx
|
||||
|
||||
@@ -73,14 +73,35 @@ struct Args {
|
||||
#[arg(short, long)]
|
||||
table: bool,
|
||||
|
||||
/// Sort the path table by last use, most recent first
|
||||
/// Show in-use paths only
|
||||
#[arg(short = 'a', long)]
|
||||
active: bool,
|
||||
|
||||
/// Show path usage time
|
||||
#[arg(short = 'u', long)]
|
||||
usage: bool,
|
||||
|
||||
/// Show via transport IDs
|
||||
#[arg(short = 'V', long)]
|
||||
vias: bool,
|
||||
|
||||
/// Show path expiry times
|
||||
#[arg(short = 'E', long)]
|
||||
expiry: bool,
|
||||
|
||||
/// Maximum hops to filter path table by
|
||||
#[arg(short = 'm', long, value_name = "hops", allow_negative_numbers = true)]
|
||||
max: Option<i64>,
|
||||
|
||||
/// Minimum value to filter path table by
|
||||
#[arg(
|
||||
short = 'M',
|
||||
long = "min-value",
|
||||
value_name = "value",
|
||||
allow_negative_numbers = true
|
||||
)]
|
||||
min_value: Option<f64>,
|
||||
|
||||
/// Show announce rate info
|
||||
#[arg(short, long)]
|
||||
rates: bool,
|
||||
@@ -126,11 +147,11 @@ struct Args {
|
||||
unblackhole: bool,
|
||||
|
||||
/// Duration of blackhole enforcement in hours
|
||||
#[arg(long)]
|
||||
#[arg(long, value_name = "hours")]
|
||||
duration: Option<f64>,
|
||||
|
||||
/// Reason for blackholing identity
|
||||
#[arg(long)]
|
||||
#[arg(long, value_name = "reason")]
|
||||
reason: Option<String>,
|
||||
|
||||
/// View published blackhole list for remote transport instance
|
||||
@@ -141,6 +162,14 @@ struct Args {
|
||||
#[arg(short, long)]
|
||||
json: bool,
|
||||
|
||||
/// Analyze tables
|
||||
#[arg(short = 'A', long)]
|
||||
analyze: bool,
|
||||
|
||||
/// Path to capture file for analyze mode
|
||||
#[arg(long, value_name = "path")]
|
||||
capture: Option<String>,
|
||||
|
||||
/// Hexadecimal hash of the destination
|
||||
destination: Option<String>,
|
||||
|
||||
@@ -180,7 +209,8 @@ pub(crate) async fn main() -> ExitCode {
|
||||
|| args.rates
|
||||
|| destination.is_some()
|
||||
|| args.drop_via
|
||||
|| args.blackholed)
|
||||
|| args.blackholed
|
||||
|| args.analyze)
|
||||
{
|
||||
let help = <Args as clap::CommandFactory>::command()
|
||||
.render_help()
|
||||
@@ -229,8 +259,11 @@ async fn dispatch_local(args: &Args, ctx: &ClientCtx, destination: Option<&str>)
|
||||
if args.unblackhole {
|
||||
return do_unblackhole(ctx, destination).await;
|
||||
}
|
||||
if args.analyze {
|
||||
return analyze_tables(ctx).await;
|
||||
}
|
||||
if args.table {
|
||||
return show_path_table(ctx, destination, args.max, args.json, args.usage).await;
|
||||
return show_path_table(ctx, destination, args).await;
|
||||
}
|
||||
if args.rates {
|
||||
return show_rate_table(ctx, destination, args.json).await;
|
||||
@@ -620,14 +653,50 @@ fn table_filter(destination: Option<&str>) -> Result<Option<[u8; 16]>, ExitCode>
|
||||
}
|
||||
}
|
||||
|
||||
/// rnpath.py, local shared instance.
|
||||
async fn show_path_table(
|
||||
ctx: &ClientCtx,
|
||||
destination: Option<&str>,
|
||||
max_hops: Option<i64>,
|
||||
/// rnpath.py `-A`: the tables are fetched, then the stub upstream ships at
|
||||
/// 1.6.1 prints its line; `--capture` is accepted and unused.
|
||||
async fn analyze_tables(ctx: &ClientCtx) -> ExitCode {
|
||||
for table in [
|
||||
RpcRequest::GetPathTable { max_hops: None },
|
||||
RpcRequest::GetRateTable,
|
||||
RpcRequest::GetLinkDistribution,
|
||||
] {
|
||||
if let Err(e) = request(ctx, &table).await {
|
||||
tracing::debug!("Shared instance RPC failed while analyzing tables: {e}");
|
||||
}
|
||||
}
|
||||
println!("Not yet implemented");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
/// How rnpath.py renders `-t`.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct TableView {
|
||||
filter: Option<[u8; 16]>,
|
||||
json: bool,
|
||||
usage: bool,
|
||||
) -> ExitCode {
|
||||
active: bool,
|
||||
vias: bool,
|
||||
expiry: bool,
|
||||
min_value: Option<f64>,
|
||||
}
|
||||
|
||||
impl TableView {
|
||||
fn new(args: &Args, filter: Option<[u8; 16]>) -> Self {
|
||||
Self {
|
||||
filter,
|
||||
json: args.json,
|
||||
usage: args.usage,
|
||||
active: args.active,
|
||||
vias: args.vias,
|
||||
expiry: args.expiry,
|
||||
min_value: args.min_value,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// rnpath.py, local shared instance.
|
||||
async fn show_path_table(ctx: &ClientCtx, destination: Option<&str>, args: &Args) -> ExitCode {
|
||||
let filter = match table_filter(destination) {
|
||||
Ok(filter) => filter,
|
||||
Err(code) => return code,
|
||||
@@ -637,89 +706,149 @@ async fn show_path_table(
|
||||
Ok(other) => return unexpected(other),
|
||||
Err(e) => return rpc_failed(e),
|
||||
};
|
||||
if let Some(max) = max_hops {
|
||||
if let Some(max) = args.max {
|
||||
table.retain(|e| i64::from(e.hops) <= max);
|
||||
}
|
||||
table.sort_by(|a, b| (&a.interface, a.hops).cmp(&(&b.interface, b.hops)));
|
||||
print_path_table(table, filter, json, usage, now_epoch())
|
||||
print_path_table(table, TableView::new(args, filter), now_epoch())
|
||||
}
|
||||
|
||||
fn print_path_table(
|
||||
mut table: Vec<rpc::PathTableEntry>,
|
||||
filter: Option<[u8; 16]>,
|
||||
json: bool,
|
||||
usage: bool,
|
||||
now: f64,
|
||||
) -> ExitCode {
|
||||
fn print_path_table(mut table: Vec<rpc::PathTableEntry>, view: TableView, now: f64) -> ExitCode {
|
||||
// rnpath.py dumps the whole table, filter or not.
|
||||
if json {
|
||||
if view.json {
|
||||
println!("{}", path_table_json(&table));
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
if usage {
|
||||
if view.usage {
|
||||
sort_by_usage(&mut table);
|
||||
}
|
||||
let mut displayed = 0;
|
||||
for entry in &table {
|
||||
if filter.is_none_or(|f| entry.hash == f) {
|
||||
if view.filter.is_none_or(|f| entry.hash == f) {
|
||||
displayed += 1;
|
||||
println!("{}", path_table_line(entry, now));
|
||||
if let Some(line) = path_table_line(entry, view, now) {
|
||||
println!("{line}");
|
||||
}
|
||||
}
|
||||
}
|
||||
if filter.is_some() && displayed == 0 {
|
||||
if view.filter.is_some() && displayed == 0 {
|
||||
println!("No path known");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
/// rnpath.py.
|
||||
fn path_table_line(entry: &rpc::PathTableEntry, now: f64) -> String {
|
||||
format!(
|
||||
"{} {:>3}h via {} on {} expires in {} {}",
|
||||
/// rnpath.py; `None` for a row `-M` or `-a` filters out.
|
||||
fn path_table_line(entry: &rpc::PathTableEntry, view: TableView, now: f64) -> Option<String> {
|
||||
if let Some(min_value) = view.min_value.filter(|v| *v != 0.0) {
|
||||
let value = entry.value.unwrap_or(0.0);
|
||||
if value == 0.0 || value < min_value {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let state = match entry.state {
|
||||
Some(2) => " (R)",
|
||||
Some(1) => " (u)",
|
||||
_ => " (?)",
|
||||
};
|
||||
let usage = match entry.used {
|
||||
None => ", no usage info".to_string(),
|
||||
Some(used) => {
|
||||
if view.active && used == 0.0 {
|
||||
return None;
|
||||
}
|
||||
match (view.usage, used != 0.0) {
|
||||
(true, true) => format!(
|
||||
", last used {} ago",
|
||||
prettytime(PyNum::Float(now - used), false)
|
||||
),
|
||||
(true, false) => ", never used".to_string(),
|
||||
(false, _) => String::new(),
|
||||
}
|
||||
}
|
||||
};
|
||||
let via = if view.vias {
|
||||
format!(
|
||||
" via {}",
|
||||
pretty_hex_rep(entry.via.as_deref().unwrap_or_default())
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let expiry = if view.expiry {
|
||||
format!(
|
||||
" expires in {}",
|
||||
prettytime(PyNum::Float(entry.expires - now), true)
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
Some(format!(
|
||||
"{} {:>3}h{state}{via} on {}{expiry} {}{usage}",
|
||||
pretty_hex_rep(&entry.hash),
|
||||
entry.hops,
|
||||
pretty_hex_rep(entry.via.as_deref().unwrap_or_default()),
|
||||
entry.interface,
|
||||
prettytime(PyNum::Float(entry.expires - now), true),
|
||||
cost_suffix(entry.value, entry.lr_cost)
|
||||
)
|
||||
))
|
||||
}
|
||||
|
||||
/// rnpath.py: most recently used first.
|
||||
/// rnpath.py: most recently used first; a table missing `used` stays as it
|
||||
/// is, as upstream's sort raises and is skipped.
|
||||
fn sort_by_usage(entries: &mut [rpc::PathTableEntry]) {
|
||||
entries.sort_by(|a, b| b.used.total_cmp(&a.used));
|
||||
if entries.iter().all(|e| e.used.is_some()) {
|
||||
entries.sort_by(|a, b| b.used.unwrap_or(0.0).total_cmp(&a.used.unwrap_or(0.0)));
|
||||
}
|
||||
}
|
||||
|
||||
/// The `(dv:<value>/lc:<lr_cost>)` tail of an rnpath 1.6.0 table line (rnpath.py).
|
||||
/// The `(dv:<value>/lc:<lr_cost>)` part of an rnpath table line (rnpath.py).
|
||||
fn cost_suffix(value: Option<f64>, lr_cost: Option<f64>) -> String {
|
||||
format!("(dv:{}/lc:{})", pretty_cost(value), pretty_cost(lr_cost))
|
||||
}
|
||||
|
||||
/// `json.dumps` of the path table rows with bytes as hex (rnpath.py).
|
||||
/// Upstream sends `value` and `used` as int 0 when unset, and floats otherwise.
|
||||
/// `json.dumps` of the path table rows with bytes as hex (rnpath.py), keys a
|
||||
/// peer leaves out omitted. Upstream sends `value` and `used` as int 0 when
|
||||
/// unset, and floats otherwise.
|
||||
fn path_table_json(entries: &[rpc::PathTableEntry]) -> String {
|
||||
let rows: Vec<String> = entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let via = e
|
||||
.via
|
||||
.as_ref()
|
||||
.map(|v| py_json_str(&hex::encode(v)))
|
||||
.unwrap_or_else(|| "null".to_string());
|
||||
format!(
|
||||
"{{\"hash\": {}, \"timestamp\": {}, \"via\": {via}, \"hops\": {}, \"expires\": {}, \"value\": {}, \"used\": {}, \"lr_cost\": {}, \"interface\": {}}}",
|
||||
py_json_str(&hex::encode(&e.hash)),
|
||||
py_float_repr(e.timestamp),
|
||||
e.hops,
|
||||
py_float_repr(e.expires),
|
||||
e.value.map(py_int_or_float).unwrap_or_else(|| "null".to_string()),
|
||||
py_int_or_float(e.used),
|
||||
e.lr_cost.map(py_float_repr).unwrap_or_else(|| "null".to_string()),
|
||||
py_json_str(&e.interface)
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let rows: Vec<String> =
|
||||
entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let via = e
|
||||
.via
|
||||
.as_ref()
|
||||
.map(|v| py_json_str(&hex::encode(v)))
|
||||
.unwrap_or_else(|| "null".to_string());
|
||||
let mut fields = vec![
|
||||
format!("\"hash\": {}", py_json_str(&hex::encode(&e.hash))),
|
||||
format!("\"timestamp\": {}", py_float_repr(e.timestamp)),
|
||||
format!("\"via\": {via}"),
|
||||
format!("\"hops\": {}", e.hops),
|
||||
format!("\"expires\": {}", py_float_repr(e.expires)),
|
||||
format!(
|
||||
"\"value\": {}",
|
||||
e.value
|
||||
.map(py_int_or_float)
|
||||
.unwrap_or_else(|| "null".to_string())
|
||||
),
|
||||
];
|
||||
fields.extend(
|
||||
e.used
|
||||
.map(|used| format!("\"used\": {}", py_int_or_float(used))),
|
||||
);
|
||||
fields.push(format!(
|
||||
"\"lr_cost\": {}",
|
||||
e.lr_cost
|
||||
.map(py_float_repr)
|
||||
.unwrap_or_else(|| "null".to_string())
|
||||
));
|
||||
fields.push(format!("\"interface\": {}", py_json_str(&e.interface)));
|
||||
fields.extend(e.interface_hash.as_ref().map(|hash| {
|
||||
format!("\"interface_hash\": {}", py_json_str(&hex::encode(hash)))
|
||||
}));
|
||||
fields.extend(e.state.map(|state| format!("\"state\": {state}")));
|
||||
format!("{{{}}}", fields.join(", "))
|
||||
})
|
||||
.collect();
|
||||
format!("[{}]", rows.join(", "))
|
||||
}
|
||||
|
||||
@@ -1124,7 +1253,7 @@ async fn await_remote_path(
|
||||
.unwrap_or(0.0),
|
||||
_ => 0.0,
|
||||
};
|
||||
if handle.has_path(dest).await.unwrap_or(false) {
|
||||
if rns_tools::has_local_path(handle, dest).await {
|
||||
return Ok(());
|
||||
}
|
||||
print!("Path to {} requested ", pretty_hex_rep(&dest));
|
||||
@@ -1134,7 +1263,7 @@ async fn await_remote_path(
|
||||
.await;
|
||||
let deadline = deadline_after(timeout.max(medium));
|
||||
loop {
|
||||
if handle.has_path(dest).await.unwrap_or(false) {
|
||||
if rns_tools::has_local_path(handle, dest).await {
|
||||
return Ok(());
|
||||
}
|
||||
if deadline.is_some_and(|d| Instant::now() >= d) {
|
||||
@@ -1164,10 +1293,8 @@ async fn remote_query(
|
||||
) -> Result<Vec<u8>, ExitCode> {
|
||||
print!("{OUTPUT_RST}Establishing link with remote transport instance... ");
|
||||
flush();
|
||||
print!("{OUTPUT_RST}Sending request... ");
|
||||
flush();
|
||||
let client = LinkClient::new(handle.transport_tx.clone(), identity);
|
||||
match client
|
||||
let result = client
|
||||
.query(
|
||||
transport_hash,
|
||||
app,
|
||||
@@ -1176,8 +1303,13 @@ async fn remote_query(
|
||||
REMOTE_HOPS,
|
||||
REMOTE_LINK_TIMEOUT,
|
||||
)
|
||||
.await
|
||||
{
|
||||
.await;
|
||||
// Upstream prints this once the link is up, so not after a link failure.
|
||||
if matches!(result, Ok(_) | Err(LinkClientError::RequestFailed(_))) {
|
||||
print!("{OUTPUT_RST}Sending request... ");
|
||||
flush();
|
||||
}
|
||||
match result {
|
||||
// A timed-out receipt has no response; callers report it as a failed request.
|
||||
Err(LinkClientError::RequestFailed(RequestFailure::TimedOut)) => Ok(Vec::new()),
|
||||
// Upstream's link-closed callback prints, but its exit() runs off the
|
||||
@@ -1296,6 +1428,11 @@ async fn run_remote(args: &Args, remote: &str) -> ExitCode {
|
||||
println!("{OUTPUT_RST}{message}");
|
||||
return stop_runtime(handle, ExitCode::from(255)).await;
|
||||
}
|
||||
// rnpath.py analyzes the local tables even with -R.
|
||||
if args.analyze {
|
||||
println!("{OUTPUT_RST}Not yet implemented");
|
||||
return stop_runtime(handle, ExitCode::SUCCESS).await;
|
||||
}
|
||||
let destination = args.destination.as_deref().filter(|d| !d.is_empty());
|
||||
let filter = match table_filter(destination) {
|
||||
Ok(filter) => filter,
|
||||
@@ -1311,7 +1448,7 @@ fn remote_unimplemented(args: &Args) -> Option<&'static str> {
|
||||
Some("Listing blackholed identities on remote instances not yet implemented")
|
||||
} else if args.blackhole || args.unblackhole {
|
||||
Some("Blackholing identity on remote instances not yet implemented")
|
||||
} else if args.table || args.rates {
|
||||
} else if args.analyze || args.table || args.rates {
|
||||
None
|
||||
} else if args.drop_announces {
|
||||
Some("Dropping announce queues on remote instances not yet implemented")
|
||||
@@ -1360,7 +1497,7 @@ async fn remote_management(
|
||||
{
|
||||
Ok(RpcResponse::PathTable(table)) if !table.is_empty() => {
|
||||
print!("{OUTPUT_RST}");
|
||||
print_path_table(table, filter, args.json, args.usage, now)
|
||||
print_path_table(table, TableView::new(args, filter), now)
|
||||
}
|
||||
_ => remote_request_failed(),
|
||||
}
|
||||
@@ -1522,9 +1659,11 @@ mod tests {
|
||||
hops: 1,
|
||||
expires: 0.0,
|
||||
value: None,
|
||||
used,
|
||||
used: Some(used),
|
||||
lr_cost: None,
|
||||
interface: String::new(),
|
||||
interface_hash: None,
|
||||
state: None,
|
||||
};
|
||||
let mut entries = vec![entry(1, 0.0), entry(2, 20.0), entry(3, 0.0), entry(4, 30.0)];
|
||||
sort_by_usage(&mut entries);
|
||||
|
||||
@@ -173,7 +173,7 @@ async fn run(args: &Args, handle: &ReticulumHandle, dest_hash: [u8; 16], full_na
|
||||
let timeout = args.timeout.filter(|t| *t != 0.0);
|
||||
|
||||
// rnprobe.py.
|
||||
if !local_has_path(handle, dest_hash).await {
|
||||
if !rns_tools::has_local_path(handle, dest_hash).await {
|
||||
let _ = handle
|
||||
.request_path(dest_hash, PathRequestOptions::default())
|
||||
.await;
|
||||
@@ -184,7 +184,7 @@ async fn run(args: &Args, handle: &ReticulumHandle, dest_hash: [u8; 16], full_na
|
||||
}
|
||||
let path_deadline = deadline_after(probe_timeout(handle, dest_hash, timeout).await);
|
||||
let mut i = 0;
|
||||
while !local_has_path(handle, dest_hash).await && !passed(path_deadline) {
|
||||
while !rns_tools::has_local_path(handle, dest_hash).await && !passed(path_deadline) {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
if !json {
|
||||
print!("\u{8}\u{8}{} ", SPINNER[i]);
|
||||
@@ -568,16 +568,6 @@ async fn medium_path_timeout(handle: &ReticulumHandle) -> f64 {
|
||||
.unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// `RNS.Transport.has_path`: this process's own path table.
|
||||
async fn local_has_path(handle: &ReticulumHandle, dest: [u8; 16]) -> bool {
|
||||
matches!(
|
||||
handle
|
||||
.query_transport(TransportQuery::HasPath { dest })
|
||||
.await,
|
||||
Some(TransportQueryResponse::BoolResult(true))
|
||||
)
|
||||
}
|
||||
|
||||
/// `RNS.Transport.hops_to`: this process's own path table.
|
||||
async fn local_hops(handle: &ReticulumHandle, dest: [u8; 16]) -> u8 {
|
||||
match handle
|
||||
|
||||
@@ -87,6 +87,10 @@ struct Args {
|
||||
#[arg(short = 'P', long = "pr-stats")]
|
||||
pr_stats: bool,
|
||||
|
||||
/// Show filtered traffic stats.
|
||||
#[arg(short = 'F', long = "filter-stats")]
|
||||
filter_stats: bool,
|
||||
|
||||
/// Show link stats.
|
||||
#[arg(short, long)]
|
||||
link_stats: bool,
|
||||
@@ -103,6 +107,10 @@ struct Args {
|
||||
#[arg(short, long)]
|
||||
totals: bool,
|
||||
|
||||
/// Display tunnel information.
|
||||
#[arg(short = 'T', long)]
|
||||
tunnels: bool,
|
||||
|
||||
/// Display packets per second in totals.
|
||||
#[arg(short = 'p', long)]
|
||||
pps: bool,
|
||||
@@ -115,8 +123,8 @@ struct Args {
|
||||
#[arg(short = 'z', long)]
|
||||
profiling: bool,
|
||||
|
||||
/// Sort interfaces by [rate, traffic, rx, tx, rxs, txs, anns, arx, atx, arxc, atxc, held,
|
||||
/// prx, ptx, prxc, ptxc, pvs, ivs, flt, txdrp, txdrb, txbuf].
|
||||
/// Sort interfaces by [rate, traffic, rx, tx, rxs, txs, frx, ftx, anns, arx, atx, arxc,
|
||||
/// atxc, afrxc, held, prx, ptx, prxc, ptxc, pvs, ivs, flt, txdrp, txdrb, txbuf].
|
||||
#[arg(short, long)]
|
||||
sort: Option<String>,
|
||||
|
||||
@@ -585,7 +593,7 @@ impl Session {
|
||||
) -> Result<Option<(Value, Option<Value>, Option<Value>)>, u8> {
|
||||
let no_output = args.json;
|
||||
let destination = Destination::hash_from_name_and_identity(MGMT_APP, Some(&identity_hash));
|
||||
if !self.handle.has_path(destination).await.unwrap_or(false) {
|
||||
if !rns_tools::has_local_path(&self.handle, destination).await {
|
||||
if !no_output {
|
||||
outp!(out, "Path to {} requested ", pretty_hex(&destination));
|
||||
out.flush_now();
|
||||
@@ -595,7 +603,7 @@ impl Session {
|
||||
.request_path(destination, PathRequestOptions::default())
|
||||
.await;
|
||||
let started = std::time::Instant::now();
|
||||
while !self.handle.has_path(destination).await.unwrap_or(false) {
|
||||
while !rns_tools::has_local_path(&self.handle, destination).await {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
if started.elapsed().as_secs_f64() > args.timeout {
|
||||
if !no_output {
|
||||
@@ -877,7 +885,8 @@ impl Session {
|
||||
|
||||
/// The stored info dictionary as `list_discovered_interfaces` returns it:
|
||||
/// the file's keys in order, the name sanitized, `"None"` IFAC values
|
||||
/// dropped, and the status appended (Discovery.py).
|
||||
/// dropped, the config entry rebuilt from the record, and the status appended
|
||||
/// (Discovery.py).
|
||||
fn stored_info(root: &Path, record: &DiscoveredInterface) -> Value {
|
||||
let mut map = std::fs::read(root.join(record.filename()))
|
||||
.ok()
|
||||
@@ -892,6 +901,11 @@ fn stored_info(root: &Path, record: &DiscoveredInterface) -> Value {
|
||||
});
|
||||
let status = record.status.unwrap_or(DiscoveryStatus::Unknown);
|
||||
set_key(&mut map, "name", Value::from(record.info.name.as_str()));
|
||||
// The file's entry may come from an rnsd that does not filter announced strings.
|
||||
match rns_transport::discovery::storage::config_entry(record) {
|
||||
Some(entry) => set_key(&mut map, "config_entry", Value::from(entry)),
|
||||
None => map.retain(|(k, _)| k.as_str() != Some("config_entry")),
|
||||
}
|
||||
set_key(&mut map, "status", Value::from(status.as_str()));
|
||||
set_key(&mut map, "status_code", Value::from(status.code()));
|
||||
Value::Map(map)
|
||||
@@ -925,8 +939,12 @@ fn sort_key(name: &str) -> Option<fn(&Value) -> f64> {
|
||||
"rate" | "bitrate" => |i| k(i, "bitrate"),
|
||||
"rx" => |i| k(i, "rxb"),
|
||||
"tx" => |i| k(i, "txb"),
|
||||
"frx" => |i| k(i, "frxb"),
|
||||
"ftx" => |i| k(i, "ftxb"),
|
||||
"rxs" => |i| k(i, "rxs"),
|
||||
"txs" => |i| k(i, "txs"),
|
||||
"frxs" => |i| k(i, "frxs"),
|
||||
"ftxs" => |i| k(i, "ftxs"),
|
||||
"traffic" => |i| k(i, "rxb") + k(i, "txb"),
|
||||
"anns" | "announces" => {
|
||||
|i| k(i, "incoming_announce_frequency") + k(i, "outgoing_announce_frequency")
|
||||
@@ -935,6 +953,7 @@ fn sort_key(name: &str) -> Option<fn(&Value) -> f64> {
|
||||
"atx" => |i| k(i, "outgoing_announce_frequency"),
|
||||
"arxc" => |i| k(i, "arxc"),
|
||||
"atxc" => |i| k(i, "atxc"),
|
||||
"afrxc" => |i| k(i, "afrxc"),
|
||||
"prx" => |i| k(i, "incoming_pr_frequency"),
|
||||
"ptx" => |i| k(i, "outgoing_pr_frequency"),
|
||||
"prxc" => |i| k(i, "prxc"),
|
||||
@@ -979,8 +998,6 @@ fn render_status(
|
||||
outln!(out, "{}", py_json(stats));
|
||||
return;
|
||||
}
|
||||
let astats = args.announce_stats;
|
||||
let pstats = args.pr_stats;
|
||||
|
||||
let mut interfaces: Vec<Value> = match get(stats, "interfaces") {
|
||||
Some(Value::Array(list)) => list.clone(),
|
||||
@@ -1044,7 +1061,7 @@ fn render_status(
|
||||
}
|
||||
|
||||
if args.totals {
|
||||
render_totals(out, stats, astats, pstats, args.pps);
|
||||
render_totals(out, stats, args);
|
||||
}
|
||||
if args.queues {
|
||||
render_queues(out, stats);
|
||||
@@ -1164,6 +1181,9 @@ fn render_interface(out: &mut Out, ifstat: &Value, name: &str, args: &Args) {
|
||||
py_str_opt(get(ifstat, "mtu"))
|
||||
);
|
||||
}
|
||||
if args.tunnels {
|
||||
render_tunnel_lines(out, ifstat, clients);
|
||||
}
|
||||
|
||||
render_radio_lines(out, ifstat);
|
||||
|
||||
@@ -1405,9 +1425,13 @@ fn render_interface(out: &mut Out, ifstat: &Value, name: &str, args: &Args) {
|
||||
}
|
||||
if asr {
|
||||
if truthy(get(ifstat, "arxc")) && truthy(get(ifstat, "atxc")) {
|
||||
let filtered = match get(ifstat, "afrxc").filter(|v| truthy(Some(v))) {
|
||||
Some(count) => format!(", {} filtered", py_str(count)),
|
||||
None => String::new(),
|
||||
};
|
||||
outln!(
|
||||
out,
|
||||
" Announces : {}↓ {}↑ total",
|
||||
" Announces : {}↓ {}↑ total{filtered}",
|
||||
py_str_opt(get(ifstat, "arxc")),
|
||||
py_str_opt(get(ifstat, "atxc"))
|
||||
);
|
||||
@@ -1436,6 +1460,73 @@ fn render_interface(out: &mut Out, ifstat: &Value, name: &str, args: &Args) {
|
||||
));
|
||||
}
|
||||
outln!(out, " Traffic : {txstat}\n {rxstat}");
|
||||
|
||||
if args.filter_stats {
|
||||
let mut frxstat = format!("↓{}", prettysize(num(get(ifstat, "frxb")).f(), "B"));
|
||||
let mut ftxstat = format!("↑{}", prettysize(num(get(ifstat, "ftxb")).f(), "B"));
|
||||
if has(ifstat, "frxs") && has(ifstat, "ftxs") {
|
||||
frxstat.push_str(&format!(" {}", prettyspeed(num(get(ifstat, "frxs")).f())));
|
||||
ftxstat.push_str(&format!(" {}", prettyspeed(num(get(ifstat, "ftxs")).f())));
|
||||
}
|
||||
outln!(out, " Filtered : {ftxstat}\n {frxstat}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `-T` (rnstatus.py): the tunnel id, and for a tunnel the peer's transport.
|
||||
fn render_tunnel_lines(out: &mut Out, ifstat: &Value, clients: Option<Num>) {
|
||||
let tunnel_id = get(ifstat, "tunnel_id").filter(|v| truthy(Some(v)));
|
||||
if clients.is_none_or(|c| c.f() == 0.0) {
|
||||
let shown = tunnel_id
|
||||
.and_then(Value::as_slice)
|
||||
.map_or_else(|| "None".to_string(), hex::encode);
|
||||
outln!(out, " Tunnel ID : {shown}");
|
||||
}
|
||||
if tunnel_id.is_none() {
|
||||
return;
|
||||
}
|
||||
let remote_id = match get(ifstat, "remote_transport_id").filter(|v| truthy(Some(v))) {
|
||||
Some(id) => pretty_hex_value(id),
|
||||
None => "Unknown".to_string(),
|
||||
};
|
||||
outln!(out, " Rem.Tr.ID : {remote_id}");
|
||||
let transport = if truthy(get(ifstat, "rem_is_tn")) {
|
||||
", transport enabled"
|
||||
} else {
|
||||
", no transport"
|
||||
};
|
||||
let implementation = match get(ifstat, "rem_impl").filter(|v| truthy(Some(v))) {
|
||||
Some(name) => py_str(name),
|
||||
None => "Unknown implementation".to_string(),
|
||||
};
|
||||
let version = match get(ifstat, "rem_vers").filter(|v| truthy(Some(v))) {
|
||||
Some(Value::Array(parts)) => {
|
||||
let parts: Vec<String> = parts.iter().map(py_str).collect();
|
||||
format!(" {}{transport}", parts.join("."))
|
||||
}
|
||||
Some(other) => format!(" {}{transport}", py_str(other)),
|
||||
None => ", unknown version".to_string(),
|
||||
};
|
||||
outln!(out, " Rem.Vers. : {implementation}{version}");
|
||||
let cost = |key: &str, label: &str| match not_none(ifstat, key) {
|
||||
Some(value) => format!("{label} {}", pretty_cost_value(value)),
|
||||
None => format!("{label} ?"),
|
||||
};
|
||||
outln!(
|
||||
out,
|
||||
" Rem.Csts. : {}, {}",
|
||||
cost("rem_dst_cost", "Dst"),
|
||||
cost("rem_pr_cost", "PR")
|
||||
);
|
||||
}
|
||||
|
||||
/// `RNS.prettycost`: "n" for anything but an int or a float.
|
||||
fn pretty_cost_value(value: &Value) -> String {
|
||||
match value {
|
||||
Value::Integer(_) | Value::F32(_) | Value::F64(_) => {
|
||||
pretty_cost(Some(num(Some(value)).f()))
|
||||
}
|
||||
_ => "n".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The optional radio, Weave and I2P lines (rnstatus.py), with
|
||||
@@ -1551,30 +1642,33 @@ fn render_radio_lines(out: &mut Out, ifstat: &Value) {
|
||||
}
|
||||
|
||||
/// The traffic totals blocks (rnstatus.py).
|
||||
fn render_totals(out: &mut Out, stats: &Value, astats: bool, pstats: bool, pps: bool) {
|
||||
fn render_totals(out: &mut Out, stats: &Value, args: &Args) {
|
||||
let (astats, pstats) = (args.announce_stats, args.pr_stats);
|
||||
let n = |k: &str| num(get(stats, k)).f();
|
||||
let (mut rxb_str, mut txb_str) = pair(n("rxb"), n("txb"));
|
||||
let rxs = n("rxs");
|
||||
let txs = n("txs");
|
||||
let mut rxstat = format!("{rxb_str} {}", prettyspeed(rxs));
|
||||
let mut txstat = format!("{txb_str} {}", prettyspeed(txs));
|
||||
// Data flow: the share of traffic that is neither announces nor path requests.
|
||||
let data_pct = |rx: bool| {
|
||||
let (whole, parts) = if rx {
|
||||
("rxs", n("prxs") + n("arxs"))
|
||||
} else {
|
||||
("txs", n("ptxs") + n("atxs"))
|
||||
};
|
||||
if truthy(get(stats, whole)) {
|
||||
100.0 - (100.0f64).min(parts / n(whole) * 100.0)
|
||||
} else {
|
||||
100.0
|
||||
}
|
||||
};
|
||||
if (pstats || astats)
|
||||
&& ["prxs", "ptxs", "arxs", "atxs"]
|
||||
.iter()
|
||||
.all(|k| has(stats, k))
|
||||
{
|
||||
let parxs = n("prxs") + n("arxs");
|
||||
let patxs = n("ptxs") + n("atxs");
|
||||
let drxpct = if truthy(get(stats, "rxs")) {
|
||||
100.0 - (100.0f64).min(parxs / rxs * 100.0)
|
||||
} else {
|
||||
100.0
|
||||
};
|
||||
let dtxpct = if truthy(get(stats, "txs")) {
|
||||
100.0 - (100.0f64).min(patxs / txs * 100.0)
|
||||
} else {
|
||||
100.0
|
||||
};
|
||||
let (drxpct, dtxpct) = (data_pct(true), data_pct(false));
|
||||
if rxs > 0.0 {
|
||||
rxstat = format!(
|
||||
"{rxstat}, {}% data ({})",
|
||||
@@ -1590,12 +1684,49 @@ fn render_totals(out: &mut Out, stats: &Value, astats: bool, pstats: bool, pps:
|
||||
);
|
||||
}
|
||||
}
|
||||
if pps {
|
||||
if args.pps {
|
||||
rxstat = format!("{rxstat}, {}", prettysize(n("rxpps"), "pps"));
|
||||
txstat = format!("{txstat}, {}", prettysize(n("txpps"), "pps"));
|
||||
}
|
||||
outln!(out, "\n Totals : {txstat}\n {rxstat}");
|
||||
|
||||
if args.filter_stats {
|
||||
let (mut frxstat, mut ftxstat) = pair(n("frxb"), n("ftxb"));
|
||||
if has(stats, "frxs") && has(stats, "ftxs") {
|
||||
frxstat.push_str(&format!(" {}", prettyspeed(n("frxs"))));
|
||||
ftxstat.push_str(&format!(" {}", prettyspeed(n("ftxs"))));
|
||||
}
|
||||
outln!(
|
||||
out,
|
||||
"\n Filtered : {ftxstat}\n {frxstat}"
|
||||
);
|
||||
}
|
||||
|
||||
if args.link_stats
|
||||
&& ["lrxb", "ltxb", "lrxs", "ltxs"]
|
||||
.iter()
|
||||
.all(|k| has(stats, k))
|
||||
{
|
||||
let (lrxb_str, ltxb_str) = pair(n("lrxb"), n("ltxb"));
|
||||
let link_pct = |link: &str, data: f64| {
|
||||
if data != 0.0 && truthy(get(stats, link)) {
|
||||
(100.0f64).min(n(link) / data * 100.0) as i64
|
||||
} else {
|
||||
0
|
||||
}
|
||||
};
|
||||
let drxs = rxs * (data_pct(true) / 100.0);
|
||||
let dtxs = txs * (data_pct(false) / 100.0);
|
||||
outln!(
|
||||
out,
|
||||
"\n Links : {ltxb_str} {}, {}% of data flow\n {lrxb_str} {}, {}% of data flow",
|
||||
prettyspeed(n("ltxs")),
|
||||
link_pct("ltxs", dtxs),
|
||||
prettyspeed(n("lrxs")),
|
||||
link_pct("lrxs", drxs)
|
||||
);
|
||||
}
|
||||
|
||||
let flow_pct = |part: &str, whole: &str| -> i64 {
|
||||
if truthy(get(stats, whole)) && truthy(get(stats, part)) {
|
||||
(100.0f64).min(n(part) / n(whole) * 100.0) as i64
|
||||
@@ -2243,3 +2374,73 @@ fn truncate_ellipsis(s: &str, limit: usize) -> String {
|
||||
s.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rns_transport::discovery::storage::config_entry;
|
||||
|
||||
/// A record file whose stored entry carries an injected section prints the
|
||||
/// entry rebuilt from the record instead (`-D` and `--json` alike).
|
||||
#[test]
|
||||
fn discovered_details_rebuild_the_config_entry_from_the_record() {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"rnstatus-config-entry-{}-{}",
|
||||
std::process::id(),
|
||||
unix_now()
|
||||
));
|
||||
let store = DiscoveryStore::open(&dir).unwrap();
|
||||
let info = rns_transport::discovery::app_data::DiscoveryInfo {
|
||||
name: "Relay".to_string(),
|
||||
interface_type: "BackboneInterface".to_string(),
|
||||
transport_id: [0x42; 16],
|
||||
reachable_on: Some("relay.example".to_string()),
|
||||
port: Some(4242),
|
||||
impl_name: Some("RNS".to_string()),
|
||||
impl_version: Some("1.6.1".to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
let now = unix_now();
|
||||
let record = DiscoveredInterface {
|
||||
info,
|
||||
network_id: [0x42; 16],
|
||||
hops: 1,
|
||||
stamp_value: 0.0,
|
||||
stamp: Vec::new(),
|
||||
discovered: now,
|
||||
last_heard: now,
|
||||
heard_count: 0,
|
||||
status: None,
|
||||
};
|
||||
store.upsert(record.clone()).unwrap();
|
||||
let path = store.root().join(record.filename());
|
||||
let Value::Map(mut map) =
|
||||
rmpv::decode::read_value(&mut std::fs::read(&path).unwrap().as_slice()).unwrap()
|
||||
else {
|
||||
panic!("record file is a map");
|
||||
};
|
||||
set_key(
|
||||
&mut map,
|
||||
"config_entry",
|
||||
Value::from(
|
||||
"[[Relay]]\n type = BackboneInterface\n[[Evil]]\n type = PipeInterface\n command = x",
|
||||
),
|
||||
);
|
||||
let mut bytes = Vec::new();
|
||||
rmpv::encode::write_value(&mut bytes, &Value::Map(map)).unwrap();
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
|
||||
let records = store.list_filtered(None, &HashSet::new()).unwrap();
|
||||
let info = stored_info(store.root(), &records[0]);
|
||||
assert_eq!(
|
||||
get(&info, "config_entry").and_then(Value::as_str),
|
||||
config_entry(&records[0]).as_deref()
|
||||
);
|
||||
let mut out = Out::new(false);
|
||||
let refs: Vec<&DiscoveredInterface> = records.iter().collect();
|
||||
print_discovered_details(&mut out, &refs, &[&info], false, false);
|
||||
let sections: Vec<&str> = out.buf.lines().filter(|l| l.starts_with(" [[")).collect();
|
||||
assert_eq!(sections, [" [[Relay]]"], "{}", out.buf);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
@@ -295,7 +295,9 @@ async fn listen(args: &Args, interrupt: &ShutdownSignal) -> ! {
|
||||
tracing::info!(target: rns_tools::NOTICE_TARGET, "Executing command [{}] for {requestor}", command.command);
|
||||
let result = rns_tools::rnx::execute(&command).await;
|
||||
tracing::info!(target: rns_tools::NOTICE_TARGET, "Delivering result of command [{}] to {requestor}", command.command);
|
||||
if let Err(e) = responder.respond(RequestOutcome::ReplyValue(result.to_msgpack())) {
|
||||
// Output over the admitted reply size is cut, not dropped.
|
||||
let packed = result.into_msgpack_within(responder.response_byte_limit());
|
||||
if let Err(e) = responder.respond(RequestOutcome::ReplyValue(packed)) {
|
||||
tracing::warn!("could not deliver result of command [{}]: {e}", command.command);
|
||||
}
|
||||
});
|
||||
@@ -498,7 +500,7 @@ impl Client<'_> {
|
||||
async fn ensure_path(&self, timeout: Timeout) -> bool {
|
||||
let handle = self.handle;
|
||||
let hash = self.destination_hash;
|
||||
if handle.has_path(hash).await.unwrap_or(false) {
|
||||
if rns_tools::has_local_path(handle, hash).await {
|
||||
return true;
|
||||
}
|
||||
let _ = handle
|
||||
@@ -510,7 +512,7 @@ impl Client<'_> {
|
||||
let msg = format!("Path to <{}> requested", hex::encode(hash));
|
||||
let found = spin(&msg, async {
|
||||
loop {
|
||||
if handle.has_path(hash).await.unwrap_or(false) {
|
||||
if rns_tools::has_local_path(handle, hash).await {
|
||||
return true;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
|
||||
@@ -23,7 +23,7 @@ pub const RETICULUM_COMPAT_VERSION: &str = rns_runtime::constants::RETICULUM_COM
|
||||
|
||||
/// A tool's `--version` line: its own name and crate version, then the
|
||||
/// releases it follows, `also` first and Reticulum last, as
|
||||
/// `lxmd-rs 1.4.0 (LXMF 1.3.0, Reticulum 1.6.0)`.
|
||||
/// `lxmd-rs 1.4.0 (LXMF 1.3.0, Reticulum 1.6.1)`.
|
||||
pub fn version_line(tool: &str, crate_version: &str, also: &[(&str, &str)]) -> String {
|
||||
let follows: Vec<String> = also
|
||||
.iter()
|
||||
@@ -335,6 +335,21 @@ impl RpcRegistration {
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `RNS.Transport.has_path`: this process's own path table. A
|
||||
/// shared-instance client fills it from the path responses it asks for and
|
||||
/// sends to a destination only once it holds a path; `ReticulumHandle::has_path`
|
||||
/// asks the shared instance instead.
|
||||
pub async fn has_local_path(handle: &ReticulumHandle, destination: [u8; 16]) -> bool {
|
||||
matches!(
|
||||
handle
|
||||
.query_transport(rns_transport::messages::TransportQuery::HasPath { dest: destination })
|
||||
.await,
|
||||
Some(rns_transport::messages::TransportQueryResponse::BoolResult(
|
||||
true
|
||||
))
|
||||
)
|
||||
}
|
||||
|
||||
/// Reticulum.get_medium_path_timeout (Reticulum.py): ask the shared
|
||||
/// instance, or compute Transport.medium_path_timeout (Transport.py)
|
||||
/// from the lowest online interface bitrate. 0 when unknown or on error.
|
||||
|
||||
+121
-3
@@ -152,10 +152,54 @@ impl CommandResult {
|
||||
|
||||
/// Packed result, the response value the listener returns.
|
||||
pub fn to_msgpack(&self) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
rmpv::encode::write_value(&mut out, &self.to_value()).expect("encoding to a Vec");
|
||||
out
|
||||
pack(&self.to_value())
|
||||
}
|
||||
|
||||
/// Packed result of at most `limit` bytes. Output that does not fit is cut,
|
||||
/// stdout first, while `stdout_len`/`stderr_len` keep the real lengths, so
|
||||
/// the client reports it as truncated, as for its own `--stdout` and
|
||||
/// `--stderr` limits (rnx.py).
|
||||
pub fn into_msgpack_within(mut self, limit: usize) -> Vec<u8> {
|
||||
let out_len = self.stdout.as_ref().map_or(0, Vec::len);
|
||||
let err_len = self.stderr.as_ref().map_or(0, Vec::len);
|
||||
let (stdout, stderr) = (self.stdout.take(), self.stderr.take());
|
||||
self.stdout = stdout.as_ref().map(|_| Vec::new());
|
||||
self.stderr = stderr.as_ref().map(|_| Vec::new());
|
||||
// Empty bins take a 2-byte header; a bin32 header takes 5.
|
||||
let frame = self.to_msgpack().len();
|
||||
self.stdout = stdout;
|
||||
self.stderr = stderr;
|
||||
if frame + out_len + err_len + 6 > limit {
|
||||
let mut room = limit.saturating_sub(frame + 6);
|
||||
for (stream, len) in [(&mut self.stderr, err_len), (&mut self.stdout, out_len)] {
|
||||
if let Some(bytes) = stream.as_mut() {
|
||||
let keep = len.min(room);
|
||||
bytes.truncate(keep);
|
||||
room -= keep;
|
||||
}
|
||||
}
|
||||
}
|
||||
let bin = |b: Option<Vec<u8>>| b.map_or(Value::Nil, Value::Binary);
|
||||
let int = |i: Option<u64>| i.map_or(Value::Nil, |n| Value::from(n as i64));
|
||||
pack(&Value::Array(vec![
|
||||
Value::Boolean(self.executed),
|
||||
self.retcode.map_or(Value::Nil, Value::from),
|
||||
bin(self.stdout),
|
||||
bin(self.stderr),
|
||||
int(self.stdout_len),
|
||||
int(self.stderr_len),
|
||||
Value::F64(self.started),
|
||||
self.concluded.map_or(Value::Nil, Value::F64),
|
||||
]))
|
||||
}
|
||||
}
|
||||
|
||||
fn pack(value: &Value) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
rmpv::encode::write_value(&mut out, value).expect("encoding to a Vec");
|
||||
// Deferred replies are admitted by allocation capacity; growth after a large
|
||||
// output doubles it, and a 16 MB result would be refused.
|
||||
out.into_boxed_slice().into_vec()
|
||||
}
|
||||
|
||||
fn now() -> f64 {
|
||||
@@ -604,3 +648,77 @@ pub fn client_result(
|
||||
};
|
||||
(rendered, Some(response), code)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn packed_result_holds_no_spare_capacity() {
|
||||
let result = CommandResult {
|
||||
executed: true,
|
||||
retcode: Some(0),
|
||||
stdout: Some(vec![0x5a; 16_000_000]),
|
||||
stderr: Some(Vec::new()),
|
||||
stdout_len: Some(16_000_000),
|
||||
stderr_len: Some(0),
|
||||
started: 1.0,
|
||||
concluded: Some(2.0),
|
||||
};
|
||||
let packed = result.to_msgpack();
|
||||
assert!(packed.len() > 16_000_000);
|
||||
assert_eq!(packed.capacity(), packed.len());
|
||||
}
|
||||
|
||||
fn output_result(stdout: usize, stderr: usize) -> CommandResult {
|
||||
CommandResult {
|
||||
executed: true,
|
||||
retcode: Some(0),
|
||||
stdout: Some(vec![b'o'; stdout]),
|
||||
stderr: Some(vec![b'e'; stderr]),
|
||||
stdout_len: Some(stdout as u64),
|
||||
stderr_len: Some(stderr as u64),
|
||||
started: 1.0,
|
||||
concluded: Some(2.0),
|
||||
}
|
||||
}
|
||||
|
||||
fn streams(packed: &[u8]) -> (usize, usize, i64, i64) {
|
||||
let Value::Array(items) = rmpv::decode::read_value(&mut &packed[..]).unwrap() else {
|
||||
panic!("result is an array");
|
||||
};
|
||||
let len = |v: &Value| v.as_slice().unwrap().len();
|
||||
let int = |v: &Value| v.as_i64().unwrap();
|
||||
(
|
||||
len(&items[2]),
|
||||
len(&items[3]),
|
||||
int(&items[4]),
|
||||
int(&items[5]),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_result_that_fits_packs_unchanged() {
|
||||
let result = output_result(70_000, 300);
|
||||
assert_eq!(
|
||||
result.clone().into_msgpack_within(1 << 20),
|
||||
result.to_msgpack()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_oversized_result_is_cut_stdout_first_and_keeps_the_real_lengths() {
|
||||
let packed = output_result(70_000, 300).into_msgpack_within(50_000);
|
||||
assert!(packed.len() <= 50_000);
|
||||
assert_eq!(packed.capacity(), packed.len());
|
||||
let (out, err, out_len, err_len) = streams(&packed);
|
||||
assert!(out > 49_000 && out < 50_000);
|
||||
assert_eq!((err, out_len, err_len), (300, 70_000, 300));
|
||||
|
||||
let packed = output_result(70_000, 300).into_msgpack_within(100);
|
||||
assert!(packed.len() <= 100);
|
||||
let (out, err, out_len, err_len) = streams(&packed);
|
||||
assert_eq!((out, out_len, err_len), (0, 70_000, 300));
|
||||
assert!(err < 300);
|
||||
}
|
||||
}
|
||||
@@ -111,6 +111,11 @@ fn write_responder_config(tmp: &TempDir, shared_port: u16, control_port: u16, li
|
||||
enable_transport = Yes\n\
|
||||
respond_to_probes = Yes\n\
|
||||
\n\
|
||||
[stamps]\n\
|
||||
# A cheap probe-destination stamp: a debug build under load can take\n\
|
||||
# longer than the path deadline to make the default value-25 one.\n\
|
||||
destination_value = 8\n\
|
||||
\n\
|
||||
[logging]\n\
|
||||
loglevel = 1\n\
|
||||
\n\
|
||||
|
||||
@@ -13,6 +13,19 @@ enum InboundOrigin {
|
||||
CachedPacket,
|
||||
}
|
||||
|
||||
/// Python 1.6.1's verdict on one inbound frame (`Transport.inbound`): filtered
|
||||
/// unless preprocessing admits it.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
|
||||
pub(super) enum InboundVerdict {
|
||||
#[default]
|
||||
Filtered,
|
||||
/// Admitted, and counted in `rx_packets`.
|
||||
Accepted,
|
||||
/// Admitted without reaching `rx_packets`: a path request batched into one
|
||||
/// already in flight (Transport.py:2256).
|
||||
Batched,
|
||||
}
|
||||
|
||||
/// A transit link proof's verdict; only a bad signature is a protocol
|
||||
/// violation (Transport.py).
|
||||
#[derive(PartialEq, Eq)]
|
||||
@@ -43,13 +56,13 @@ impl TransportActor {
|
||||
fields(interface_id = packet.interface_id, raw_len = packet.raw.len()),
|
||||
)]
|
||||
pub(super) fn on_inbound(&mut self, packet: crate::messages::InboundPacket) {
|
||||
self.on_inbound_inner(packet, InboundOrigin::Wire);
|
||||
self.on_inbound_counted(packet, InboundOrigin::Wire);
|
||||
}
|
||||
|
||||
/// An announce the ingress controller held, released for processing; it
|
||||
/// can be held again (Interface.py).
|
||||
/// can be held again, and counts again (Interface.py).
|
||||
pub(super) fn on_released_announce(&mut self, announce: crate::ingress::HeldAnnounce) {
|
||||
self.on_inbound_inner(
|
||||
self.on_inbound_counted(
|
||||
crate::messages::InboundPacket {
|
||||
raw: announce.raw,
|
||||
interface_id: announce.receiving_interface_id,
|
||||
@@ -69,8 +82,8 @@ impl TransportActor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Upstream drops stamp and blackhole rejections silently; anything else
|
||||
/// is a protocol violation (Transport.py).
|
||||
/// Upstream counts stamp and blackhole rejections as filtered; anything
|
||||
/// else is a protocol violation (Transport.py).
|
||||
fn reject_announce(
|
||||
&mut self,
|
||||
header: &rns_wire::header::PacketHeader,
|
||||
@@ -89,6 +102,8 @@ impl TransportActor {
|
||||
);
|
||||
if reason == InvalidAnnounce::Invalid {
|
||||
self.protocol_violation(interface_id);
|
||||
} else {
|
||||
self.filtered_announce(interface_id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,7 +143,7 @@ impl TransportActor {
|
||||
if raw.len() > 500 {
|
||||
return;
|
||||
}
|
||||
self.on_inbound_inner(
|
||||
self.on_inbound_counted(
|
||||
crate::messages::InboundPacket {
|
||||
raw,
|
||||
interface_id: 0,
|
||||
@@ -140,6 +155,42 @@ impl TransportActor {
|
||||
);
|
||||
}
|
||||
|
||||
/// Python `Transport.inbound`: each frame counts once, on its interface and
|
||||
/// parent, as accepted or filtered bytes; cache replays are not counted.
|
||||
fn on_inbound_counted(
|
||||
&mut self,
|
||||
packet: crate::messages::InboundPacket,
|
||||
origin: InboundOrigin,
|
||||
) {
|
||||
let (interface_id, len) = (packet.interface_id, packet.raw.len() as u64);
|
||||
if self.is_detaching(interface_id) {
|
||||
return;
|
||||
}
|
||||
let outer = std::mem::take(&mut self.inbound_verdict);
|
||||
self.on_inbound_inner(packet, origin);
|
||||
let verdict = std::mem::replace(&mut self.inbound_verdict, outer);
|
||||
if origin == InboundOrigin::CachedPacket {
|
||||
return;
|
||||
}
|
||||
if verdict == InboundVerdict::Accepted {
|
||||
self.count_rx_packet();
|
||||
}
|
||||
let accepted = verdict != InboundVerdict::Filtered;
|
||||
let Some(entry) = self.interfaces.get_mut(&interface_id) else {
|
||||
return;
|
||||
};
|
||||
let parent = entry.parent_id;
|
||||
entry.received.count(len, accepted);
|
||||
if let Some(parent) = parent.and_then(|id| self.interfaces.get_mut(&id)) {
|
||||
parent.received.count(len, accepted);
|
||||
}
|
||||
}
|
||||
|
||||
/// Python's `preprocess_inbound` verdict on the frame being processed.
|
||||
pub(super) fn set_inbound_verdict(&mut self, verdict: InboundVerdict) {
|
||||
self.inbound_verdict = verdict;
|
||||
}
|
||||
|
||||
fn on_inbound_inner(&mut self, packet: crate::messages::InboundPacket, origin: InboundOrigin) {
|
||||
// Transport.py: frames of two bytes or less are protocol
|
||||
// violations before any IFAC handling.
|
||||
@@ -249,8 +300,15 @@ impl TransportActor {
|
||||
return;
|
||||
}
|
||||
|
||||
// Transport.HOP_LIMITER, on wire hops (Transport.py).
|
||||
if parsed.hops >= self.hop_limiter {
|
||||
// Interface.hop_limiter, then Transport.HOP_LIMITER, on wire hops (Transport.py).
|
||||
let interface_limit = self
|
||||
.interfaces
|
||||
.get(&packet.interface_id)
|
||||
.and_then(|entry| entry.hop_limiter)
|
||||
.filter(|limit| *limit > 0);
|
||||
if interface_limit.is_some_and(|limit| parsed.hops >= limit)
|
||||
|| parsed.hops >= self.hop_limiter
|
||||
{
|
||||
trace!(
|
||||
hops = parsed.hops,
|
||||
interface_id = packet.interface_id,
|
||||
@@ -378,24 +436,21 @@ impl TransportActor {
|
||||
}
|
||||
}
|
||||
|
||||
if origin != InboundOrigin::CachedPacket {
|
||||
self.count_rx_packet();
|
||||
// Python 1.6.1 admits announces and path requests at the end of their
|
||||
// own gates, everything else here (Transport.py:2266).
|
||||
let path_request = parsed.flags.packet_type != rns_wire::flags::PacketType::Announce
|
||||
&& parsed.destination_hash == Self::path_request_dest_hash();
|
||||
if parsed.flags.packet_type != rns_wire::flags::PacketType::Announce && !path_request {
|
||||
self.set_inbound_verdict(InboundVerdict::Accepted);
|
||||
}
|
||||
|
||||
// Destination-type filtering runs after the packet filter and before
|
||||
// the hash is remembered (Transport.py).
|
||||
// Announce gates run after the packet filter and before the hash is
|
||||
// remembered (Transport.py).
|
||||
if parsed.flags.packet_type == rns_wire::flags::PacketType::Announce
|
||||
&& !self.admit_announce_type(&raw[data_offset..], parsed.hops, packet.interface_id)
|
||||
&& !self.admit_announce_ingress(&raw, &parsed, data_offset, packet.interface_id)
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Transport.py: announce frames above the base MTU.
|
||||
if parsed.flags.packet_type == rns_wire::flags::PacketType::Announce
|
||||
&& raw.len() > rns_wire::constants::MTU
|
||||
{
|
||||
self.protocol_violation(packet.interface_id);
|
||||
return;
|
||||
}
|
||||
|
||||
if check_hashlist {
|
||||
self.packet_hashlist.insert(pkt_hash);
|
||||
@@ -430,28 +485,46 @@ impl TransportActor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Python's announce ingress filter: a short name hash is a protocol
|
||||
/// violation, blocked and unrequired types are dropped silently.
|
||||
fn admit_announce_type(
|
||||
/// Python's announce ingress in `preprocess_inbound`, in its order: the
|
||||
/// frame and payload sizes (protocol violations), a blocked type (silent),
|
||||
/// an unrequired type (filtered), then the prefilter (Transport.py).
|
||||
fn admit_announce_ingress(
|
||||
&mut self,
|
||||
payload: &[u8],
|
||||
wire_hops: u8,
|
||||
raw: &[u8],
|
||||
header: &rns_wire::header::PacketHeader,
|
||||
data_offset: usize,
|
||||
interface_id: InterfaceId,
|
||||
) -> bool {
|
||||
use crate::destination_filter::{AnnounceSource, NAME_HASH_LEN, NameHash};
|
||||
const KEYSIZE: usize = 64;
|
||||
let Some(name_hash) = payload
|
||||
.get(KEYSIZE..KEYSIZE + NAME_HASH_LEN)
|
||||
.and_then(|bytes| NameHash::try_from(bytes).ok())
|
||||
else {
|
||||
use rns_wire::constants::{KEYSIZE, MTU, TRUNCATED_HASHLENGTH};
|
||||
const KEY_LEN: usize = KEYSIZE / 8;
|
||||
const RANDOM_BLOB_LEN: usize = 10;
|
||||
let payload = &raw[data_offset..];
|
||||
// A HEADER_1 announce must leave room for a relay's transport id.
|
||||
let oversize = raw.len() > MTU
|
||||
|| (header.flags.header_type == rns_wire::flags::HeaderType::Header1
|
||||
&& raw.len() > MTU - TRUNCATED_HASHLENGTH / 8);
|
||||
if oversize || payload.len() < KEY_LEN + NAME_HASH_LEN + RANDOM_BLOB_LEN {
|
||||
debug!(
|
||||
interface_id,
|
||||
size = payload.len(),
|
||||
"malformed announce packet"
|
||||
frame = raw.len(),
|
||||
payload = payload.len(),
|
||||
"announce size violation"
|
||||
);
|
||||
self.protocol_violation(interface_id);
|
||||
return false;
|
||||
};
|
||||
}
|
||||
let name_hash: NameHash = payload[KEY_LEN..KEY_LEN + NAME_HASH_LEN]
|
||||
.try_into()
|
||||
.expect("payload length checked");
|
||||
if self.destination_filter.is_blocked(&name_hash) {
|
||||
trace!(
|
||||
interface_id,
|
||||
destination_type = self.destination_filter.type_name(&name_hash),
|
||||
"announce dropped by destination type filter"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
let source = if self.is_local_client_interface(interface_id) {
|
||||
AnnounceSource::LocalClient
|
||||
} else if self.is_shared_instance_peer_interface(interface_id) {
|
||||
@@ -459,17 +532,102 @@ impl TransportActor {
|
||||
} else {
|
||||
AnnounceSource::Other
|
||||
};
|
||||
let admitted = self
|
||||
if !self
|
||||
.destination_filter
|
||||
.admits(&name_hash, source, wire_hops);
|
||||
if !admitted {
|
||||
.admits(&name_hash, source, header.hops)
|
||||
{
|
||||
trace!(
|
||||
interface_id,
|
||||
destination_type = self.destination_filter.type_name(&name_hash),
|
||||
"announce dropped by destination type filter"
|
||||
destination_type = self.destination_filter.pretty_name(&name_hash),
|
||||
"announce filtered as not required"
|
||||
);
|
||||
self.filtered_announce(interface_id);
|
||||
return false;
|
||||
}
|
||||
admitted
|
||||
let blob_at = KEY_LEN + NAME_HASH_LEN;
|
||||
let random_blob: [u8; RANDOM_BLOB_LEN] = payload[blob_at..blob_at + RANDOM_BLOB_LEN]
|
||||
.try_into()
|
||||
.expect("payload length checked");
|
||||
if !self.prefilter_admits(header, &random_blob, interface_id) {
|
||||
trace!(
|
||||
interface_id,
|
||||
dest = hex::encode(header.destination_hash),
|
||||
"announce prefiltered"
|
||||
);
|
||||
self.record_interface_event(interface_id, InterfaceEvent::ReceivedAnnounce, 0);
|
||||
self.filtered_announce(interface_id);
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Python's prefilter conditions: an announce for a known path that is no
|
||||
/// path response, answers no path request and has no queued rebroadcast
|
||||
/// must pass `announce_prefilter` (Transport.py). Reads the raw path table,
|
||||
/// as upstream does, so an expired path not yet culled counts.
|
||||
fn prefilter_admits(
|
||||
&self,
|
||||
header: &rns_wire::header::PacketHeader,
|
||||
random_blob: &[u8; 10],
|
||||
interface_id: InterfaceId,
|
||||
) -> bool {
|
||||
let destination = &header.destination_hash;
|
||||
let Some(path) = self.path_table.get(destination) else {
|
||||
return true;
|
||||
};
|
||||
header.context == rns_wire::context::PacketContext::PathResponse
|
||||
|| self.path_requests.contains_key(destination)
|
||||
|| self.discovery_path_requests.contains_key(destination)
|
||||
|| self.announce_table.get(destination).is_some()
|
||||
|| self.announce_prefilter(destination, path, random_blob, interface_id)
|
||||
}
|
||||
|
||||
/// Python `Transport.announce_prefilter`: whether an announce could still
|
||||
/// update this path (Transport.py). A path whose interface is gone keeps
|
||||
/// it, as upstream's `None` interface does.
|
||||
fn announce_prefilter(
|
||||
&self,
|
||||
destination: &[u8; 16],
|
||||
path: &crate::path_table::PathEntry,
|
||||
random_blob: &[u8; 10],
|
||||
receiving_interface: InterfaceId,
|
||||
) -> bool {
|
||||
let Some(path_interface) = self.interfaces.get(&path.interface_id) else {
|
||||
return true;
|
||||
};
|
||||
let emitted = announce_timebase(random_blob);
|
||||
match emitted.cmp(&path_timebase_from_random_blobs(path.random_blobs.iter())) {
|
||||
std::cmp::Ordering::Greater => true,
|
||||
std::cmp::Ordering::Less => false,
|
||||
std::cmp::Ordering::Equal => {
|
||||
self.interfaces
|
||||
.get(&receiving_interface)
|
||||
.is_some_and(|entry| entry.gravity > path_interface.gravity)
|
||||
|| self.path_table.get_state(destination)
|
||||
== crate::constants::PathState::Unresponsive
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Interface.py culls a held announce for a destination now known when
|
||||
/// `announce_prefilter` rejects it, with none of the ingress exemptions.
|
||||
pub(super) fn held_announce_is_useful(&self, held: &crate::ingress::HeldAnnounce) -> bool {
|
||||
let Some(path) = self.path_table.get(&held.destination_hash) else {
|
||||
return true;
|
||||
};
|
||||
let Some(random_blob) = rns_wire::header::PacketHeader::unpack(&held.raw)
|
||||
.ok()
|
||||
.and_then(|(_, offset)| held.raw.get(offset + 74..offset + 84))
|
||||
.and_then(|blob| <[u8; 10]>::try_from(blob).ok())
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
self.announce_prefilter(
|
||||
&held.destination_hash,
|
||||
path,
|
||||
&random_blob,
|
||||
held.receiving_interface_id,
|
||||
)
|
||||
}
|
||||
|
||||
fn process_announce(
|
||||
@@ -612,27 +770,35 @@ impl TransportActor {
|
||||
.discovery_path_requests
|
||||
.get(&header.destination_hash)
|
||||
.is_some_and(|request| now_f64() < request.timeout);
|
||||
self.record_interface_event(interface_id, InterfaceEvent::ReceivedAnnounce, raw.len());
|
||||
self.count_transport_event(InterfaceEvent::ReceivedAnnounce);
|
||||
// A held announce samples the frequency after the limiter decision,
|
||||
// with no bytes and no transport count (Transport.py).
|
||||
if let Some(entry) = self.interfaces.get_mut(&interface_id)
|
||||
&& !is_from_local_client
|
||||
&& !announced_destination_known
|
||||
&& !answers_path_request
|
||||
&& entry.ingress.should_ingress_limit()
|
||||
{
|
||||
entry.ingress.hold_announce(crate::ingress::HeldAnnounce {
|
||||
let outcome = entry.ingress.hold_announce(crate::ingress::HeldAnnounce {
|
||||
raw: bytes::Bytes::copy_from_slice(raw),
|
||||
destination_hash: header.destination_hash,
|
||||
hops: header.hops,
|
||||
receiving_interface_id: interface_id,
|
||||
});
|
||||
if outcome.is_filtered() {
|
||||
self.filtered_announce(interface_id);
|
||||
}
|
||||
self.record_interface_event(interface_id, InterfaceEvent::ReceivedAnnounce, 0);
|
||||
debug!(
|
||||
dest = hex::encode(header.destination_hash),
|
||||
interface = interface_id,
|
||||
?outcome,
|
||||
"announce held by ingress controller (burst active)"
|
||||
);
|
||||
return;
|
||||
}
|
||||
self.record_interface_event(interface_id, InterfaceEvent::ReceivedAnnounce, raw.len());
|
||||
self.count_transport_event(InterfaceEvent::ReceivedAnnounce);
|
||||
self.set_inbound_verdict(InboundVerdict::Accepted);
|
||||
|
||||
if let Some(validated_identity) = validated_identity.as_ref() {
|
||||
let known_public_key = self
|
||||
@@ -679,6 +845,7 @@ impl TransportActor {
|
||||
let announce_identity_hash = Some(validated.identity_hash);
|
||||
let announce_random_hash = announce_data.random_hash;
|
||||
let announce_stamp_value = validated.stamp_value.unwrap_or(0.0);
|
||||
let announce_emitted = announce_timebase(&announce_random_hash);
|
||||
|
||||
// Python remembers every freshly validated announce, replays included,
|
||||
// before it decides whether the path changes; a validation-cache hit
|
||||
@@ -702,6 +869,7 @@ impl TransportActor {
|
||||
e.is_path_response = is_path_response;
|
||||
e.name_hash = announce_name_hash;
|
||||
e.facts_known = true;
|
||||
e.emitted = Some(announce_emitted);
|
||||
self.kd.pending.mark_dirty(header.destination_hash);
|
||||
self.remember_received_ratchet(header.destination_hash, announce_ratchet);
|
||||
}
|
||||
@@ -725,6 +893,7 @@ impl TransportActor {
|
||||
stamp_value: announce_stamp_value,
|
||||
lr_cost: validated.lr_cost,
|
||||
facts_known: true,
|
||||
emitted: Some(announce_emitted),
|
||||
});
|
||||
self.state_dirty = true;
|
||||
self.kd.pending.mark_dirty(header.destination_hash);
|
||||
@@ -749,8 +918,6 @@ impl TransportActor {
|
||||
.map(|e| e.mode)
|
||||
.unwrap_or(InterfaceMode::Gateway);
|
||||
|
||||
let announce_emitted = announce_timebase(&announce_random_hash);
|
||||
|
||||
// Cancel our queued rebroadcast when a neighbor already carried it.
|
||||
// Same-hop neighbor rebroadcast counts toward the local cap;
|
||||
// strict hops+1 forward drops our queued copy outright.
|
||||
@@ -795,6 +962,9 @@ impl TransportActor {
|
||||
.unwrap_or_default();
|
||||
let suppressed =
|
||||
self.is_path_interface_suppressed(header.destination_hash, interface_id, now_f64());
|
||||
// Transport.py: an unresponsive path takes the same emission with more
|
||||
// hops, but the announce is not rebroadcast.
|
||||
let mut table_insertion_only = false;
|
||||
let should_add = if suppressed {
|
||||
false
|
||||
} else if let Some(existing) = self.path_table.get(&header.destination_hash) {
|
||||
@@ -817,8 +987,9 @@ impl TransportActor {
|
||||
} else if existing.is_expired() || announce_emitted > path_timebase {
|
||||
!random_seen
|
||||
} else if announce_emitted == path_timebase {
|
||||
self.path_table.get_state(&header.destination_hash)
|
||||
== crate::constants::PathState::Unresponsive
|
||||
table_insertion_only = self.path_table.get_state(&header.destination_hash)
|
||||
== crate::constants::PathState::Unresponsive;
|
||||
table_insertion_only
|
||||
} else {
|
||||
false
|
||||
}
|
||||
@@ -861,6 +1032,7 @@ impl TransportActor {
|
||||
// check above compares against our own queued copy. Non-transport
|
||||
// nodes never queue (would amplify the announce per hub).
|
||||
if !rate_blocked
|
||||
&& !table_insertion_only
|
||||
&& (self.is_transport_enabled || is_from_local_client)
|
||||
&& header.context != rns_wire::context::PacketContext::PathResponse
|
||||
&& header.hops < PATHFINDER_M
|
||||
@@ -890,6 +1062,8 @@ impl TransportActor {
|
||||
block_rebroadcast: false,
|
||||
attached_interface: None,
|
||||
source_interface: Some(interface_id),
|
||||
packet_hash: announce_packet_hash,
|
||||
dedup_interfaces: Vec::new(),
|
||||
};
|
||||
self.announce_table
|
||||
.insert(header.destination_hash, announce_entry);
|
||||
@@ -952,6 +1126,10 @@ impl TransportActor {
|
||||
tunnel.expires = now_f64() + TUNNEL_TIMEOUT as f64;
|
||||
}
|
||||
}
|
||||
// Transport.py: a local client's announce or path response proves it live.
|
||||
if is_from_local_client {
|
||||
self.mark_path_responsive(&header.destination_hash);
|
||||
}
|
||||
self.state_dirty = true;
|
||||
if self.path_requests.contains_key(&header.destination_hash) {
|
||||
self.use_destination(&header.destination_hash);
|
||||
@@ -985,6 +1163,18 @@ impl TransportActor {
|
||||
"path learned from announce"
|
||||
);
|
||||
} else {
|
||||
// Transport.py: a copy of the queued announce from an interface
|
||||
// off a shared medium needs no rebroadcast back onto it.
|
||||
if self
|
||||
.interfaces
|
||||
.get(&interface_id)
|
||||
.is_some_and(|entry| !entry.shared_medium)
|
||||
&& let Some(queued) = self.announce_table.get_mut(&header.destination_hash)
|
||||
&& queued.packet_hash == announce_packet_hash
|
||||
&& !queued.dedup_interfaces.contains(&interface_id)
|
||||
{
|
||||
queued.dedup_interfaces.push(interface_id);
|
||||
}
|
||||
debug!(
|
||||
dest = hex::encode(header.destination_hash),
|
||||
hops = header.hops,
|
||||
@@ -1012,21 +1202,20 @@ impl TransportActor {
|
||||
}
|
||||
let app_data_for_handlers = announce_app_data;
|
||||
|
||||
// The desiring interface is unused: the response rebroadcasts once
|
||||
// everywhere through the announce table (Transport.py).
|
||||
// Transport.py: a local client's answer to an external request goes
|
||||
// once, as a path response, to the interface that asked.
|
||||
if is_from_local_client
|
||||
&& header.context == rns_wire::context::PacketContext::PathResponse
|
||||
&& self
|
||||
&& let Some(desiring) = self
|
||||
.pending_local_path_requests
|
||||
.remove(&header.destination_hash)
|
||||
.is_some()
|
||||
{
|
||||
let now = now_f64();
|
||||
let rebroadcast_raw = self.transport_announce_from_raw(
|
||||
let response_raw = self.transport_announce_from_raw(
|
||||
raw,
|
||||
header.destination_hash,
|
||||
header.hops,
|
||||
rns_wire::context::PacketContext::None,
|
||||
rns_wire::context::PacketContext::PathResponse,
|
||||
);
|
||||
self.announce_table.insert(
|
||||
header.destination_hash,
|
||||
@@ -1035,11 +1224,13 @@ impl TransportActor {
|
||||
retransmit_timeout: now,
|
||||
retries: PATHFINDER_R,
|
||||
hops: header.hops,
|
||||
packet_raw: rebroadcast_raw,
|
||||
packet_raw: response_raw,
|
||||
local_rebroadcasts: 0,
|
||||
block_rebroadcast: false,
|
||||
attached_interface: None,
|
||||
block_rebroadcast: true,
|
||||
attached_interface: Some(desiring),
|
||||
source_interface: Some(interface_id),
|
||||
packet_hash: announce_packet_hash,
|
||||
dedup_interfaces: Vec::new(),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1090,6 +1281,7 @@ impl TransportActor {
|
||||
announce_packet_hash,
|
||||
is_path_response,
|
||||
hops: header.hops,
|
||||
emitted: announce_emitted,
|
||||
app_data: handler_app_data.clone(),
|
||||
public_key: announce_public_key,
|
||||
ratchet: announce_ratchet,
|
||||
@@ -1175,31 +1367,9 @@ impl TransportActor {
|
||||
return;
|
||||
}
|
||||
|
||||
// Tunnel synthesis: install the tunnel, and replay its cached paths,
|
||||
// once the signature verifies (Transport.py).
|
||||
if header.destination_hash == tunnel_synth_dest {
|
||||
if let Some(payload_start) = self.data_payload_offset(raw, header) {
|
||||
match crate::tunnel::TunnelSynthesisData::unpack(&raw[payload_start..])
|
||||
.filter(crate::tunnel::TunnelSynthesisData::is_signed)
|
||||
{
|
||||
Some(synthesis) => {
|
||||
let tunnel_id = synthesis.tunnel_id();
|
||||
debug!(
|
||||
tunnel_id = hex::encode(&tunnel_id[..16]),
|
||||
interface_id, "tunnel synthesis request validated"
|
||||
);
|
||||
crate::tunnel::handle_tunnel(
|
||||
&mut self.tunnel_table,
|
||||
tunnel_id,
|
||||
interface_id,
|
||||
);
|
||||
self.state_dirty = true;
|
||||
self.restore_tunnel_paths(&tunnel_id, interface_id);
|
||||
}
|
||||
// Wrong length or a bad signature is a silent drop
|
||||
// (Transport.py).
|
||||
None => debug!(interface_id, "invalid tunnel synthesis"),
|
||||
}
|
||||
self.tunnel_synthesize_handler(&raw[payload_start..], interface_id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1230,8 +1400,8 @@ impl TransportActor {
|
||||
.remove(&rns_wire::hash::packet_hash(raw, header.flags.header_type));
|
||||
return;
|
||||
}
|
||||
if let Some(tx) = self.destination_channels.get(&header.destination_hash)
|
||||
&& let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::InboundPacket {
|
||||
if let Some(tx) = self.destination_channels.get(&header.destination_hash) {
|
||||
match tx.try_send(crate::link_messages::DestinationEvent::InboundPacket {
|
||||
interface_owner: self
|
||||
.interfaces
|
||||
.get(&interface_id)
|
||||
@@ -1239,11 +1409,21 @@ impl TransportActor {
|
||||
raw: raw.clone(),
|
||||
interface_id,
|
||||
metrics,
|
||||
})
|
||||
{
|
||||
self.channel_drops += 1;
|
||||
warn!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e,
|
||||
"failed to deliver InboundPacket to local destination (channel full)");
|
||||
}) {
|
||||
// Python's `Link.receive` (Link.py:1034).
|
||||
Ok(())
|
||||
if header.flags.destination_type
|
||||
== rns_wire::flags::DestinationType::Link =>
|
||||
{
|
||||
self.count_link_bytes(raw.len(), 0);
|
||||
}
|
||||
Ok(()) => {}
|
||||
Err(e) => {
|
||||
self.channel_drops += 1;
|
||||
warn!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e,
|
||||
"failed to deliver InboundPacket to local destination (channel full)");
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1260,6 +1440,8 @@ impl TransportActor {
|
||||
.insert(pkt_hash, interface_id, Some(target_interface));
|
||||
self.send_to_interface(target_interface, &forwarded);
|
||||
if let Some(path) = self.path_table.get_live_mut(&header.destination_hash) {
|
||||
// A first use is persisted: the path cull keeps used paths.
|
||||
self.state_dirty |= path.used == 0.0;
|
||||
path.mark_used();
|
||||
}
|
||||
trace!(
|
||||
@@ -1389,6 +1571,8 @@ impl TransportActor {
|
||||
return;
|
||||
}
|
||||
if let Some(path) = self.path_table.get_live_mut(&header.destination_hash) {
|
||||
// A first use is persisted: the path cull keeps used paths.
|
||||
self.state_dirty |= path.used == 0.0;
|
||||
path.mark_used();
|
||||
}
|
||||
|
||||
@@ -1413,6 +1597,7 @@ impl TransportActor {
|
||||
receiving_owner,
|
||||
requested_mode,
|
||||
accepted_mtu_ceiling,
|
||||
traffic: 0,
|
||||
};
|
||||
self.link_table.insert(link_id, link_entry);
|
||||
|
||||
@@ -1894,8 +2079,8 @@ impl TransportActor {
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(tx) = self.destination_channels.get(&header.destination_hash)
|
||||
&& let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::InboundPacket {
|
||||
if let Some(tx) = self.destination_channels.get(&header.destination_hash) {
|
||||
match tx.try_send(crate::link_messages::DestinationEvent::InboundPacket {
|
||||
interface_owner: self
|
||||
.interfaces
|
||||
.get(&_interface_id)
|
||||
@@ -1903,11 +2088,18 @@ impl TransportActor {
|
||||
raw: raw.clone(),
|
||||
interface_id: _interface_id,
|
||||
metrics,
|
||||
})
|
||||
{
|
||||
self.channel_drops += 1;
|
||||
error!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e,
|
||||
"failed to deliver link proof to local link");
|
||||
}) {
|
||||
// Python hands only resource proofs to `Link.receive`.
|
||||
Ok(()) if header.context == rns_wire::context::PacketContext::ResourcePrf => {
|
||||
self.count_link_bytes(raw.len(), 0);
|
||||
}
|
||||
Ok(()) => {}
|
||||
Err(e) => {
|
||||
self.channel_drops += 1;
|
||||
error!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e,
|
||||
"failed to deliver link proof to local link");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1949,6 +2141,29 @@ impl TransportActor {
|
||||
self.protocol_violation(interface_id);
|
||||
return true;
|
||||
}
|
||||
let skip_hashlist = matches!(
|
||||
header.context,
|
||||
rns_wire::context::PacketContext::Keepalive
|
||||
| rns_wire::context::PacketContext::Resource
|
||||
| rns_wire::context::PacketContext::ResourceReq
|
||||
| rns_wire::context::PacketContext::ResourcePrf
|
||||
| rns_wire::context::PacketContext::CacheRequest
|
||||
| rns_wire::context::PacketContext::Channel
|
||||
);
|
||||
let pkt_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
|
||||
// The hashlist check deferred from ingress: Python's packet filter.
|
||||
if !skip_hashlist && self.packet_hashlist.contains(&pkt_hash) {
|
||||
trace!(
|
||||
link_id = hex::encode(header.destination_hash),
|
||||
packet_kind, "duplicate link-table packet dropped"
|
||||
);
|
||||
self.packet_filter_hit(interface_id);
|
||||
self.set_inbound_verdict(InboundVerdict::Filtered);
|
||||
return true;
|
||||
}
|
||||
if !from_local_client {
|
||||
self.count_link_bytes(raw.len(), 0);
|
||||
}
|
||||
if !self.link_registration_is_current(&entry)
|
||||
|| raw.len() > entry.accepted_mtu_ceiling as usize
|
||||
{
|
||||
@@ -2014,31 +2229,20 @@ impl TransportActor {
|
||||
self.local_hops_delta
|
||||
};
|
||||
}
|
||||
let skip_hashlist = matches!(
|
||||
header.context,
|
||||
rns_wire::context::PacketContext::Keepalive
|
||||
| rns_wire::context::PacketContext::Resource
|
||||
| rns_wire::context::PacketContext::ResourceReq
|
||||
| rns_wire::context::PacketContext::ResourcePrf
|
||||
| rns_wire::context::PacketContext::CacheRequest
|
||||
| rns_wire::context::PacketContext::Channel
|
||||
);
|
||||
if !skip_hashlist {
|
||||
let pkt_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
|
||||
if !self.packet_hashlist.insert(pkt_hash) {
|
||||
trace!(
|
||||
link_id = hex::encode(header.destination_hash),
|
||||
packet_kind, "duplicate link-table packet dropped after claim"
|
||||
);
|
||||
return true;
|
||||
}
|
||||
self.packet_hashlist.insert(pkt_hash);
|
||||
}
|
||||
if let Some(entry) = self.link_table.get_mut(&header.destination_hash) {
|
||||
entry.timestamp = now_f64();
|
||||
entry.traffic = entry.traffic.saturating_add(forwarded.len() as u64);
|
||||
}
|
||||
self.send_to_interface(target_interface, &forwarded);
|
||||
if !self.is_local_client_interface(target_interface) {
|
||||
self.count_link_bytes(0, forwarded.len());
|
||||
}
|
||||
// Transport.py
|
||||
if let Some(path) = self.path_table.get_mut(&entry.destination_hash) {
|
||||
self.state_dirty |= path.used == 0.0;
|
||||
path.mark_used();
|
||||
}
|
||||
trace!(
|
||||
|
||||
@@ -455,12 +455,27 @@ impl TransportActor {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Python counts every packet an own Link sends in `link_txb` (Packet.py:312).
|
||||
fn try_send_link_endpoint_raw(
|
||||
&mut self,
|
||||
interface_id: InterfaceId,
|
||||
link_id: [u8; 16],
|
||||
role: crate::messages::LinkEndpointRole,
|
||||
raw: &[u8],
|
||||
) -> InterfaceSendOutcome {
|
||||
let outcome = self.try_send_link_endpoint_raw_uncounted(interface_id, link_id, role, raw);
|
||||
if outcome == InterfaceSendOutcome::Sent {
|
||||
self.count_link_bytes(0, raw.len());
|
||||
}
|
||||
outcome
|
||||
}
|
||||
|
||||
fn try_send_link_endpoint_raw_uncounted(
|
||||
&mut self,
|
||||
interface_id: InterfaceId,
|
||||
link_id: [u8; 16],
|
||||
role: crate::messages::LinkEndpointRole,
|
||||
raw: &[u8],
|
||||
) -> InterfaceSendOutcome {
|
||||
use crate::messages::LinkEndpointRole;
|
||||
|
||||
|
||||
@@ -45,7 +45,9 @@ impl TransportActor {
|
||||
if now - self.last_tables_cull >= TABLES_CULL_INTERVAL {
|
||||
self.cull_path_table(now);
|
||||
self.reverse_table.cull_expired();
|
||||
self.tunnel_table.cull_expired();
|
||||
if self.tunnel_table.cull_expired() > 0 {
|
||||
self.state_dirty = true;
|
||||
}
|
||||
self.cull_stale_tunnel_paths(now);
|
||||
self.cull_path_interface_suppressions(now);
|
||||
self.cull_local_link_route_attempts(now);
|
||||
@@ -75,12 +77,6 @@ impl TransportActor {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Cull may have removed path/tunnel entries — flag for save so
|
||||
// the on-disk file reflects the current routing state. False
|
||||
// positives (cull found nothing) cost one no-op file rewrite at
|
||||
// the next periodic flush.
|
||||
self.state_dirty = true;
|
||||
self.last_tables_cull = now;
|
||||
}
|
||||
|
||||
@@ -93,9 +89,10 @@ impl TransportActor {
|
||||
e.source_interface,
|
||||
e.attached_interface,
|
||||
e.block_rebroadcast,
|
||||
e.dedup_interfaces.clone(),
|
||||
)
|
||||
});
|
||||
if let Some((raw, _source_iface, Some(attached_interface), true)) = send_info {
|
||||
if let Some((raw, _source_iface, Some(attached_interface), true, _)) = send_info {
|
||||
let timestamp = self.announce_table.get(&hash).unwrap().timestamp;
|
||||
self.admit_cached_response(
|
||||
*hash.as_bytes(),
|
||||
@@ -112,8 +109,8 @@ impl TransportActor {
|
||||
// The helper excludes an exact shared IPC peer and applies
|
||||
// mode policy. A broadcast radio may need same-interface
|
||||
// retransmission to reach a different physical neighbor.
|
||||
if let Some((raw, source_iface, _, _)) = send_info {
|
||||
self.broadcast_announce_on_interfaces(&raw, source_iface);
|
||||
if let Some((raw, source_iface, _, _, skip)) = send_info {
|
||||
self.broadcast_announce_skipping(&raw, source_iface, &skip);
|
||||
}
|
||||
}
|
||||
self.announce_table.cull_exhausted(PATHFINDER_R);
|
||||
@@ -130,8 +127,8 @@ impl TransportActor {
|
||||
if now - self.last_blackhole_check >= BLACKHOLE_CHECK_INTERVAL {
|
||||
if self.blackhole_table.cull_expired() > 0 {
|
||||
self.publish_blackhole_snapshot();
|
||||
self.state_dirty = true;
|
||||
}
|
||||
self.state_dirty = true;
|
||||
self.last_blackhole_check = now;
|
||||
}
|
||||
|
||||
@@ -250,19 +247,22 @@ impl TransportActor {
|
||||
};
|
||||
let check_unused = now > self.path_pool_last_checked + PATH_POOL_CHECK_INTERVAL;
|
||||
let interfaces = &self.interfaces;
|
||||
let (removed, unused) = self.path_table.cull(now, linger, check_unused, |id| {
|
||||
interfaces.get(&id).map(|entry| entry.bitrate)
|
||||
});
|
||||
if let Some(unused) = unused {
|
||||
let (removed, unused) =
|
||||
self.path_table
|
||||
.cull(now, linger, check_unused, self.hop_limiter, |id| {
|
||||
interfaces.get(&id).map(|entry| entry.bitrate)
|
||||
});
|
||||
if let Some((unused, target)) = unused {
|
||||
self.path_pool_last_checked = now;
|
||||
if unused > PATH_POOL_UNUSED_TARGET {
|
||||
if unused > target {
|
||||
debug!(
|
||||
culled = unused - PATH_POOL_UNUSED_TARGET,
|
||||
"culled never-used paths to reach the pool size target"
|
||||
culled = unused - target,
|
||||
target, "culled never-used paths to reach the pool size target"
|
||||
);
|
||||
}
|
||||
}
|
||||
if removed > 0 {
|
||||
self.state_dirty = true;
|
||||
pathing!(removed, "removed stale paths");
|
||||
}
|
||||
}
|
||||
@@ -360,7 +360,8 @@ impl TransportActor {
|
||||
should_request = true;
|
||||
} else if !path_request_throttle {
|
||||
if expired_link.taken_hops == 0 {
|
||||
should_request = true;
|
||||
// Transport.py: a local client's Link to a 0-hop destination asks nothing.
|
||||
should_request = self.path_table.hops_to(&destination_hash) != Some(0);
|
||||
} else if self.path_table.hops_to(&destination_hash) == Some(1)
|
||||
|| expired_link.taken_hops == 1
|
||||
{
|
||||
@@ -557,15 +558,29 @@ impl TransportActor {
|
||||
}
|
||||
|
||||
/// Python's interface job (Transport.py): re-evaluate both burst
|
||||
/// limiters, then release at most one held announce per interface.
|
||||
/// limiters, then, when a release is due, cull the held announces that
|
||||
/// can no longer update a path and release at most one per interface.
|
||||
fn process_held_announces(&mut self, _now: f64) {
|
||||
let iface_ids: Vec<InterfaceId> = self.interfaces.keys().copied().collect();
|
||||
for iface_id in iface_ids {
|
||||
let released = self.interfaces.get_mut(&iface_id).and_then(|iface| {
|
||||
let due = self.interfaces.get_mut(&iface_id).is_some_and(|iface| {
|
||||
iface.ingress.should_ingress_limit();
|
||||
iface.ingress.should_ingress_limit_pr();
|
||||
iface.ingress.try_release_held()
|
||||
iface.ingress.release_due()
|
||||
});
|
||||
if !due {
|
||||
continue;
|
||||
}
|
||||
let culled: Vec<[u8; 16]> = self.interfaces[&iface_id]
|
||||
.ingress
|
||||
.held_announces()
|
||||
.filter(|held| !self.held_announce_is_useful(held))
|
||||
.map(|held| held.destination_hash)
|
||||
.collect();
|
||||
let released = self
|
||||
.interfaces
|
||||
.get_mut(&iface_id)
|
||||
.and_then(|iface| iface.ingress.cull_and_release(&culled));
|
||||
|
||||
if let Some(announce) = released {
|
||||
pathing!(
|
||||
@@ -747,6 +762,7 @@ mod cleanup_tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
};
|
||||
actor.recent_announces.insert(entry.dest_hash, entry);
|
||||
}
|
||||
@@ -846,6 +862,34 @@ mod cleanup_tests {
|
||||
assert_eq!(actor.pending_discovery_prs.len(), 2);
|
||||
}
|
||||
|
||||
/// Transport.py 1.6.1 (5bd93ad9): a local client's unproven Link to a
|
||||
/// 0-hop destination neither asks for a path nor expires it.
|
||||
#[test]
|
||||
fn local_client_link_to_a_local_destination_asks_nothing() {
|
||||
let now = now_f64();
|
||||
for (hops, asks) in [(0, false), (2, true)] {
|
||||
let (mut actor, _tx) = TransportActor::new();
|
||||
let dest = [0x33; 16];
|
||||
actor
|
||||
.path_table
|
||||
.insert(dest, PathEntry::new(None, hops, 1, InterfaceMode::Full));
|
||||
actor.handle_expired_unvalidated_link(
|
||||
crate::link_table::ExpiredLink {
|
||||
next_hop: None,
|
||||
interface_id: 1,
|
||||
remaining_hops: hops,
|
||||
destination_hash: dest,
|
||||
receiving_interface: 2,
|
||||
taken_hops: 0,
|
||||
},
|
||||
now,
|
||||
);
|
||||
assert_eq!(!actor.pending_discovery_prs.is_empty(), asks, "hops {hops}");
|
||||
// A leaf drops the path it asks for.
|
||||
assert_eq!(actor.path_table.has_path(&dest), !asks, "hops {hops}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Transport.py: one cull pass removes every
|
||||
/// reverse entry past REVERSE_TIMEOUT, with no batch cap.
|
||||
#[test]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -266,6 +266,7 @@ impl TransportActor {
|
||||
|
||||
// Transport.py: traffic marks use, never liveness.
|
||||
if let Some(path) = self.path_table.get_live_mut(&request.destination_hash) {
|
||||
self.state_dirty |= path.used == 0.0;
|
||||
path.mark_used();
|
||||
}
|
||||
sent
|
||||
@@ -674,7 +675,6 @@ impl TransportActor {
|
||||
data.get(PR_LENGTH..).and_then(|ext| ext.try_into().ok());
|
||||
(Some(id), &data[32..48], ext)
|
||||
};
|
||||
let tag_bytes = Some(tag);
|
||||
|
||||
let now = now_f64();
|
||||
let mut unique_tag = [0u8; 32];
|
||||
@@ -714,19 +714,25 @@ impl TransportActor {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Python counts a path request once its tag and stamp pass these gates
|
||||
// (Transport.py).
|
||||
// Python counts a path request once its tag and stamp pass these gates,
|
||||
// then classifies it against the updated burst state (Transport.py).
|
||||
self.set_inbound_verdict(super::inbound::InboundVerdict::Batched);
|
||||
self.record_interface_event(interface_id, InterfaceEvent::ReceivedPathRequest, raw_len);
|
||||
self.count_transport_event(InterfaceEvent::ReceivedPathRequest);
|
||||
let ingress_limited = self
|
||||
.interfaces
|
||||
.get_mut(&interface_id)
|
||||
.is_some_and(|iface| iface.ingress.should_ingress_limit_pr());
|
||||
|
||||
// Transport.py: a request for a destination already
|
||||
// in flight joins the waiting requesters instead of being processed.
|
||||
if self.inflight_path_requests.contains_key(&requested_dest) {
|
||||
// A local client's request for a live path is answered from the table.
|
||||
let answer_from_table =
|
||||
is_from_local_client && self.path_table.get_live(&requested_dest).is_some();
|
||||
if !answer_from_table && self.inflight_path_requests.contains_key(&requested_dest) {
|
||||
// A leaf answers batched requesters only for its local clients;
|
||||
// upstream would also emit PATH_RESPONSEs naming the leaf as relay.
|
||||
if (self.is_transport_enabled || is_from_local_client)
|
||||
&& !self.processing_ingress_limited
|
||||
{
|
||||
if (self.is_transport_enabled || is_from_local_client) && !ingress_limited {
|
||||
pathing!(
|
||||
dest = %hex::encode(requested_dest),
|
||||
interface_id,
|
||||
@@ -736,8 +742,55 @@ impl TransportActor {
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.set_inbound_verdict(super::inbound::InboundVerdict::Accepted);
|
||||
self.inflight_path_requests.insert(requested_dest, now);
|
||||
|
||||
let mut tag_bytes = [0u8; 16];
|
||||
tag_bytes.copy_from_slice(tag);
|
||||
let request = crate::inbound_queues::PendingPathRequest {
|
||||
interface_id,
|
||||
destination: requested_dest,
|
||||
requestor: requestor_transport_id,
|
||||
tag: tag_bytes,
|
||||
ext,
|
||||
};
|
||||
if ingress_limited {
|
||||
// Transport.py: answered after every other class, still in flight.
|
||||
if !self.inbound_rx.push_ingress_limited(
|
||||
&self.inbound_queues,
|
||||
crate::inbound_queues::Queued::PathRequest(Box::new(request)),
|
||||
) {
|
||||
self.release_path_request_gate(&requested_dest);
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.path_request(request, false);
|
||||
}
|
||||
|
||||
/// Python `Transport.path_request` for a request past the inbound gates.
|
||||
pub(super) fn path_request(
|
||||
&mut self,
|
||||
request: crate::inbound_queues::PendingPathRequest,
|
||||
ingress_limited: bool,
|
||||
) {
|
||||
let crate::inbound_queues::PendingPathRequest {
|
||||
interface_id,
|
||||
destination: requested_dest,
|
||||
requestor: requestor_transport_id,
|
||||
tag,
|
||||
ext,
|
||||
} = request;
|
||||
let tag = &tag[..];
|
||||
let tag_bytes = Some(tag);
|
||||
let now = now_f64();
|
||||
let is_from_local_client = self.is_local_client_interface(interface_id);
|
||||
// Transport.py consults the limiter for every request it processes.
|
||||
let should_ingress_limit = ingress_limited
|
||||
|| self
|
||||
.interfaces
|
||||
.get_mut(&interface_id)
|
||||
.is_some_and(|iface| iface.ingress.should_ingress_limit_pr());
|
||||
|
||||
if self.local_destinations.contains(&requested_dest) {
|
||||
pathing!(
|
||||
dest = %hex::encode(requested_dest),
|
||||
@@ -787,81 +840,103 @@ impl TransportActor {
|
||||
.is_some_and(|iface| iface.mode == InterfaceMode::Roaming)
|
||||
&& path.interface_id == interface_id;
|
||||
|
||||
if requestor_is_next_hop || same_roaming_interface {
|
||||
// Transport.py: answered, even when declined.
|
||||
self.inflight_path_requests.remove(&requested_dest);
|
||||
}
|
||||
if requestor_is_next_hop {
|
||||
// Transport.py: a known path answers the request even when the
|
||||
// reply is declined or its announce cannot be read.
|
||||
let Some(raw) = path
|
||||
.packet_hash
|
||||
.and_then(|hash| self.cached_announce_raw(&hash))
|
||||
else {
|
||||
pathing!(
|
||||
dest = %hex::encode(requested_dest),
|
||||
"not answering path request — requester is our next hop"
|
||||
"ignoring path request — cached announce for the known path is unavailable"
|
||||
);
|
||||
self.inflight_path_requests.remove(&requested_dest);
|
||||
return;
|
||||
}
|
||||
};
|
||||
if same_roaming_interface {
|
||||
pathing!(
|
||||
dest = %hex::encode(requested_dest),
|
||||
"not answering path request on roaming interface learned from same interface"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let cached_raw: Option<(u8, Vec<u8>)> = path
|
||||
.packet_hash
|
||||
.and_then(|hash| self.cached_announce_raw(&hash))
|
||||
.map(|raw| (path.hops, raw));
|
||||
if let Some((hops, raw)) = cached_raw {
|
||||
// Python 1.3.8 Transport.py: unparseable cached announce
|
||||
// aborts the answer entirely (no fall-through to discovery).
|
||||
let Some(response) =
|
||||
self.path_response_from_cached_announce(&raw, requested_dest, hops)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
pathing!(
|
||||
dest = %hex::encode(requested_dest),
|
||||
hops,
|
||||
"answering path request — path is known, queueing path response"
|
||||
);
|
||||
let now = now_f64();
|
||||
let path_on_local_client = self.is_local_client_interface(path.interface_id);
|
||||
let response_delay = if is_from_local_client || path_on_local_client {
|
||||
0.0
|
||||
} else {
|
||||
let roaming_extra = if self
|
||||
.interfaces
|
||||
.get(&interface_id)
|
||||
.is_some_and(|iface| iface.mode == InterfaceMode::Roaming)
|
||||
{
|
||||
PATH_REQUEST_RG
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
PATH_REQUEST_GRACE + roaming_extra
|
||||
};
|
||||
if let Some(held_entry) = self.announce_table.remove(&requested_dest) {
|
||||
self.held_announces.insert(requested_dest, held_entry);
|
||||
}
|
||||
self.announce_table.insert(
|
||||
requested_dest,
|
||||
crate::announce::AnnounceEntry {
|
||||
timestamp: now,
|
||||
retransmit_timeout: now + response_delay,
|
||||
retries: 0,
|
||||
hops,
|
||||
packet_raw: response,
|
||||
local_rebroadcasts: 0,
|
||||
block_rebroadcast: true,
|
||||
attached_interface: Some(interface_id),
|
||||
source_interface: None,
|
||||
},
|
||||
);
|
||||
if !self.shared_instance_client_mode {
|
||||
self.use_destination(&requested_dest);
|
||||
}
|
||||
self.inflight_path_requests.remove(&requested_dest);
|
||||
return;
|
||||
}
|
||||
// Transport.py returns here before the pop; this is a miss like any other.
|
||||
let Some(response) =
|
||||
self.path_response_from_cached_announce(&raw, requested_dest, path.hops)
|
||||
else {
|
||||
self.inflight_path_requests.remove(&requested_dest);
|
||||
return;
|
||||
};
|
||||
if requestor_is_next_hop {
|
||||
pathing!(
|
||||
dest = %hex::encode(requested_dest),
|
||||
"not answering path request — requester is our next hop"
|
||||
);
|
||||
self.inflight_path_requests.remove(&requested_dest);
|
||||
return;
|
||||
}
|
||||
let hops = path.hops;
|
||||
pathing!(
|
||||
dest = %hex::encode(requested_dest),
|
||||
hops,
|
||||
"answering path request — path is known, queueing path response"
|
||||
);
|
||||
let path_on_local_client = self.is_local_client_interface(path.interface_id);
|
||||
let response_delay = if is_from_local_client || path_on_local_client {
|
||||
0.0
|
||||
} else {
|
||||
let roaming_extra = if self
|
||||
.interfaces
|
||||
.get(&interface_id)
|
||||
.is_some_and(|iface| iface.mode == InterfaceMode::Roaming)
|
||||
{
|
||||
PATH_REQUEST_RG
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
PATH_REQUEST_GRACE + roaming_extra
|
||||
};
|
||||
// A repeat request keeps the time of an answer already queued to the
|
||||
// same interface; Transport.py restarts the grace, so a requester
|
||||
// repeating faster than grace plus the announce check is never answered.
|
||||
let queued = self.announce_table.get(&requested_dest).filter(|entry| {
|
||||
entry.block_rebroadcast && entry.attached_interface == Some(interface_id)
|
||||
});
|
||||
let (timestamp, retransmit_timeout) = match queued {
|
||||
Some(entry) => (
|
||||
entry.timestamp,
|
||||
entry.retransmit_timeout.min(now + response_delay),
|
||||
),
|
||||
None => {
|
||||
if let Some(held_entry) = self.announce_table.remove(&requested_dest) {
|
||||
self.held_announces.insert(requested_dest, held_entry);
|
||||
}
|
||||
(now, now + response_delay)
|
||||
}
|
||||
};
|
||||
self.announce_table.insert(
|
||||
requested_dest,
|
||||
crate::announce::AnnounceEntry {
|
||||
timestamp,
|
||||
retransmit_timeout,
|
||||
// Transport.py: lets an overheard answer cancel this one.
|
||||
retries: PATHFINDER_R,
|
||||
hops,
|
||||
packet_raw: response,
|
||||
local_rebroadcasts: 0,
|
||||
block_rebroadcast: true,
|
||||
attached_interface: Some(interface_id),
|
||||
source_interface: None,
|
||||
packet_hash: path.packet_hash.unwrap_or_default(),
|
||||
dedup_interfaces: Vec::new(),
|
||||
},
|
||||
);
|
||||
if !self.shared_instance_client_mode {
|
||||
self.use_destination(&requested_dest);
|
||||
}
|
||||
self.inflight_path_requests.remove(&requested_dest);
|
||||
return;
|
||||
}
|
||||
|
||||
// Python 1.3.8 Transport.py: recursive_prs forces discovery
|
||||
@@ -886,17 +961,13 @@ impl TransportActor {
|
||||
None,
|
||||
);
|
||||
} else if self.is_transport_enabled && should_search_unknown {
|
||||
let ingress_limited = self.processing_ingress_limited
|
||||
|| self
|
||||
.interfaces
|
||||
.get_mut(&interface_id)
|
||||
.is_some_and(|iface| iface.ingress.should_ingress_limit_pr());
|
||||
if ingress_limited {
|
||||
if should_ingress_limit {
|
||||
pathing!(
|
||||
dest = %hex::encode(requested_dest),
|
||||
interface_id,
|
||||
"not forwarding recursive path request — ingress PR burst active"
|
||||
);
|
||||
self.release_path_request_gate(&requested_dest);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -907,6 +978,7 @@ impl TransportActor {
|
||||
dest = %hex::encode(requested_dest),
|
||||
"reached rebroadcast decision for unstamped path request under stamp enforcement"
|
||||
);
|
||||
self.release_path_request_gate(&requested_dest);
|
||||
return;
|
||||
}
|
||||
if self.begin_or_join_recursive_discovery(requested_dest, interface_id, now) {
|
||||
@@ -919,6 +991,8 @@ impl TransportActor {
|
||||
true,
|
||||
search.flatten(),
|
||||
);
|
||||
} else {
|
||||
self.release_path_request_gate(&requested_dest);
|
||||
}
|
||||
} else if self.has_local_client_interfaces() {
|
||||
pathing!(
|
||||
@@ -941,6 +1015,7 @@ impl TransportActor {
|
||||
interface_id,
|
||||
"ignoring unknown path request on non-discovery interface"
|
||||
);
|
||||
self.release_path_request_gate(&requested_dest);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1336,14 +1411,14 @@ mod cache_miss_tests {
|
||||
use crate::messages::InterfaceEntry;
|
||||
use crate::path_table::PathEntry;
|
||||
|
||||
/// Transport.py answers a known path whose announce cannot be read by
|
||||
/// ignoring the request: no discovery, and nothing left in flight.
|
||||
#[test]
|
||||
fn live_path_without_cached_announce_uses_normal_discovery_gates() {
|
||||
// A Boundary requester searches only Boundary and Gateway interfaces
|
||||
// (Transport.py), so the Full route gets no request.
|
||||
for (mode, discovers, sent) in [
|
||||
(InterfaceMode::Gateway, true, true),
|
||||
(InterfaceMode::Boundary, true, false),
|
||||
(InterfaceMode::Full, false, false),
|
||||
fn live_path_without_cached_announce_is_ignored() {
|
||||
for mode in [
|
||||
InterfaceMode::Gateway,
|
||||
InterfaceMode::Boundary,
|
||||
InterfaceMode::Full,
|
||||
] {
|
||||
let (mut actor, _actor_tx) = TransportActor::new();
|
||||
actor.is_transport_enabled = true;
|
||||
@@ -1383,11 +1458,9 @@ mod cache_miss_tests {
|
||||
let mut request = requested.to_vec();
|
||||
request.extend_from_slice(&[0x55; 16]);
|
||||
actor.handle_inbound_path_request(&request, 1);
|
||||
assert_eq!(egress_rx.try_recv().is_ok(), sent);
|
||||
assert_eq!(
|
||||
actor.discovery_path_requests.contains_key(&requested),
|
||||
discovers
|
||||
);
|
||||
assert!(egress_rx.try_recv().is_err(), "{mode:?}");
|
||||
assert!(!actor.discovery_path_requests.contains_key(&requested));
|
||||
assert!(!actor.inflight_path_requests.contains_key(&requested));
|
||||
assert!(actor.announce_table.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1505,6 +1578,7 @@ mod path_request_stamp_tests {
|
||||
#[test]
|
||||
fn without_enforcement_unstamped_requests_are_counted_and_relayed_as_received() {
|
||||
let (mut actor, _a, mut b) = actor_with_two_interfaces(true);
|
||||
actor.stamp_policy.stamp_prs = false;
|
||||
let data = hex::decode(STAMPED_TAG_1).unwrap()[..PR_LENGTH].to_vec();
|
||||
actor.handle_inbound_path_request(&data, 1);
|
||||
assert_eq!(received(&actor, 1), 1);
|
||||
@@ -1512,9 +1586,8 @@ mod path_request_stamp_tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stamping_transport_relays_unstamped_requests_with_the_lenient_marker() {
|
||||
fn a_default_transport_relays_unstamped_requests_with_the_lenient_marker() {
|
||||
let (mut actor, _a, mut b) = actor_with_two_interfaces(true);
|
||||
actor.stamp_policy.stamp_prs = true;
|
||||
let data = hex::decode(STAMPED_TAG_1).unwrap()[..PR_LENGTH].to_vec();
|
||||
actor.handle_inbound_path_request(&data, 1);
|
||||
let relayed = payload(&b.try_recv().expect("relayed without waiting for a stamp"));
|
||||
@@ -1527,6 +1600,7 @@ mod path_request_stamp_tests {
|
||||
#[test]
|
||||
fn unstamped_emission_carries_the_transport_id_on_a_leaf() {
|
||||
let (mut actor, mut a, _b) = actor_with_two_interfaces(false);
|
||||
actor.stamp_policy.stamp_prs = false;
|
||||
actor.on_path_request([0x77; 16]);
|
||||
let sent = payload(&a.try_recv().expect("sent"));
|
||||
assert_eq!(sent.len(), PR_LENGTH);
|
||||
@@ -1534,9 +1608,8 @@ mod path_request_stamp_tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stamped_emission_waits_for_the_stamper_then_uses_the_cached_stamp() {
|
||||
fn default_emission_waits_for_the_stamper_then_uses_the_cached_stamp() {
|
||||
let (mut actor, mut a, _b) = actor_with_two_interfaces(false);
|
||||
actor.stamp_policy.stamp_prs = true;
|
||||
actor.stamp_policy.pr_value = 4.0;
|
||||
let dest = [0x77; 16];
|
||||
let tag = [0x55; 16];
|
||||
|
||||
@@ -124,6 +124,11 @@ impl TransportActor {
|
||||
return;
|
||||
}
|
||||
let now = now_f64();
|
||||
// Transport.py: a failed Link never drops or rediscovers a 0-hop path.
|
||||
let local = self
|
||||
.path_table
|
||||
.get_live(&request.destination_hash)
|
||||
.is_some_and(|path| path.hops == 0);
|
||||
let mut path_dropped = false;
|
||||
let mut observed = false;
|
||||
if let Some(attempt) = request.failed_attempt.and_then(|link_id| {
|
||||
@@ -140,6 +145,7 @@ impl TransportActor {
|
||||
}) {
|
||||
observed = now - attempt.observed_at < LOCAL_LINK_ROUTE_LIFETIME;
|
||||
if observed
|
||||
&& !local
|
||||
&& self
|
||||
.path_table
|
||||
.get_live(&request.destination_hash)
|
||||
@@ -155,7 +161,7 @@ impl TransportActor {
|
||||
// A failed attempt's fresh replacement needs no new discovery flood.
|
||||
// Unknown attempts and explicit discovery can ask even if a cached
|
||||
// route exists, but all callers share the destination throttle/FIFO.
|
||||
let should_request = path_dropped || !has_path || !observed;
|
||||
let should_request = !local && (path_dropped || !has_path || !observed);
|
||||
let recent = self
|
||||
.path_requests
|
||||
.get(&request.destination_hash)
|
||||
@@ -280,6 +286,20 @@ mod tests {
|
||||
assert!(!again.path_dropped && again.has_path);
|
||||
}
|
||||
|
||||
/// Transport.py 1.6.1 (5bd93ad9): a failed Link to a 0-hop destination
|
||||
/// neither expires its path nor asks for one.
|
||||
#[test]
|
||||
fn failed_link_to_a_local_destination_keeps_its_path() {
|
||||
let (mut actor, handle, _radio) = fixture();
|
||||
actor.path_table.get_mut(&[0xDD; 16]).unwrap().hops = 0;
|
||||
let link = dispatch(&mut actor);
|
||||
let result = recover(&mut actor, &handle, [0xDD; 16], Some(link));
|
||||
assert!(!result.path_dropped && result.has_path && !result.request_scheduled);
|
||||
assert!(actor.pending_discovery_prs.is_empty());
|
||||
let explicit = recover(&mut actor, &handle, [0xDD; 16], None);
|
||||
assert!(!explicit.request_scheduled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_link_failure_preserves_fresh_same_radio_and_alternate_routes() {
|
||||
for interface in [1, 2] {
|
||||
|
||||
@@ -24,6 +24,13 @@ pub(super) struct PendingAdmission {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Admission is independent of path-request stamping.
|
||||
fn unstamped_actor() -> TransportActor {
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
actor.stamp_policy.stamp_prs = false;
|
||||
actor
|
||||
}
|
||||
|
||||
fn interface(
|
||||
actor: &mut TransportActor,
|
||||
id: InterfaceId,
|
||||
@@ -53,7 +60,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn full_driver_preserves_tag_without_spending_path_or_airtime_budget() {
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
let mut actor = unstamped_actor();
|
||||
let mut radio = interface(&mut actor, 1, 1);
|
||||
fill(&actor, 1);
|
||||
let dest = [0xD1; 16];
|
||||
@@ -81,7 +88,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn partial_admission_retries_only_failed_interface() {
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
let mut actor = unstamped_actor();
|
||||
let mut blocked = interface(&mut actor, 1, 1);
|
||||
let mut ready = interface(&mut actor, 2, 8);
|
||||
fill(&actor, 1);
|
||||
@@ -99,7 +106,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn refused_target_does_not_extend_healthy_recovery_discovery_cooldown() {
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
let mut actor = unstamped_actor();
|
||||
let handle = actor.path_recovery_handle();
|
||||
let mut blocked = interface(&mut actor, 1, 1);
|
||||
let mut ready = interface(&mut actor, 2, 8);
|
||||
@@ -150,7 +157,7 @@ mod tests {
|
||||
#[test]
|
||||
fn deadline_and_new_signed_route_retire_unadmitted_bytes() {
|
||||
for new_route in [false, true] {
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
let mut actor = unstamped_actor();
|
||||
let mut radio = interface(&mut actor, 1, 1);
|
||||
fill(&actor, 1);
|
||||
let dest = [0xD3; 16];
|
||||
@@ -174,7 +181,7 @@ mod tests {
|
||||
#[test]
|
||||
fn replacement_or_closed_interface_cannot_inherit_old_queued_request() {
|
||||
for replace in [false, true] {
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
let mut actor = unstamped_actor();
|
||||
let radio = interface(&mut actor, 1, 1);
|
||||
fill(&actor, 1);
|
||||
actor.on_path_request([0xD4; 16]);
|
||||
@@ -194,7 +201,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn recursive_operation_retirement_cancels_pending_egress() {
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
let mut actor = unstamped_actor();
|
||||
let mut radio = interface(&mut actor, 1, 1);
|
||||
fill(&actor, 1);
|
||||
let dest = [0xD5; 16];
|
||||
@@ -212,7 +219,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn admission_inventory_is_bounded_and_clear_shared_retires_it() {
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
let mut actor = unstamped_actor();
|
||||
let _radio = interface(&mut actor, 1, 1);
|
||||
fill(&actor, 1);
|
||||
for i in 0..MAX_PENDING_ADMISSIONS + 32 {
|
||||
@@ -231,7 +238,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn initial_policy_veto_and_missing_target_do_not_create_retry_or_sent_state() {
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
let mut actor = unstamped_actor();
|
||||
let mut radio = interface(&mut actor, 1, 1);
|
||||
actor.interfaces.get_mut(&1).unwrap().announce_allowed_at = now_f64() + 120.0;
|
||||
actor.send_path_request([0xD7; 16], 1, None, true);
|
||||
@@ -247,7 +254,7 @@ mod tests {
|
||||
fn admission_review_round_robin_reaches_recovered_interface_behind_full_slice() {
|
||||
let start = now_f64();
|
||||
let _clock = crate::test_clock::Clock::at(start);
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
let mut actor = unstamped_actor();
|
||||
let _blocked = interface(&mut actor, 1, 1);
|
||||
let mut recovering = interface(&mut actor, 2, 1);
|
||||
fill(&actor, 1);
|
||||
@@ -326,7 +333,7 @@ mod tests {
|
||||
for release_at_deadline in [false, true] {
|
||||
let start = now_f64();
|
||||
let clock = crate::test_clock::Clock::at(start);
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
let mut actor = unstamped_actor();
|
||||
let mut radio = interface(&mut actor, 1, 1);
|
||||
fill(&actor, 1);
|
||||
let dest = [0xE3; 16];
|
||||
@@ -395,7 +402,7 @@ mod tests {
|
||||
for change in 0..=5 {
|
||||
let start = now_f64();
|
||||
let clock = crate::test_clock::Clock::at(start);
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
let mut actor = unstamped_actor();
|
||||
let mut radio = interface(&mut actor, 1, 1);
|
||||
fill(&actor, 1);
|
||||
let dest = [0xE4; 16];
|
||||
|
||||
@@ -1,6 +1,18 @@
|
||||
use super::*;
|
||||
use tracing::info;
|
||||
|
||||
/// Python's `storagepath/announce_rate_table` (Transport.py).
|
||||
const ANNOUNCE_RATE_TABLE_FILE: &str = "announce_rate_table";
|
||||
|
||||
/// Python `save_announce_rate_table`: write through a temporary file and a
|
||||
/// rename, logging a failure (Transport.py, Storage.py).
|
||||
fn save_announce_rate_table(dir: &std::path::Path, blob: &[u8]) {
|
||||
let path = dir.join(ANNOUNCE_RATE_TABLE_FILE);
|
||||
if let Err(e) = rns_identity::persistence::atomic_write(&path, blob) {
|
||||
tracing::warn!(path = %path.display(), error = %e, "could not persist announce rate table");
|
||||
}
|
||||
}
|
||||
|
||||
/// Wall-clock helper kept here so tests can inject a fake clock without
|
||||
/// dragging it through the actor.
|
||||
fn now() -> f64 {
|
||||
@@ -31,6 +43,7 @@ fn recent_announce_from_cached_packet(
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: false,
|
||||
emitted: None,
|
||||
};
|
||||
|
||||
if let Ok((header, offset)) = rns_wire::header::PacketHeader::unpack(&raw_packet)
|
||||
@@ -74,35 +87,42 @@ pub(super) struct RoutingSnapshot {
|
||||
pub transport_identity_hash: Option<[u8; 16]>,
|
||||
}
|
||||
|
||||
fn write_encoded(
|
||||
dir: &std::path::Path,
|
||||
name: &str,
|
||||
encoded: Result<Vec<u8>, crate::persistence::PersistenceError>,
|
||||
) -> bool {
|
||||
let written =
|
||||
encoded.and_then(|bytes| crate::persistence::atomic_write_bytes(&dir.join(name), &bytes));
|
||||
if let Err(e) = &written {
|
||||
trace!("failed to save {name}: {e}");
|
||||
}
|
||||
written.is_ok()
|
||||
}
|
||||
|
||||
/// Persist a routing snapshot. Runs on the blocking pool for periodic saves
|
||||
/// and inline for shutdown; must not touch the actor.
|
||||
pub(super) fn write_routing_snapshot(dir: &std::path::Path, snapshot: &RoutingSnapshot) {
|
||||
let interface_names = &snapshot.interface_names;
|
||||
use crate::persistence as p;
|
||||
let keys = p::interface_keys(&snapshot.interface_names);
|
||||
|
||||
let path_table_path = dir.join("path_table.msgpack");
|
||||
if let Err(e) =
|
||||
crate::persistence::save_path_table(&snapshot.path_table, interface_names, &path_table_path)
|
||||
{
|
||||
trace!("failed to save path table: {}", e);
|
||||
} else {
|
||||
if write_encoded(
|
||||
dir,
|
||||
"path_table.msgpack",
|
||||
p::encode_path_table(&snapshot.path_table, &keys),
|
||||
) {
|
||||
debug!("saved path table ({} entries)", snapshot.path_table.len());
|
||||
}
|
||||
|
||||
let destination_table_path = dir.join("destination_table");
|
||||
if let Err(e) = crate::persistence::save_python_destination_table(
|
||||
&snapshot.path_table,
|
||||
interface_names,
|
||||
&destination_table_path,
|
||||
write_encoded(
|
||||
dir,
|
||||
"destination_table",
|
||||
p::encode_python_destination_table(&snapshot.path_table, &keys),
|
||||
);
|
||||
if write_encoded(
|
||||
dir,
|
||||
"blackhole_table.msgpack",
|
||||
p::encode_blackhole_table(&snapshot.blackhole_table),
|
||||
) {
|
||||
trace!("failed to save Python destination_table: {}", e);
|
||||
}
|
||||
|
||||
let blackhole_path = dir.join("blackhole_table.msgpack");
|
||||
if let Err(e) =
|
||||
crate::persistence::save_blackhole_table(&snapshot.blackhole_table, &blackhole_path)
|
||||
{
|
||||
trace!("failed to save blackhole table: {}", e);
|
||||
} else {
|
||||
debug!(
|
||||
"saved blackhole table ({} entries)",
|
||||
snapshot.blackhole_table.len()
|
||||
@@ -111,39 +131,32 @@ pub(super) fn write_routing_snapshot(dir: &std::path::Path, snapshot: &RoutingSn
|
||||
|
||||
// Publisher files are written only when fetched (Discovery.py).
|
||||
if let Some(local_identity_hash) = snapshot.transport_identity_hash {
|
||||
let blackhole_dir = dir.join("blackhole");
|
||||
if let Err(e) = crate::persistence::save_local_blackhole_file(
|
||||
&snapshot.blackhole_table,
|
||||
local_identity_hash,
|
||||
&blackhole_dir,
|
||||
) {
|
||||
trace!("failed to save Python blackhole files: {}", e);
|
||||
let written =
|
||||
p::encode_local_blackhole_file(&snapshot.blackhole_table, local_identity_hash)
|
||||
.and_then(|bytes| p::write_local_blackhole_file(&bytes, &dir.join("blackhole")));
|
||||
if let Err(e) = written {
|
||||
trace!("failed to save Python blackhole files: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
// Per-announce Python cache files are written event-driven at receive
|
||||
// (`cache_announce_to_disk`), not re-serialized here every cycle.
|
||||
|
||||
let tunnel_path = dir.join("tunnel_table.msgpack");
|
||||
if let Err(e) =
|
||||
crate::persistence::save_tunnel_table(&snapshot.tunnel_table, interface_names, &tunnel_path)
|
||||
{
|
||||
trace!("failed to save tunnel table: {}", e);
|
||||
} else {
|
||||
if write_encoded(
|
||||
dir,
|
||||
"tunnel_table.msgpack",
|
||||
p::encode_tunnel_table(&snapshot.tunnel_table, &keys),
|
||||
) {
|
||||
debug!(
|
||||
"saved tunnel table ({} entries)",
|
||||
snapshot.tunnel_table.len()
|
||||
);
|
||||
}
|
||||
|
||||
let python_tunnels_path = dir.join("tunnels");
|
||||
if let Err(e) = crate::persistence::save_python_tunnel_table(
|
||||
&snapshot.tunnel_table,
|
||||
interface_names,
|
||||
&python_tunnels_path,
|
||||
) {
|
||||
trace!("failed to save Python tunnels table: {}", e);
|
||||
}
|
||||
write_encoded(
|
||||
dir,
|
||||
"tunnels",
|
||||
p::encode_python_tunnel_table(&snapshot.tunnel_table, &keys),
|
||||
);
|
||||
|
||||
debug!(
|
||||
paths = snapshot.path_table.len(),
|
||||
@@ -418,22 +431,31 @@ impl TransportActor {
|
||||
trace!("failed to save hashlist: {}", e);
|
||||
} else {
|
||||
info!(entries = hashes.len(), "flushed hashlist");
|
||||
self.hashlist_saved_revision = self.packet_hashlist.revision();
|
||||
}
|
||||
save_announce_rate_table(dir, &self.rate_table.to_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
/// Falling-edge (foreground→background) flush. Same coverage as
|
||||
/// `save_state` but entirely off-actor: on desktop the edge fires on
|
||||
/// every window focus loss, and the inline fsync chain (F_FULLFSYNC per
|
||||
/// file on macOS) stalls routing + control queries for seconds.
|
||||
/// file on macOS) stalls routing + control queries for seconds. What
|
||||
/// is already on disk is not written again.
|
||||
pub(super) fn save_state_async(&mut self) {
|
||||
self.save_routing_state_async();
|
||||
if self.state_dirty {
|
||||
self.save_routing_state_async();
|
||||
}
|
||||
if !self.owns_persistent_hashlist() {
|
||||
return;
|
||||
}
|
||||
let Some(dir) = self.storage_dir.clone() else {
|
||||
return;
|
||||
};
|
||||
let revision = self.packet_hashlist.revision();
|
||||
if revision == self.hashlist_saved_revision {
|
||||
return;
|
||||
}
|
||||
if self
|
||||
.hashlist_save_in_flight
|
||||
.load(std::sync::atomic::Ordering::Acquire)
|
||||
@@ -443,7 +465,9 @@ impl TransportActor {
|
||||
}
|
||||
self.hashlist_save_in_flight
|
||||
.store(true, std::sync::atomic::Ordering::Release);
|
||||
self.hashlist_saved_revision = revision;
|
||||
let hashes = self.packet_hashlist.current_hashes();
|
||||
let rate_table = self.rate_table.to_bytes();
|
||||
let in_flight = self.hashlist_save_in_flight.clone();
|
||||
let entries = hashes.len();
|
||||
let write = move || {
|
||||
@@ -453,6 +477,7 @@ impl TransportActor {
|
||||
} else {
|
||||
info!(entries, "flushed hashlist");
|
||||
}
|
||||
save_announce_rate_table(&dir, &rate_table);
|
||||
in_flight.store(false, std::sync::atomic::Ordering::Release);
|
||||
};
|
||||
match tokio::runtime::Handle::try_current() {
|
||||
@@ -477,6 +502,29 @@ impl TransportActor {
|
||||
self.is_transport_enabled && !self.storage_client()
|
||||
}
|
||||
|
||||
/// Python `Transport.start` loads the table with the hashlist; a file it
|
||||
/// rejects leaves the table empty (Transport.py).
|
||||
fn load_announce_rate_table(&mut self, dir: &std::path::Path) {
|
||||
let path = dir.join(ANNOUNCE_RATE_TABLE_FILE);
|
||||
if !path.is_file() {
|
||||
return;
|
||||
}
|
||||
match std::fs::read(&path)
|
||||
.ok()
|
||||
.and_then(|blob| crate::rate_limit::RateTable::from_bytes(&blob))
|
||||
{
|
||||
Some(loaded) => {
|
||||
let entries = loaded.len();
|
||||
self.rate_table.absorb(loaded);
|
||||
debug!(entries, "loaded announce rate table from storage");
|
||||
}
|
||||
None => tracing::warn!(
|
||||
path = %path.display(),
|
||||
"could not load announce rate table from storage, initialized empty"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Restore the canonical packet hashlist once both storage and the
|
||||
/// actor's transport authority are known. Shared-instance clients and
|
||||
/// non-transport leaves must never load or overwrite the authoritative
|
||||
@@ -489,6 +537,7 @@ impl TransportActor {
|
||||
return;
|
||||
};
|
||||
self.hashlist_load_attempted = true;
|
||||
self.load_announce_rate_table(&dir);
|
||||
|
||||
let raw_path = dir.join("packet_hashlist.raw");
|
||||
if raw_path.exists() {
|
||||
@@ -509,6 +558,7 @@ impl TransportActor {
|
||||
);
|
||||
}
|
||||
self.packet_hashlist.load_from(loaded.hashes);
|
||||
self.hashlist_saved_revision = self.packet_hashlist.revision();
|
||||
debug!(count, "loaded canonical packet hashlist from disk");
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -536,6 +586,7 @@ impl TransportActor {
|
||||
self.packet_hashlist.load_from(hashes.clone());
|
||||
match crate::persistence::save_raw_hashes(&hashes, &raw_path) {
|
||||
Ok(()) => {
|
||||
self.hashlist_saved_revision = self.packet_hashlist.revision();
|
||||
info!(
|
||||
source = %legacy_path.display(),
|
||||
destination = %raw_path.display(),
|
||||
@@ -945,6 +996,7 @@ impl TransportActor {
|
||||
}
|
||||
if count > 0 {
|
||||
self.publish_blackhole_snapshot();
|
||||
self.detach_blackholed_tunnel_peers();
|
||||
debug!(count, "loaded Python blackhole files");
|
||||
}
|
||||
}
|
||||
@@ -954,8 +1006,9 @@ impl TransportActor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Load a persisted tunnel unbound; only a later synthesis binds it.
|
||||
/// Python keeps a tunnel only when one of its paths loads.
|
||||
/// Load a persisted tunnel unbound, within the reconnect window; only a
|
||||
/// later synthesis binds it. Python keeps a tunnel only when one of its
|
||||
/// paths loads.
|
||||
fn load_unbound_tunnel(
|
||||
&mut self,
|
||||
tunnel_id: &[u8],
|
||||
@@ -994,11 +1047,12 @@ impl TransportActor {
|
||||
if tunnel_paths.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let window = now_f64() + crate::constants::TUNNEL_RECONNECT_WINDOW as f64;
|
||||
self.tunnel_table.insert(crate::tunnel::TunnelEntry {
|
||||
tunnel_id,
|
||||
interface_id: None,
|
||||
tunnel_paths,
|
||||
expires,
|
||||
expires: expires.min(window),
|
||||
});
|
||||
true
|
||||
}
|
||||
@@ -1018,6 +1072,8 @@ impl TransportActor {
|
||||
) {
|
||||
if !self.pending_path_entries.is_empty() {
|
||||
let mut promoted = 0usize;
|
||||
let mut filtered = 0usize;
|
||||
let mut blackholed = 0usize;
|
||||
let hashes = [
|
||||
crate::persistence::interface_hash_from_name(upstream_name),
|
||||
crate::persistence::interface_hash_from_name(name),
|
||||
@@ -1039,6 +1095,21 @@ impl TransportActor {
|
||||
}
|
||||
let mut hash = [0u8; 16];
|
||||
hash.copy_from_slice(&pe.destination_hash);
|
||||
// Transport.py: a restored path skips blackholed identities
|
||||
// and filtered destination types.
|
||||
let known = self.recent_announces.get(&hash);
|
||||
if known.and_then(|k| k.public_key).is_some_and(|key| {
|
||||
self.blackhole_table
|
||||
.is_blackholed(&rns_crypto::sha::truncated_hash(&key))
|
||||
}) {
|
||||
blackholed += 1;
|
||||
return false;
|
||||
}
|
||||
let name_hash = known.filter(|k| k.facts_known).map(|k| &k.name_hash);
|
||||
if !self.destination_filter.admits_stored(name_hash) {
|
||||
filtered += 1;
|
||||
return false;
|
||||
}
|
||||
let next_hop = pe.next_hop.as_ref().and_then(|h| {
|
||||
if h.len() == 16 {
|
||||
let mut arr = [0u8; 16];
|
||||
@@ -1084,11 +1155,13 @@ impl TransportActor {
|
||||
}
|
||||
false
|
||||
});
|
||||
if promoted > 0 {
|
||||
if promoted > 0 || filtered > 0 || blackholed > 0 {
|
||||
debug!(
|
||||
interface_id = id,
|
||||
name = %name,
|
||||
promoted,
|
||||
filtered,
|
||||
blackholed,
|
||||
"rebound persisted path entries to live interface"
|
||||
);
|
||||
}
|
||||
@@ -1210,6 +1283,7 @@ mod announce_clean_tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
},
|
||||
);
|
||||
actor
|
||||
@@ -1390,6 +1464,46 @@ mod async_save_tests {
|
||||
actor
|
||||
}
|
||||
|
||||
/// A cull pass that removes nothing leaves the routing state clean, so the
|
||||
/// periodic save has nothing to write.
|
||||
#[test]
|
||||
fn empty_cull_pass_leaves_state_clean() {
|
||||
let dir = temp_storage();
|
||||
let mut actor = dirty_actor(&dir);
|
||||
actor.state_dirty = false;
|
||||
actor.last_tables_cull = 0.0;
|
||||
actor.last_blackhole_check = 0.0;
|
||||
actor.on_tick();
|
||||
assert!(actor.path_table.has_path(&[0x11; 16]));
|
||||
assert!(!actor.state_dirty);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A background edge writes only what changed since the last save.
|
||||
#[test]
|
||||
fn background_save_skips_unchanged_state() {
|
||||
let dir = temp_storage();
|
||||
let mut actor = dirty_actor(&dir);
|
||||
actor.is_transport_enabled = true;
|
||||
actor.state_dirty = false;
|
||||
actor.save_state_async();
|
||||
assert!(!dir.join("path_table.msgpack").exists());
|
||||
assert!(!dir.join("packet_hashlist.raw").exists());
|
||||
|
||||
actor.packet_hashlist.insert([0xAA; 32]);
|
||||
actor.save_state_async();
|
||||
assert!(!dir.join("path_table.msgpack").exists());
|
||||
let saved = crate::persistence::load_hashlist_raw(&dir.join("packet_hashlist.raw"));
|
||||
assert_eq!(saved.unwrap().hashes, vec![[0xAA; 32]]);
|
||||
|
||||
std::fs::remove_file(dir.join("packet_hashlist.raw")).unwrap();
|
||||
actor.state_dirty = true;
|
||||
actor.save_state_async();
|
||||
assert!(dir.join("path_table.msgpack").exists());
|
||||
assert!(!dir.join("packet_hashlist.raw").exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Pending known-destination marks are handed to the store on the 10 s cadence,
|
||||
/// without waiting for the routing tables' periodic save.
|
||||
#[test]
|
||||
@@ -1415,6 +1529,7 @@ mod async_save_tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
},
|
||||
);
|
||||
let now = crate::now_f64();
|
||||
@@ -1652,4 +1767,46 @@ mod async_save_tests {
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Python 1.6.1 saves and loads `announce_rate_table` only on a transport
|
||||
/// instance that owns its storage (Transport.py).
|
||||
#[test]
|
||||
fn a_transport_instance_keeps_its_announce_rate_table_across_restarts() {
|
||||
let dir = temp_storage();
|
||||
let file = dir.join(ANNOUNCE_RATE_TABLE_FILE);
|
||||
let (mut leaf, _) = TransportActor::new();
|
||||
leaf.storage_dir = Some(dir.clone());
|
||||
leaf.rate_table
|
||||
.check_interface_rate([0x31; 16], 60.0, 0, 0.0);
|
||||
leaf.save_state();
|
||||
assert!(!file.exists(), "a leaf persists no rate table");
|
||||
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
actor.is_transport_enabled = true;
|
||||
actor.storage_dir = Some(dir.clone());
|
||||
for _ in 0..2 {
|
||||
actor
|
||||
.rate_table
|
||||
.check_interface_rate([0x31; 16], 60.0, 0, 0.0);
|
||||
}
|
||||
actor.save_state();
|
||||
assert!(file.exists());
|
||||
|
||||
let (mut restarted, _) = TransportActor::new();
|
||||
restarted.is_transport_enabled = true;
|
||||
restarted.initialize_storage(dir.clone());
|
||||
let (_, entry) = restarted.rate_table.iter().next().expect("loaded");
|
||||
let (_, saved) = actor.rate_table.iter().next().unwrap();
|
||||
assert_eq!(
|
||||
(&entry.timestamps, entry.violations, entry.blocked_until),
|
||||
(&saved.timestamps, 1, saved.blocked_until)
|
||||
);
|
||||
|
||||
std::fs::write(&file, b"RNSART").unwrap();
|
||||
let (mut damaged, _) = TransportActor::new();
|
||||
damaged.is_transport_enabled = true;
|
||||
damaged.initialize_storage(dir.clone());
|
||||
assert_eq!(damaged.rate_table.len(), 0);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -191,6 +191,20 @@ impl TransportActor {
|
||||
let _ = self.admit_discovery_requester(destination, requester, now, false);
|
||||
}
|
||||
|
||||
/// Release the in-flight gate after a request that left nothing pending,
|
||||
/// unless a search for the destination still is. Transport.py keeps it
|
||||
/// for 45 s, batching every later request.
|
||||
pub(super) fn release_path_request_gate(&mut self, destination: &[u8; 16]) {
|
||||
let now = now_f64();
|
||||
let searching = self
|
||||
.discovery_path_requests
|
||||
.get(destination)
|
||||
.is_some_and(|operation| operation.engaged && now < operation.timeout);
|
||||
if !searching {
|
||||
self.inflight_path_requests.remove(destination);
|
||||
}
|
||||
}
|
||||
|
||||
/// `engage` starts a fan-out unless one is already engaged; an entry that
|
||||
/// only batched requesters is engaged with a fresh deadline
|
||||
/// (Transport.py).
|
||||
@@ -314,8 +328,7 @@ impl TransportActor {
|
||||
&& self.interfaces.get(&id).is_some_and(|entry| {
|
||||
!interface_marked_offline(entry)
|
||||
// A radio can serve hidden peers; an IPC edge is one peer.
|
||||
&& (id != incoming || (entry.role == InterfaceRole::Normal
|
||||
&& entry.mode != InterfaceMode::Roaming))
|
||||
&& (id != incoming || entry.role == InterfaceRole::Normal)
|
||||
});
|
||||
if eligible {
|
||||
self.send_or_retain_announce(id, response, true);
|
||||
|
||||
@@ -13,11 +13,13 @@ impl TransportActor {
|
||||
.path_table
|
||||
.iter_live()
|
||||
.map(|(hash, entry)| {
|
||||
let iface_name = self
|
||||
.interfaces
|
||||
.get(&entry.interface_id)
|
||||
let iface = self.interfaces.get(&entry.interface_id);
|
||||
let iface_name = iface
|
||||
.map(|e| e.name.clone())
|
||||
.unwrap_or_else(|| format!("interface_{}", entry.interface_id));
|
||||
let interface_hash = crate::persistence::interface_hash_from_name(
|
||||
iface.map_or(iface_name.as_str(), |e| e.upstream_name()),
|
||||
);
|
||||
let hash = hash.into_bytes();
|
||||
let known = self.recent_announces.get(&hash);
|
||||
PathTableRpcEntry {
|
||||
@@ -30,6 +32,8 @@ impl TransportActor {
|
||||
used: entry.used,
|
||||
lr_cost: known.and_then(|k| k.lr_cost),
|
||||
interface: iface_name,
|
||||
interface_hash,
|
||||
state: self.path_table.get_state(&hash),
|
||||
interface_id: entry.interface_id,
|
||||
interface_mode: self
|
||||
.interfaces
|
||||
@@ -59,11 +63,7 @@ impl TransportActor {
|
||||
.as_ref()
|
||||
.map(|o| o.load(std::sync::atomic::Ordering::Relaxed))
|
||||
.unwrap_or(true);
|
||||
let rx_bytes = entry
|
||||
.rxb
|
||||
.as_ref()
|
||||
.map(|c| c.load(std::sync::atomic::Ordering::Relaxed))
|
||||
.unwrap_or(0);
|
||||
let rx_bytes = entry.received.accepted;
|
||||
let tx_bytes = entry
|
||||
.txb
|
||||
.as_ref()
|
||||
@@ -93,6 +93,7 @@ impl TransportActor {
|
||||
.get(&iface_id)
|
||||
.copied()
|
||||
.unwrap_or_default();
|
||||
let speeds = self.traffic_count.speeds.get(&iface_id).copied();
|
||||
// Python publishes IFAC only for an interface that has it.
|
||||
let ifac_signature = entry.ifac_signature();
|
||||
let has_ifac = entry.ifac_key.is_some();
|
||||
@@ -101,6 +102,8 @@ impl TransportActor {
|
||||
name: entry.name.clone(),
|
||||
rx_bytes,
|
||||
tx_bytes,
|
||||
filtered_rx_bytes: entry.received.filtered,
|
||||
filtered_tx_bytes: 0,
|
||||
rx_rate: 0,
|
||||
tx_rate: 0,
|
||||
online,
|
||||
@@ -145,6 +148,7 @@ impl TransportActor {
|
||||
announces_sent: entry.ingress.announces_sent(),
|
||||
path_requests_received: entry.ingress.path_requests_received(),
|
||||
path_requests_sent: entry.ingress.path_requests_sent(),
|
||||
announces_filtered: entry.ingress.announces_filtered(),
|
||||
protocol_violations: entry.protocol_violations,
|
||||
ifac_violations: entry.ifac_violations,
|
||||
packet_filter_hits: entry.packet_filter_hits,
|
||||
@@ -157,7 +161,8 @@ impl TransportActor {
|
||||
.inspection
|
||||
.as_ref()
|
||||
.and_then(|source| source.identity().cloned()),
|
||||
speeds: self.traffic_count.speeds.get(&iface_id).copied(),
|
||||
speeds: speeds.map(|s| [s[0], s[1], s[2], s[3], s[4], s[5]]),
|
||||
filtered_speeds: speeds.map(|s| [s[6], s[7]]),
|
||||
announce_rx_bytes: arxb,
|
||||
announce_tx_bytes: atxb,
|
||||
path_request_rx_bytes: prxb,
|
||||
@@ -174,6 +179,14 @@ impl TransportActor {
|
||||
tx_stalled: inspection.tx_stalled,
|
||||
tx_buffered: inspection.tx_buffered,
|
||||
radio: inspection.radio,
|
||||
last_connect_error: inspection.last_connect_error.map(str::to_string),
|
||||
connect_failures: inspection.connect_failures,
|
||||
tunnel_id: self
|
||||
.tunnel_table
|
||||
.interface_tunnel(iface_id)
|
||||
.or(entry.tunnel.local_tunnel_id),
|
||||
remote_transport_id: entry.tunnel.remote_transport,
|
||||
remote_transport: entry.tunnel.remote_info.clone(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -184,6 +197,9 @@ impl TransportActor {
|
||||
TransportQuery::GetTrafficTotals => {
|
||||
TransportQueryResponse::TrafficTotals(self.traffic_totals())
|
||||
}
|
||||
TransportQuery::GetLinkDistribution => {
|
||||
TransportQueryResponse::LinkDistribution(self.link_distribution())
|
||||
}
|
||||
TransportQuery::GetRateTable => {
|
||||
let entries: Vec<RateTableRpcEntry> = self
|
||||
.rate_table
|
||||
@@ -227,6 +243,7 @@ impl TransportActor {
|
||||
is_path_response,
|
||||
retained: a.retained,
|
||||
facts_known: a.facts_known,
|
||||
emitted: a.emitted,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -450,6 +467,7 @@ impl TransportActor {
|
||||
for dest in dropped {
|
||||
self.path_table.remove(&dest);
|
||||
}
|
||||
self.detach_blackholed_tunnel_peers();
|
||||
self.state_dirty = true;
|
||||
self.publish_blackhole_snapshot();
|
||||
TransportQueryResponse::OptBoolResult(Some(true))
|
||||
@@ -510,11 +528,7 @@ impl TransportActor {
|
||||
.as_ref()
|
||||
.map(|o| o.load(std::sync::atomic::Ordering::Relaxed))
|
||||
.unwrap_or(true);
|
||||
let rx = entry
|
||||
.rxb
|
||||
.as_ref()
|
||||
.map(|c| c.load(std::sync::atomic::Ordering::Relaxed))
|
||||
.unwrap_or(0);
|
||||
let rx = entry.received.accepted;
|
||||
let tx = entry
|
||||
.txb
|
||||
.as_ref()
|
||||
@@ -681,6 +695,22 @@ impl TransportActor {
|
||||
self.cleanup_known_destinations(crate::actor::now_f64());
|
||||
TransportQueryResponse::IntResult(self.recent_announces.len() as i64)
|
||||
}
|
||||
TransportQuery::GetKnownDestinations => {
|
||||
let mut rows: Vec<_> = self
|
||||
.recent_announces
|
||||
.values()
|
||||
.filter_map(super::store_worker::known_destination_row)
|
||||
.collect();
|
||||
rows.sort_by_key(|row| row.destination_hash);
|
||||
TransportQueryResponse::KnownDestinations(rows)
|
||||
}
|
||||
TransportQuery::KnownDestinationsLoaded => {
|
||||
TransportQueryResponse::BoolResult(self.kd.loaded)
|
||||
}
|
||||
TransportQuery::LoadKnownDestinations { rows } => {
|
||||
self.merge_known_destinations(rows);
|
||||
TransportQueryResponse::Ok
|
||||
}
|
||||
TransportQuery::ResolveIdentityHash { input } => {
|
||||
// First treat input as a destination hash.
|
||||
if let Some(entry) = self.recent_announces.get(&input)
|
||||
@@ -808,10 +838,14 @@ pub(super) enum InterfaceEvent {
|
||||
SentPathRequest,
|
||||
}
|
||||
|
||||
/// Byte counters the traffic count samples: Python's `rxb`, `txb`, `arxb`,
|
||||
/// `atxb`, `prxb`, `ptxb`, `frxb` and `ftxb`.
|
||||
const SAMPLED: usize = 8;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct TrafficSample {
|
||||
at: std::time::Instant,
|
||||
bytes: [u64; 6],
|
||||
bytes: [u64; SAMPLED],
|
||||
}
|
||||
|
||||
/// Python `Transport.count_traffic_loop` state and the packet counters it
|
||||
@@ -821,10 +855,12 @@ pub(super) struct TrafficCount {
|
||||
started: std::time::Instant,
|
||||
totals: TrafficTotalsRpcEntry,
|
||||
samples: HashMap<InterfaceId, TrafficSample>,
|
||||
speeds: HashMap<InterfaceId, [f64; 6]>,
|
||||
speeds: HashMap<InterfaceId, [f64; SAMPLED]>,
|
||||
/// Python `r_stat_rssi`, `r_stat_snr` and `r_stat_q` per interface.
|
||||
signal: HashMap<InterfaceId, PacketMetrics>,
|
||||
last_pps: Option<(std::time::Instant, u64, u64)>,
|
||||
/// `link_rxb` and `link_txb` at `last_pps`.
|
||||
last_link_bytes: (u64, u64),
|
||||
last_count: f64,
|
||||
}
|
||||
|
||||
@@ -837,6 +873,7 @@ impl Default for TrafficCount {
|
||||
speeds: HashMap::new(),
|
||||
signal: HashMap::new(),
|
||||
last_pps: None,
|
||||
last_link_bytes: (0, 0),
|
||||
last_count: 0.0,
|
||||
}
|
||||
}
|
||||
@@ -869,22 +906,93 @@ impl TransportActor {
|
||||
else {
|
||||
return;
|
||||
};
|
||||
match event {
|
||||
InterfaceEvent::ReceivedAnnounce => parent.ingress.spawned_received_announce(size),
|
||||
InterfaceEvent::SentAnnounce => parent.ingress.spawned_sent_announce(size),
|
||||
InterfaceEvent::ReceivedPathRequest => {
|
||||
// AutoInterface keeps the base Interface counters, so its peers' events
|
||||
// count on it too (AutoInterface.py, Interface.py).
|
||||
let counts_children = parent
|
||||
.upstream_identity()
|
||||
.is_some_and(|identity| identity.class_name == "AutoInterface");
|
||||
match (event, counts_children) {
|
||||
(InterfaceEvent::ReceivedAnnounce, true) => {
|
||||
parent.ingress.received_announce_bytes(size)
|
||||
}
|
||||
(InterfaceEvent::SentAnnounce, true) => parent.ingress.sent_announce_bytes(size),
|
||||
(InterfaceEvent::ReceivedPathRequest, true) => {
|
||||
parent.ingress.received_path_request_bytes(size)
|
||||
}
|
||||
(InterfaceEvent::SentPathRequest, true) => parent.ingress.sent_path_request_bytes(size),
|
||||
(InterfaceEvent::ReceivedAnnounce, false) => {
|
||||
parent.ingress.spawned_received_announce(size)
|
||||
}
|
||||
(InterfaceEvent::SentAnnounce, false) => parent.ingress.spawned_sent_announce(size),
|
||||
(InterfaceEvent::ReceivedPathRequest, false) => {
|
||||
parent.ingress.spawned_received_path_request(size)
|
||||
}
|
||||
InterfaceEvent::SentPathRequest => parent.ingress.spawned_sent_path_request(size),
|
||||
(InterfaceEvent::SentPathRequest, false) => {
|
||||
parent.ingress.spawned_sent_path_request(size)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `Transport.rx_packets += 1` once a packet passes the packet
|
||||
/// filter (Transport.py).
|
||||
/// Python `Interface.filtered_announce`: the interface, its parent and the
|
||||
/// transport total (Interface.py).
|
||||
pub(super) fn filtered_announce(&mut self, id: InterfaceId) {
|
||||
let Some(entry) = self.interfaces.get_mut(&id) else {
|
||||
return;
|
||||
};
|
||||
entry.ingress.filtered_announce();
|
||||
let parent_id = entry.parent_id;
|
||||
self.traffic_count.totals.announce_filtered_packets += 1;
|
||||
if let Some(parent) = parent_id.and_then(|parent| self.interfaces.get_mut(&parent)) {
|
||||
parent.ingress.filtered_announce();
|
||||
}
|
||||
}
|
||||
|
||||
/// Python 1.6.1 `Transport.rx_packets += 1` once a packet passes
|
||||
/// preprocessing (Transport.py:2266).
|
||||
pub(super) fn count_rx_packet(&mut self) {
|
||||
self.traffic_count.totals.rx_packets += 1;
|
||||
}
|
||||
|
||||
/// Python 1.6.1 `link_rxb` and `link_txb` (Transport.py, Link.py, Packet.py).
|
||||
pub(super) fn count_link_bytes(&mut self, rx: usize, tx: usize) {
|
||||
let totals = &mut self.traffic_count.totals;
|
||||
totals.lrxb = totals.lrxb.saturating_add(rx as u64);
|
||||
totals.ltxb = totals.ltxb.saturating_add(tx as u64);
|
||||
}
|
||||
|
||||
/// Python `Transport.link_distribution()`: every link table entry is a
|
||||
/// relayed Link (Transport.py:3786-3814).
|
||||
fn link_distribution(&self) -> Vec<crate::messages::LinkDistributionRpcEntry> {
|
||||
let mut by_destination: HashMap<[u8; 16], crate::messages::LinkDistributionRpcEntry> =
|
||||
HashMap::new();
|
||||
for (_, link) in self.link_table.iter() {
|
||||
let entry = by_destination
|
||||
.entry(link.destination_hash)
|
||||
.or_insert_with(|| crate::messages::LinkDistributionRpcEntry {
|
||||
destination_hash: link.destination_hash,
|
||||
..Default::default()
|
||||
});
|
||||
entry.traffic = entry.traffic.saturating_add(link.traffic);
|
||||
if link.validated {
|
||||
entry.active += 1;
|
||||
} else {
|
||||
entry.pending += 1;
|
||||
}
|
||||
if let Some(interface) = self.interfaces.get(&link.receiving_interface) {
|
||||
let hash = rns_crypto::sha::sha256(interface.upstream_name().as_bytes());
|
||||
if !entry.from_interfaces.contains(&hash) {
|
||||
entry.from_interfaces.push(hash);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut entries: Vec<_> = by_destination.into_values().collect();
|
||||
for entry in &mut entries {
|
||||
entry.from_interfaces.sort_unstable();
|
||||
}
|
||||
entries.sort_unstable_by_key(|entry| entry.destination_hash);
|
||||
entries
|
||||
}
|
||||
|
||||
/// Python `Transport.tx_packets += 1` per `Transport.transmit` (Transport.py).
|
||||
pub(super) fn count_tx_packet(&mut self) {
|
||||
self.traffic_count.totals.tx_packets += 1;
|
||||
@@ -933,8 +1041,8 @@ impl TransportActor {
|
||||
count
|
||||
.signal
|
||||
.retain(|id, _| self.interfaces.contains_key(id));
|
||||
let mut deltas = [0u64; 6];
|
||||
let mut speeds = [0f64; 6];
|
||||
let mut deltas = [0u64; SAMPLED];
|
||||
let mut speeds = [0f64; SAMPLED];
|
||||
let mut freqs = [0f64; 4];
|
||||
let mut measured = false;
|
||||
for (&id, entry) in &mut self.interfaces {
|
||||
@@ -942,7 +1050,16 @@ impl TransportActor {
|
||||
continue;
|
||||
}
|
||||
let (arxb, atxb, prxb, ptxb) = entry.ingress.announce_and_path_request_bytes();
|
||||
let bytes = [load(&entry.rxb), load(&entry.txb), arxb, atxb, prxb, ptxb];
|
||||
let bytes = [
|
||||
entry.received.accepted,
|
||||
load(&entry.txb),
|
||||
arxb,
|
||||
atxb,
|
||||
prxb,
|
||||
ptxb,
|
||||
entry.received.filtered,
|
||||
0,
|
||||
];
|
||||
let Some(previous) = count.samples.insert(id, TrafficSample { at, bytes }) else {
|
||||
continue;
|
||||
};
|
||||
@@ -950,8 +1067,8 @@ impl TransportActor {
|
||||
if elapsed <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let mut interface_speeds = [0f64; 6];
|
||||
for i in 0..6 {
|
||||
let mut interface_speeds = [0f64; SAMPLED];
|
||||
for i in 0..SAMPLED {
|
||||
let delta = bytes[i].saturating_sub(previous.bytes[i]);
|
||||
deltas[i] += delta;
|
||||
interface_speeds[i] = (delta as f64 * 8.0) / elapsed;
|
||||
@@ -972,8 +1089,12 @@ impl TransportActor {
|
||||
((totals.rx_packets.saturating_sub(rxp)) as f64 / elapsed).round() as u64;
|
||||
totals.txpps =
|
||||
((totals.tx_packets.saturating_sub(txp)) as f64 / elapsed).round() as u64;
|
||||
let (lrxb, ltxb) = count.last_link_bytes;
|
||||
totals.lrxs = totals.lrxb.saturating_sub(lrxb) as f64 * 8.0 / elapsed;
|
||||
totals.ltxs = totals.ltxb.saturating_sub(ltxb) as f64 * 8.0 / elapsed;
|
||||
}
|
||||
count.last_pps = Some((at, totals.rx_packets, totals.tx_packets));
|
||||
count.last_link_bytes = (totals.lrxb, totals.ltxb);
|
||||
totals.measured = measured;
|
||||
totals.rxb += deltas[0];
|
||||
totals.txb += deltas[1];
|
||||
@@ -981,6 +1102,8 @@ impl TransportActor {
|
||||
totals.atxb += deltas[3];
|
||||
totals.prxb += deltas[4];
|
||||
totals.ptxb += deltas[5];
|
||||
totals.frxb += deltas[6];
|
||||
totals.ftxb += deltas[7];
|
||||
[
|
||||
totals.rxs,
|
||||
totals.txs,
|
||||
@@ -988,6 +1111,8 @@ impl TransportActor {
|
||||
totals.atxs,
|
||||
totals.prxs,
|
||||
totals.ptxs,
|
||||
totals.frxs,
|
||||
totals.ftxs,
|
||||
] = speeds;
|
||||
[totals.arxf, totals.atxf, totals.prxf, totals.ptxf] = freqs;
|
||||
}
|
||||
@@ -1141,6 +1266,7 @@ mod tests {
|
||||
receiving_owner: None,
|
||||
requested_mode: 1,
|
||||
accepted_mtu_ceiling: 500,
|
||||
traffic: 0,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -68,6 +68,8 @@ struct Started {
|
||||
rows: Vec<KnownDestinationRow>,
|
||||
/// The announce cache is in its database; false keeps it in the actor's memory.
|
||||
announces_stored: bool,
|
||||
/// A client read the owner's known destinations database.
|
||||
loaded: bool,
|
||||
}
|
||||
|
||||
/// Outcome of one job, delivered to the actor.
|
||||
@@ -225,8 +227,10 @@ fn run(
|
||||
let started = if owner {
|
||||
start_owner(&mut slot, &mut announces, &source, now)
|
||||
} else {
|
||||
let rows = load_for_client(&source);
|
||||
Started {
|
||||
rows: load_for_client(&source),
|
||||
loaded: rows.is_some(),
|
||||
rows: rows.unwrap_or_default(),
|
||||
announces_stored: false,
|
||||
}
|
||||
};
|
||||
@@ -261,30 +265,32 @@ fn start_owner(
|
||||
Started {
|
||||
rows,
|
||||
announces_stored,
|
||||
loaded: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// A shared-instance client reads the owner's database once, read-only, and
|
||||
/// nothing else (`Identity.load_known_destinations`, shared-instance branch).
|
||||
fn load_for_client(source: &StoreSource) -> Vec<KnownDestinationRow> {
|
||||
/// nothing else (`Identity.load_known_destinations`, shared-instance branch);
|
||||
/// `None` when there is no database to read.
|
||||
fn load_for_client(source: &StoreSource) -> Option<Vec<KnownDestinationRow>> {
|
||||
match source {
|
||||
StoreSource::Memory => Vec::new(),
|
||||
StoreSource::Memory => None,
|
||||
#[cfg(feature = "sqlite-store")]
|
||||
StoreSource::Sqlite { known, .. } => {
|
||||
// Upstream logs an error for a missing file too; a client whose
|
||||
// directory is not the owner's has none, and that is not a fault.
|
||||
// A client whose directory is not the owner's has none; the
|
||||
// runtime then asks the shared instance (split mode).
|
||||
if !known.is_file() {
|
||||
debug!("no known destinations database to load as a shared-instance client");
|
||||
return Vec::new();
|
||||
return None;
|
||||
}
|
||||
let read = SqliteKnownDestinations::open_ro(known)
|
||||
.and_then(|mut reader| read_rows(&mut reader));
|
||||
read.unwrap_or_else(|e| {
|
||||
error!(
|
||||
"could not load known destinations from the shared instance's database: {e}; continuing with an empty table"
|
||||
);
|
||||
Vec::new()
|
||||
})
|
||||
SqliteKnownDestinations::open_ro(known)
|
||||
.and_then(|mut reader| read_rows(&mut reader))
|
||||
.map_err(|e| {
|
||||
debug!(
|
||||
"could not load known destinations from the shared instance's database: {e}"
|
||||
)
|
||||
})
|
||||
.ok()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -709,6 +715,8 @@ pub(super) struct KdState {
|
||||
pub(super) results: tokio_mpsc::UnboundedReceiver<StoreResult>,
|
||||
/// Cached announces not yet known to be stored.
|
||||
announces: AnnouncePending,
|
||||
/// Start-up read a known destinations database.
|
||||
pub(super) loaded: bool,
|
||||
#[cfg(feature = "sqlite-store")]
|
||||
db_path: Option<PathBuf>,
|
||||
#[cfg(feature = "sqlite-store")]
|
||||
@@ -733,6 +741,7 @@ impl KdState {
|
||||
in_memory: true,
|
||||
..AnnouncePending::default()
|
||||
},
|
||||
loaded: false,
|
||||
#[cfg(feature = "sqlite-store")]
|
||||
db_path: None,
|
||||
#[cfg(feature = "sqlite-store")]
|
||||
@@ -801,11 +810,13 @@ impl KdState {
|
||||
if owner && !started.announces_stored {
|
||||
self.announces.in_memory = true;
|
||||
}
|
||||
self.loaded = started.loaded;
|
||||
started.rows
|
||||
}
|
||||
None => {
|
||||
error!("the store worker is not running; continuing without stored state");
|
||||
self.announces.in_memory = true;
|
||||
self.loaded = false;
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
@@ -1237,7 +1248,7 @@ fn open_announce_store(source: &StoreSource) -> Option<Box<dyn AnnounceCacheStor
|
||||
|
||||
/// The `known_destinations` row for a live entry, or `None` when the entry has no
|
||||
/// identity key (the table requires one).
|
||||
fn known_destination_row(entry: &RecentAnnounce) -> Option<KnownDestinationRow> {
|
||||
pub(super) fn known_destination_row(entry: &RecentAnnounce) -> Option<KnownDestinationRow> {
|
||||
let public_key = entry.public_key?;
|
||||
let mut row = KnownDestinationRow::new(entry.dest_hash, entry.timestamp, public_key);
|
||||
row.packet_hash = entry.packet_hash;
|
||||
@@ -1278,6 +1289,7 @@ pub(super) fn recent_from_row(row: KnownDestinationRow) -> RecentAnnounce {
|
||||
stamp_value: row.stamp_value,
|
||||
lr_cost: row.lr_cost,
|
||||
facts_known: facts.is_some(),
|
||||
emitted: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1361,6 +1373,7 @@ mod tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: Some(3.0),
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -81,6 +81,8 @@ fn cache_entry(raw: &Bytes, timestamp: f64, attached: bool) -> crate::announce::
|
||||
block_rebroadcast: attached,
|
||||
attached_interface: attached.then_some(1),
|
||||
source_interface: Some(2),
|
||||
packet_hash: [0; 32],
|
||||
dedup_interfaces: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -45,6 +45,21 @@ fn subscribe(actor: &mut TransportActor) -> mpsc::Receiver<crate::messages::Anno
|
||||
rx
|
||||
}
|
||||
|
||||
/// An announce emitted after any made this second; Python 1.6.1 prefilters a
|
||||
/// same-emission copy of a known path (Transport.py).
|
||||
fn newer_announce(
|
||||
identity: &rns_identity::identity::Identity,
|
||||
app_name: &str,
|
||||
hops: u8,
|
||||
) -> (Bytes, [u8; 16]) {
|
||||
make_announce_for_with_random_blob(
|
||||
identity,
|
||||
app_name,
|
||||
hops,
|
||||
random_blob(0x5E, now_f64() as u64 + 1),
|
||||
)
|
||||
}
|
||||
|
||||
/// The same announce answered as a path response, as a transport hub replays
|
||||
/// it from its cache.
|
||||
fn as_path_response(announce: &Bytes) -> Bytes {
|
||||
@@ -125,8 +140,7 @@ fn a_fresh_announce_completes_a_restored_entry() {
|
||||
let restored = actor.recent_announces.get_mut(&dest).unwrap();
|
||||
(restored.facts_known, restored.hops, restored.name_hash) = (false, 0, [0; 10]);
|
||||
|
||||
let (fresh, _) =
|
||||
make_announce_for_context(&identity, "identity.restored", 3, PacketContext::None);
|
||||
let (fresh, _) = newer_announce(&identity, "identity.restored", 3);
|
||||
inbound(&mut actor, &fresh);
|
||||
|
||||
let entry = &actor.recent_announces[&dest];
|
||||
@@ -145,8 +159,7 @@ fn a_fresh_announce_after_a_replay_is_not_a_path_response() {
|
||||
inbound(&mut actor, &as_path_response(&first));
|
||||
assert!(actor.recent_announces[&dest].is_path_response);
|
||||
|
||||
let (fresh, _) =
|
||||
make_announce_for_context(&identity, "identity.first-replay", 2, PacketContext::None);
|
||||
let (fresh, _) = newer_announce(&identity, "identity.first-replay", 2);
|
||||
inbound(&mut actor, &fresh);
|
||||
|
||||
let entry = &actor.recent_announces[&dest];
|
||||
|
||||
@@ -0,0 +1,507 @@
|
||||
//! Python 1.6.1 announce ingress (Transport.py `preprocess_inbound`): the size
|
||||
//! gates, the type filters, the prefilter that drops announces which cannot
|
||||
//! update a known path before their signature is checked, the filtered count
|
||||
//! `afrxc`, and the accounting of held announces (Interface.py).
|
||||
//!
|
||||
//! Expected prefilter verdicts were checked against upstream 1.6.1
|
||||
//! `Transport.announce_prefilter`, called directly on stand-in packets and
|
||||
//! path entries (older False, newer True, same emission False, higher
|
||||
//! gravity True, unresponsive True, path interface `None` True).
|
||||
use super::*;
|
||||
use crate::announce_validation::CachedAnnounce;
|
||||
use crate::ingress::{HeldAnnounce, IngressController, IngressOverrides};
|
||||
use rns_wire::context::PacketContext;
|
||||
|
||||
const NOW: f64 = 1_800_000_000.0;
|
||||
const APP: &str = "prefilter.test";
|
||||
|
||||
struct Node {
|
||||
actor: TransportActor,
|
||||
_rx: Vec<mpsc::Receiver<Bytes>>,
|
||||
}
|
||||
|
||||
fn node(transport: bool) -> Node {
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
actor.is_transport_enabled = transport;
|
||||
actor.transport_identity_hash = Some([0x42; 16]);
|
||||
let mut receivers = Vec::new();
|
||||
for id in [1, 2] {
|
||||
let (mut entry, rx) = make_test_interface(&format!("prefilter_{id}"));
|
||||
entry.ingress = IngressController::disabled();
|
||||
actor.interfaces.insert(id, entry);
|
||||
receivers.push(rx);
|
||||
}
|
||||
Node {
|
||||
actor,
|
||||
_rx: receivers,
|
||||
}
|
||||
}
|
||||
|
||||
struct Announce {
|
||||
raw: Bytes,
|
||||
destination: [u8; 16],
|
||||
}
|
||||
|
||||
/// A signed announce emitted at `emitted` (Unix seconds).
|
||||
fn signed(
|
||||
identity: &rns_identity::identity::Identity,
|
||||
emitted: u64,
|
||||
hops: u8,
|
||||
context: PacketContext,
|
||||
app_data: &[u8],
|
||||
transport_id: Option<[u8; 16]>,
|
||||
) -> Announce {
|
||||
let app_data = (!app_data.is_empty()).then_some(app_data);
|
||||
let data =
|
||||
rns_identity::announce::AnnounceData::create_at(identity, APP, app_data, None, emitted)
|
||||
.unwrap();
|
||||
let destination = rns_identity::destination::Destination::hash_from_name_and_identity(
|
||||
APP,
|
||||
Some(&identity.hash),
|
||||
);
|
||||
let header = rns_wire::header::PacketHeader {
|
||||
flags: rns_wire::flags::PacketFlags {
|
||||
header_type: if transport_id.is_some() {
|
||||
rns_wire::flags::HeaderType::Header2
|
||||
} else {
|
||||
rns_wire::flags::HeaderType::Header1
|
||||
},
|
||||
context_flag: false,
|
||||
transport_type: if transport_id.is_some() {
|
||||
rns_wire::flags::TransportType::Transport
|
||||
} else {
|
||||
rns_wire::flags::TransportType::Broadcast
|
||||
},
|
||||
destination_type: rns_wire::flags::DestinationType::Single,
|
||||
packet_type: rns_wire::flags::PacketType::Announce,
|
||||
},
|
||||
hops,
|
||||
transport_id,
|
||||
destination_hash: destination,
|
||||
context,
|
||||
};
|
||||
let mut raw = header.pack();
|
||||
raw.extend_from_slice(&data.pack());
|
||||
Announce {
|
||||
raw: Bytes::from(raw),
|
||||
destination,
|
||||
}
|
||||
}
|
||||
|
||||
fn plain(identity: &rns_identity::identity::Identity, emitted: u64) -> Announce {
|
||||
signed(identity, emitted, 1, PacketContext::None, &[], None)
|
||||
}
|
||||
|
||||
fn inbound(actor: &mut TransportActor, raw: &Bytes, interface_id: InterfaceId) {
|
||||
actor.on_inbound(InboundPacket {
|
||||
raw: raw.clone(),
|
||||
interface_id,
|
||||
rssi: None,
|
||||
snr: None,
|
||||
q: None,
|
||||
});
|
||||
}
|
||||
|
||||
fn stats(actor: &mut TransportActor, id: InterfaceId) -> crate::messages::InterfaceStatRpcEntry {
|
||||
let TransportQueryResponse::InterfaceStats(entries) =
|
||||
actor.handle_query(TransportQuery::GetInterfaceStats)
|
||||
else {
|
||||
panic!("unexpected interface stats response");
|
||||
};
|
||||
entries
|
||||
.into_iter()
|
||||
.find(|entry| entry.id == id)
|
||||
.expect("interface is listed")
|
||||
}
|
||||
|
||||
fn totals(actor: &mut TransportActor) -> crate::messages::TrafficTotalsRpcEntry {
|
||||
let TransportQueryResponse::TrafficTotals(totals) =
|
||||
actor.handle_query(TransportQuery::GetTrafficTotals)
|
||||
else {
|
||||
panic!("unexpected traffic totals response");
|
||||
};
|
||||
totals
|
||||
}
|
||||
|
||||
fn hash(raw: &Bytes) -> [u8; 32] {
|
||||
let (header, _) = rns_wire::header::PacketHeader::unpack(raw).unwrap();
|
||||
rns_wire::hash::packet_hash(raw, header.flags.header_type)
|
||||
}
|
||||
|
||||
/// `(arxc, arxb, afrxc)` on an interface.
|
||||
fn counts(actor: &mut TransportActor, id: InterfaceId) -> (u64, u64, u64) {
|
||||
let entry = stats(actor, id);
|
||||
(
|
||||
entry.announces_received,
|
||||
entry.announce_rx_bytes,
|
||||
entry.announces_filtered,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_copy_of_a_known_path_is_dropped_before_validation() {
|
||||
let clock = crate::test_clock::Clock::at(NOW);
|
||||
let mut node = node(false);
|
||||
let identity = rns_identity::identity::Identity::new();
|
||||
let current = plain(&identity, 200);
|
||||
inbound(&mut node.actor, ¤t.raw, 1);
|
||||
assert!(node.actor.path_table.get(¤t.destination).is_some());
|
||||
let remembered_at = node.actor.recent_announces[¤t.destination].timestamp;
|
||||
let (arxc, arxb, afrxc) = counts(&mut node.actor, 1);
|
||||
let before = totals(&mut node.actor);
|
||||
|
||||
clock.set(NOW + 5.0);
|
||||
let older = plain(&identity, 199);
|
||||
inbound(&mut node.actor, &older.raw, 1);
|
||||
|
||||
assert_eq!(
|
||||
counts(&mut node.actor, 1),
|
||||
(arxc + 1, arxb, afrxc + 1),
|
||||
"received_announce(size=0) and filtered_announce()"
|
||||
);
|
||||
let after = totals(&mut node.actor);
|
||||
assert_eq!(after.announce_rx_packets, before.announce_rx_packets);
|
||||
assert_eq!(
|
||||
after.announce_filtered_packets,
|
||||
before.announce_filtered_packets + 1
|
||||
);
|
||||
assert!(matches!(
|
||||
node.actor
|
||||
.announce_validation
|
||||
.lookup(&hash(&older.raw), 0.0, false),
|
||||
CachedAnnounce::Miss
|
||||
));
|
||||
assert!(!node.actor.packet_hashlist.contains(&hash(&older.raw)));
|
||||
assert_eq!(
|
||||
node.actor.recent_announces[¤t.destination].timestamp, remembered_at,
|
||||
"a prefiltered copy is never remembered"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_same_emission_copy_needs_more_gravity_or_an_unresponsive_path() {
|
||||
let _clock = crate::test_clock::Clock::at(NOW);
|
||||
let mut node = node(false);
|
||||
node.actor.interfaces.get_mut(&2).unwrap().gravity = 1;
|
||||
let identity = rns_identity::identity::Identity::new();
|
||||
let announce = plain(&identity, 300);
|
||||
inbound(&mut node.actor, &announce.raw, 1);
|
||||
|
||||
inbound(&mut node.actor, &announce.raw, 2);
|
||||
assert_eq!(counts(&mut node.actor, 2).2, 0, "higher gravity is kept");
|
||||
assert_eq!(
|
||||
node.actor
|
||||
.path_table
|
||||
.get(&announce.destination)
|
||||
.unwrap()
|
||||
.interface_id,
|
||||
2
|
||||
);
|
||||
|
||||
inbound(&mut node.actor, &announce.raw, 1);
|
||||
let (arxc, arxb, afrxc) = counts(&mut node.actor, 1);
|
||||
assert_eq!(afrxc, 1, "lower gravity is filtered");
|
||||
|
||||
node.actor.path_table.set_state(
|
||||
announce.destination,
|
||||
crate::constants::PathState::Unresponsive,
|
||||
);
|
||||
inbound(&mut node.actor, &announce.raw, 1);
|
||||
assert_eq!(
|
||||
counts(&mut node.actor, 1),
|
||||
(arxc + 1, arxb + announce.raw.len() as u64, afrxc),
|
||||
"an unresponsive path is kept"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_responses_awaited_and_queued_destinations_skip_the_prefilter() {
|
||||
let _clock = crate::test_clock::Clock::at(NOW);
|
||||
let mut node = node(true);
|
||||
let identity = rns_identity::identity::Identity::new();
|
||||
let current = plain(&identity, 400);
|
||||
let destination = current.destination;
|
||||
inbound(&mut node.actor, ¤t.raw, 1);
|
||||
let older = plain(&identity, 399);
|
||||
let older_response = signed(&identity, 398, 1, PacketContext::PathResponse, &[], None);
|
||||
let filtered = |node: &mut Node| counts(&mut node.actor, 2).2;
|
||||
|
||||
assert!(node.actor.announce_table.get(&destination).is_some());
|
||||
inbound(&mut node.actor, &older.raw, 2);
|
||||
assert_eq!(filtered(&mut node), 0, "a queued rebroadcast");
|
||||
|
||||
node.actor.announce_table.remove(&destination);
|
||||
inbound(&mut node.actor, &older_response.raw, 2);
|
||||
assert_eq!(filtered(&mut node), 0, "a path response");
|
||||
|
||||
node.actor.path_requests.insert(destination, NOW);
|
||||
inbound(&mut node.actor, &older.raw, 2);
|
||||
assert_eq!(filtered(&mut node), 0, "an awaited path");
|
||||
node.actor.path_requests.remove(&destination);
|
||||
|
||||
node.actor.path_table.get_mut(&destination).unwrap().expires = 0.0;
|
||||
inbound(&mut node.actor, &older.raw, 2);
|
||||
assert_eq!(
|
||||
filtered(&mut node),
|
||||
1,
|
||||
"an expired path not yet culled still counts"
|
||||
);
|
||||
|
||||
node.actor
|
||||
.request_recursive_discovery(destination, 1)
|
||||
.expect("discovery for the expired path");
|
||||
inbound(&mut node.actor, &older.raw, 2);
|
||||
assert_eq!(filtered(&mut node), 1, "a discovery request");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_on_a_detached_interface_takes_any_announce() {
|
||||
let _clock = crate::test_clock::Clock::at(NOW);
|
||||
let mut node = node(false);
|
||||
let identity = rns_identity::identity::Identity::new();
|
||||
let current = plain(&identity, 500);
|
||||
inbound(&mut node.actor, ¤t.raw, 1);
|
||||
node.actor
|
||||
.path_table
|
||||
.get_mut(¤t.destination)
|
||||
.unwrap()
|
||||
.interface_id = 9;
|
||||
|
||||
inbound(&mut node.actor, &plain(&identity, 499).raw, 2);
|
||||
|
||||
assert_eq!(counts(&mut node.actor, 2).2, 0);
|
||||
}
|
||||
|
||||
/// Python 1.6.1: a frame over the MTU, a HEADER_1 announce that leaves no
|
||||
/// room for a transport id, and a payload under 84 bytes are protocol
|
||||
/// violations, checked before the type filters (Transport.py). 317 bytes of
|
||||
/// app data is upstream's largest HEADER_1 announce: `Packet.pack` built a
|
||||
/// 484-byte frame and refused 318 bytes (`RNS.Packet(...).pack()`, 1.6.1).
|
||||
#[test]
|
||||
fn announce_size_gates_come_before_the_type_filters() {
|
||||
let _clock = crate::test_clock::Clock::at(NOW);
|
||||
let mut node = node(false);
|
||||
let violations = |node: &Node| node.actor.interfaces[&1].protocol_violations;
|
||||
|
||||
let fits = signed(
|
||||
&rns_identity::identity::Identity::new(),
|
||||
600,
|
||||
1,
|
||||
PacketContext::None,
|
||||
&[0xA5; 317],
|
||||
None,
|
||||
);
|
||||
assert_eq!(fits.raw.len(), 484);
|
||||
inbound(&mut node.actor, &fits.raw, 1);
|
||||
assert!(node.actor.path_table.get(&fits.destination).is_some());
|
||||
|
||||
let too_long = signed(
|
||||
&rns_identity::identity::Identity::new(),
|
||||
600,
|
||||
1,
|
||||
PacketContext::None,
|
||||
&[0xA5; 318],
|
||||
None,
|
||||
);
|
||||
inbound(&mut node.actor, &too_long.raw, 1);
|
||||
assert!(node.actor.path_table.get(&too_long.destination).is_none());
|
||||
assert_eq!(violations(&node), 1);
|
||||
|
||||
let relayed = signed(
|
||||
&rns_identity::identity::Identity::new(),
|
||||
600,
|
||||
1,
|
||||
PacketContext::None,
|
||||
&[0xA5; 317],
|
||||
Some([0x77; 16]),
|
||||
);
|
||||
assert_eq!(relayed.raw.len(), 500);
|
||||
inbound(&mut node.actor, &relayed.raw, 1);
|
||||
assert!(node.actor.path_table.get(&relayed.destination).is_some());
|
||||
assert_eq!(violations(&node), 1);
|
||||
|
||||
node.actor.destination_filter.block("blocked.type");
|
||||
let mut short = rns_wire::header::PacketHeader::unpack(&fits.raw).unwrap().0;
|
||||
short.destination_hash = [0x31; 16];
|
||||
let mut short = short.pack();
|
||||
short.extend_from_slice(&[0x11; 64]);
|
||||
short.extend_from_slice(&rns_identity::name_hash::name_hash("blocked.type"));
|
||||
short.extend_from_slice(&[0x22; 9]);
|
||||
inbound(&mut node.actor, &Bytes::from(short), 1);
|
||||
assert_eq!(violations(&node), 2, "83 bytes of payload");
|
||||
assert_eq!(counts(&mut node.actor, 1).2, 0);
|
||||
}
|
||||
|
||||
/// A blocked type is dropped silently; an unrequired one counts as filtered
|
||||
/// (Transport.py).
|
||||
#[test]
|
||||
fn only_an_unrequired_type_counts_as_filtered() {
|
||||
let _clock = crate::test_clock::Clock::at(NOW);
|
||||
let mut node = node(false);
|
||||
let identity = rns_identity::identity::Identity::new();
|
||||
node.actor.destination_filter.block(APP);
|
||||
inbound(&mut node.actor, &plain(&identity, 700).raw, 1);
|
||||
assert_eq!(counts(&mut node.actor, 1), (0, 0, 0));
|
||||
|
||||
let mut node = self::node(false);
|
||||
node.actor.destination_filter.set_required_only(true);
|
||||
inbound(&mut node.actor, &plain(&identity, 700).raw, 1);
|
||||
assert_eq!(counts(&mut node.actor, 1), (0, 0, 1));
|
||||
assert_eq!(node.actor.interfaces[&1].protocol_violations, 0);
|
||||
}
|
||||
|
||||
fn bursting(actor: &mut TransportActor, overrides: IngressOverrides) {
|
||||
let ingress = &mut actor.interfaces.get_mut(&1).unwrap().ingress;
|
||||
*ingress = IngressController::try_with_overrides(&overrides).unwrap();
|
||||
for _ in 0..50 {
|
||||
ingress.received_announce();
|
||||
}
|
||||
assert!(ingress.should_ingress_limit(), "precondition: a burst");
|
||||
}
|
||||
|
||||
/// A held announce counts with no bytes and no transport count; its release
|
||||
/// counts its bytes once (Transport.py, Interface.py).
|
||||
#[test]
|
||||
fn a_held_announce_counts_its_bytes_only_when_released() {
|
||||
let _clock = crate::test_clock::Clock::at(NOW);
|
||||
let mut node = node(false);
|
||||
bursting(&mut node.actor, IngressOverrides::default());
|
||||
let (arxc, arxb, _) = counts(&mut node.actor, 1);
|
||||
let rx_packets = totals(&mut node.actor).announce_rx_packets;
|
||||
let announce = plain(&rns_identity::identity::Identity::new(), 800);
|
||||
|
||||
inbound(&mut node.actor, &announce.raw, 1);
|
||||
|
||||
assert_eq!(node.actor.interfaces[&1].ingress.held_count(), 1);
|
||||
assert_eq!(counts(&mut node.actor, 1), (arxc + 1, arxb, 0));
|
||||
assert_eq!(totals(&mut node.actor).announce_rx_packets, rx_packets);
|
||||
|
||||
let held = std::mem::take(&mut node.actor.interfaces.get_mut(&1).unwrap().ingress)
|
||||
.cull_and_release(&[])
|
||||
.unwrap();
|
||||
node.actor.on_released_announce(held);
|
||||
assert!(node.actor.path_table.get(&announce.destination).is_some());
|
||||
assert_eq!(
|
||||
counts(&mut node.actor, 1),
|
||||
(1, announce.raw.len() as u64, 0),
|
||||
"a calm interface releases and counts the bytes"
|
||||
);
|
||||
assert_eq!(totals(&mut node.actor).announce_rx_packets, rx_packets + 1);
|
||||
}
|
||||
|
||||
/// Interface.py `hold_announce`: a replaced held entry and a refused one are
|
||||
/// both filtered.
|
||||
#[test]
|
||||
fn refused_and_replaced_holds_count_as_filtered() {
|
||||
let _clock = crate::test_clock::Clock::at(NOW);
|
||||
let mut node = node(false);
|
||||
bursting(
|
||||
&mut node.actor,
|
||||
IngressOverrides {
|
||||
max_held: Some(1),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let first = rns_identity::identity::Identity::new();
|
||||
inbound(&mut node.actor, &plain(&first, 900).raw, 1);
|
||||
assert_eq!(counts(&mut node.actor, 1).2, 0);
|
||||
inbound(
|
||||
&mut node.actor,
|
||||
&plain(&rns_identity::identity::Identity::new(), 900).raw,
|
||||
1,
|
||||
);
|
||||
assert_eq!(
|
||||
counts(&mut node.actor, 1).2,
|
||||
1,
|
||||
"refused: the buffer is full"
|
||||
);
|
||||
inbound(&mut node.actor, &plain(&first, 901).raw, 1);
|
||||
assert_eq!(counts(&mut node.actor, 1).2, 2, "replaced");
|
||||
assert_eq!(node.actor.interfaces[&1].ingress.held_count(), 1);
|
||||
}
|
||||
|
||||
fn learned_path(actor: &mut TransportActor, destination: [u8; 16], emitted: u64) {
|
||||
let mut path = crate::path_table::PathEntry::new(None, 1, 1, InterfaceMode::Gateway);
|
||||
path.random_blobs.push_back(random_blob(0x99, emitted));
|
||||
actor.path_table.insert(destination, path);
|
||||
}
|
||||
|
||||
fn hold(actor: &mut TransportActor, announce: &Announce) {
|
||||
actor
|
||||
.interfaces
|
||||
.get_mut(&1)
|
||||
.unwrap()
|
||||
.ingress
|
||||
.hold_announce(HeldAnnounce {
|
||||
raw: announce.raw.clone(),
|
||||
destination_hash: announce.destination,
|
||||
hops: 2,
|
||||
receiving_interface_id: 1,
|
||||
});
|
||||
}
|
||||
|
||||
fn released(actor: &mut TransportActor) -> usize {
|
||||
actor.last_held_announce_check = 0.0;
|
||||
actor.on_tick();
|
||||
let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
|
||||
let mut count = 0;
|
||||
while actor
|
||||
.inbound_rx
|
||||
.poll_recv(&mut cx, &actor.inbound_queues)
|
||||
.is_ready()
|
||||
{
|
||||
count += 1;
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
/// Interface.py culls held announces the prefilter rejects, but only on a
|
||||
/// pass where a release is due, and leaves them out of the release.
|
||||
#[test]
|
||||
fn a_held_announce_a_newer_path_outdates_is_culled_when_a_release_is_due() {
|
||||
let _clock = crate::test_clock::Clock::at(NOW);
|
||||
let mut node = node(false);
|
||||
node.actor.interfaces.get_mut(&1).unwrap().ingress = IngressController::new();
|
||||
let outdated = plain(&rns_identity::identity::Identity::new(), 1000);
|
||||
let useful = plain(&rns_identity::identity::Identity::new(), 1000);
|
||||
hold(&mut node.actor, &outdated);
|
||||
hold(&mut node.actor, &useful);
|
||||
learned_path(&mut node.actor, outdated.destination, 1001);
|
||||
learned_path(&mut node.actor, useful.destination, 999);
|
||||
|
||||
assert_eq!(released(&mut node.actor), 1);
|
||||
let ingress = &node.actor.interfaces[&1].ingress;
|
||||
assert_eq!(ingress.held_count(), 0, "the outdated one is culled");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn held_announces_are_not_culled_while_no_release_is_due() {
|
||||
let _clock = crate::test_clock::Clock::at(NOW);
|
||||
let mut node = node(false);
|
||||
bursting(&mut node.actor, IngressOverrides::default());
|
||||
let outdated = plain(&rns_identity::identity::Identity::new(), 1100);
|
||||
hold(&mut node.actor, &outdated);
|
||||
learned_path(&mut node.actor, outdated.destination, 1101);
|
||||
|
||||
assert_eq!(released(&mut node.actor), 0);
|
||||
assert_eq!(node.actor.interfaces[&1].ingress.held_count(), 1);
|
||||
}
|
||||
|
||||
/// A release re-enters `preprocess_inbound` (Interface.py), so the
|
||||
/// prefilter applies to it.
|
||||
#[test]
|
||||
fn a_released_announce_for_a_newer_path_is_prefiltered() {
|
||||
let _clock = crate::test_clock::Clock::at(NOW);
|
||||
let mut node = node(false);
|
||||
let announce = plain(&rns_identity::identity::Identity::new(), 1200);
|
||||
learned_path(&mut node.actor, announce.destination, 1201);
|
||||
|
||||
node.actor.on_released_announce(HeldAnnounce {
|
||||
raw: announce.raw.clone(),
|
||||
destination_hash: announce.destination,
|
||||
hops: 2,
|
||||
receiving_interface_id: 1,
|
||||
});
|
||||
|
||||
assert_eq!(counts(&mut node.actor, 1), (1, 0, 1));
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
//! Python 1.6.1 rebroadcast rules (Transport.py): a queued announce heard
|
||||
//! again on an interface off a shared medium is not sent back there
|
||||
//! (`IDX_AT_DEDUP_IFS`, `blocked_interfaces`), and an unresponsive path
|
||||
//! replaced by the same emission is not rebroadcast (`table_insertion_only`).
|
||||
use super::*;
|
||||
|
||||
const APP: &str = "rebroadcast.test";
|
||||
|
||||
struct Hub {
|
||||
actor: TransportActor,
|
||||
rx: HashMap<InterfaceId, mpsc::Receiver<Bytes>>,
|
||||
}
|
||||
|
||||
/// A transport node with interfaces 1–3; `shared` marks shared-medium ones.
|
||||
fn hub(shared: &[InterfaceId]) -> Hub {
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
actor.is_transport_enabled = true;
|
||||
actor.transport_identity_hash = Some([0x42; 16]);
|
||||
let mut rx = HashMap::new();
|
||||
for id in [1, 2, 3] {
|
||||
let (mut entry, receiver) = make_test_interface(&format!("rebroadcast_{id}"));
|
||||
entry.ingress = crate::ingress::IngressController::disabled();
|
||||
entry.shared_medium = shared.contains(&id);
|
||||
actor.interfaces.insert(id, entry);
|
||||
rx.insert(id, receiver);
|
||||
}
|
||||
Hub { actor, rx }
|
||||
}
|
||||
|
||||
fn inbound(actor: &mut TransportActor, raw: &Bytes, interface_id: InterfaceId) {
|
||||
actor.on_inbound(InboundPacket {
|
||||
raw: raw.clone(),
|
||||
interface_id,
|
||||
rssi: None,
|
||||
snr: None,
|
||||
q: None,
|
||||
});
|
||||
}
|
||||
|
||||
impl Hub {
|
||||
/// Frames sent on an interface since the last call.
|
||||
fn sent(&mut self, id: InterfaceId) -> usize {
|
||||
let rx = self.rx.get_mut(&id).unwrap();
|
||||
let mut sent = 0;
|
||||
while rx.try_recv().is_ok() {
|
||||
sent += 1;
|
||||
}
|
||||
sent
|
||||
}
|
||||
|
||||
fn drain(&mut self) {
|
||||
for id in [1, 2, 3] {
|
||||
self.sent(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn announce(hops: u8) -> (Bytes, [u8; 16]) {
|
||||
let identity = rns_identity::identity::Identity::new();
|
||||
make_announce_for_with_random_blob(&identity, APP, hops, random_blob(0x3C, 5000))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_queued_announce_heard_again_off_a_shared_medium_skips_that_interface() {
|
||||
let _clock = crate::test_clock::Clock::at(1_800_000_000.0);
|
||||
let mut hub = hub(&[]);
|
||||
let (raw, destination) = announce(0);
|
||||
inbound(&mut hub.actor, &raw, 1);
|
||||
inbound(&mut hub.actor, &raw, 2);
|
||||
assert_eq!(
|
||||
hub.actor
|
||||
.announce_table
|
||||
.get(&destination)
|
||||
.unwrap()
|
||||
.dedup_interfaces,
|
||||
vec![2]
|
||||
);
|
||||
hub.drain();
|
||||
|
||||
hub.actor.flush_pending_announces();
|
||||
|
||||
assert_eq!(hub.sent(2), 0, "interface 2 already has it");
|
||||
assert_eq!((hub.sent(1), hub.sent(3)), (1, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_heard_on_a_shared_medium_is_still_rebroadcast_there() {
|
||||
let _clock = crate::test_clock::Clock::at(1_800_000_000.0);
|
||||
let mut hub = hub(&[2]);
|
||||
let (raw, destination) = announce(0);
|
||||
inbound(&mut hub.actor, &raw, 1);
|
||||
inbound(&mut hub.actor, &raw, 2);
|
||||
assert!(
|
||||
hub.actor
|
||||
.announce_table
|
||||
.get(&destination)
|
||||
.unwrap()
|
||||
.dedup_interfaces
|
||||
.is_empty()
|
||||
);
|
||||
hub.drain();
|
||||
|
||||
hub.actor.flush_pending_announces();
|
||||
|
||||
assert_eq!((hub.sent(1), hub.sent(2), hub.sent(3)), (1, 1, 1));
|
||||
}
|
||||
|
||||
/// Only a copy of the queued packet itself counts (Transport.py compares
|
||||
/// packet hashes).
|
||||
#[test]
|
||||
fn a_different_announce_for_the_destination_is_not_a_copy() {
|
||||
let _clock = crate::test_clock::Clock::at(1_800_000_000.0);
|
||||
let mut hub = hub(&[]);
|
||||
let identity = rns_identity::identity::Identity::new();
|
||||
let (current, destination) =
|
||||
make_announce_for_with_random_blob(&identity, APP, 0, random_blob(0x01, 5000));
|
||||
let (older, _) = make_announce_for_with_random_blob(&identity, APP, 0, random_blob(0x02, 4999));
|
||||
inbound(&mut hub.actor, ¤t, 1);
|
||||
inbound(&mut hub.actor, &older, 2);
|
||||
assert!(
|
||||
hub.actor
|
||||
.announce_table
|
||||
.get(&destination)
|
||||
.unwrap()
|
||||
.dedup_interfaces
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
/// The path response retransmits on its attached interface whatever the
|
||||
/// dedup set says (Transport.py `outbound` with `attached_interface`).
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn an_attached_path_response_ignores_the_dedup_set() {
|
||||
let mut hub = hub(&[]);
|
||||
let (raw, destination) = announce(1);
|
||||
let response = Bytes::from(
|
||||
hub.actor
|
||||
.path_response_from_cached_announce(&raw, destination, 1)
|
||||
.unwrap(),
|
||||
);
|
||||
let now = now_f64();
|
||||
hub.actor.announce_table.insert(
|
||||
destination,
|
||||
crate::announce::AnnounceEntry {
|
||||
timestamp: now,
|
||||
retransmit_timeout: now - 1.0,
|
||||
retries: PATHFINDER_R,
|
||||
hops: 1,
|
||||
packet_raw: response.to_vec(),
|
||||
local_rebroadcasts: 0,
|
||||
block_rebroadcast: true,
|
||||
attached_interface: Some(2),
|
||||
source_interface: None,
|
||||
packet_hash: [0; 32],
|
||||
dedup_interfaces: vec![2],
|
||||
},
|
||||
);
|
||||
hub.actor.last_announces_check = 0.0;
|
||||
|
||||
hub.actor.on_tick();
|
||||
|
||||
assert_eq!(hub.rx.get_mut(&2).unwrap().try_recv().unwrap(), response);
|
||||
}
|
||||
|
||||
/// Transport.py `table_insertion_only`: the same emission with more hops
|
||||
/// replaces an unresponsive path but queues no rebroadcast.
|
||||
#[test]
|
||||
fn an_unresponsive_path_taken_by_the_same_emission_is_not_rebroadcast() {
|
||||
let _clock = crate::test_clock::Clock::at(1_800_000_000.0);
|
||||
let mut hub = hub(&[]);
|
||||
let identity = rns_identity::identity::Identity::new();
|
||||
let blob = random_blob(0xA4, 6000);
|
||||
let (current, destination) = make_announce_for_with_random_blob(&identity, APP, 1, blob);
|
||||
let (replay, _) = make_announce_for_with_random_blob(&identity, APP, 5, blob);
|
||||
inbound(&mut hub.actor, ¤t, 1);
|
||||
hub.actor.announce_table.remove(&destination);
|
||||
hub.actor
|
||||
.path_table
|
||||
.set_state(destination, crate::constants::PathState::Unresponsive);
|
||||
|
||||
inbound(&mut hub.actor, &replay, 2);
|
||||
|
||||
let path = hub.actor.path_table.get(&destination).unwrap();
|
||||
assert_eq!((path.hops, path.interface_id), (6, 2));
|
||||
assert!(hub.actor.announce_table.get(&destination).is_none());
|
||||
}
|
||||
@@ -5,6 +5,7 @@ use crate::path_discovery::DiscoveryError;
|
||||
fn relay() -> (TransportActor, Vec<mpsc::Receiver<Bytes>>) {
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
actor.is_transport_enabled = true;
|
||||
actor.stamp_policy.stamp_prs = false;
|
||||
let mut receivers = Vec::new();
|
||||
for id in 1..=3 {
|
||||
let (mut entry, rx) = make_test_interface("discovery API");
|
||||
|
||||
@@ -5,6 +5,7 @@ use crate::path_discovery::DiscoveryError;
|
||||
fn actor() -> (TransportActor, Vec<mpsc::Receiver<Bytes>>) {
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
actor.is_transport_enabled = true;
|
||||
actor.stamp_policy.stamp_prs = false;
|
||||
let mut receivers = Vec::new();
|
||||
for id in 1..=3 {
|
||||
let (tx, rx) = mpsc::channel(64);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! Held and cached announces re-enter inbound processing as Python
|
||||
//! re-injects them: past IFAC, without counting their bytes again
|
||||
//! (Interface.py, Transport.py).
|
||||
//! re-injects them: past IFAC (Interface.py, Transport.py).
|
||||
use super::*;
|
||||
use crate::ingress::HeldAnnounce;
|
||||
|
||||
@@ -41,7 +40,7 @@ fn release_held(actor: &mut TransportActor) {
|
||||
actor.inbound_rx.poll_recv(&mut cx, &actor.inbound_queues)
|
||||
{
|
||||
assert_eq!(class, crate::inbound_queues::TrafficClass::IngressLimited);
|
||||
actor.handle_inbound_event(class, item);
|
||||
actor.handle_inbound_event(item);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -32,6 +32,12 @@ fn inbound(raw: Bytes) -> TransportMessage {
|
||||
}
|
||||
|
||||
fn path_request(tag: u8) -> Bytes {
|
||||
path_request_for(&make_path_request_payload_with_tag(
|
||||
[0x77; 16], None, [tag; 16],
|
||||
))
|
||||
}
|
||||
|
||||
fn path_request_for(payload: &[u8]) -> Bytes {
|
||||
let header = rns_wire::header::PacketHeader {
|
||||
flags: rns_wire::flags::PacketFlags {
|
||||
header_type: rns_wire::flags::HeaderType::Header1,
|
||||
@@ -49,9 +55,7 @@ fn path_request(tag: u8) -> Bytes {
|
||||
context: rns_wire::context::PacketContext::None,
|
||||
};
|
||||
let mut raw = header.pack();
|
||||
raw.extend_from_slice(&make_path_request_payload_with_tag(
|
||||
[0x77; 16], None, [tag; 16],
|
||||
));
|
||||
raw.extend_from_slice(payload);
|
||||
Bytes::from(raw)
|
||||
}
|
||||
|
||||
@@ -130,14 +134,17 @@ fn queued_classes_drain_data_first_then_announce_then_path_request() {
|
||||
fn path_requests_during_a_path_request_burst_wait_behind_every_other_class() {
|
||||
let (mut actor, sender) = registered(lengths(8, 8, 8, 1));
|
||||
prime_ingress_pr_burst(&mut actor, 1);
|
||||
for tag in 1..=3u8 {
|
||||
sender.try_send(inbound(path_request(tag))).unwrap();
|
||||
for dest in 1..=3u8 {
|
||||
let payload = make_path_request_payload_with_tag([dest; 16], None, [dest; 16]);
|
||||
sender
|
||||
.try_send(inbound(path_request_for(&payload)))
|
||||
.unwrap();
|
||||
}
|
||||
// Each path request leaves the PR queue for the one-slot IL queue.
|
||||
// Each path request passes its gates, then waits in the one-slot IL queue.
|
||||
for _ in 0..3 {
|
||||
let (class, msg) = next(&mut actor).unwrap();
|
||||
assert_eq!(class, TrafficClass::PathRequest);
|
||||
actor.handle_inbound_event(class, msg);
|
||||
actor.handle_inbound_event(msg);
|
||||
}
|
||||
let snapshot = actor.inbound_queues.snapshot();
|
||||
assert_eq!(snapshot.heights, [0, 0, 0, 1]);
|
||||
@@ -151,15 +158,89 @@ fn path_requests_during_a_path_request_burst_wait_behind_every_other_class() {
|
||||
assert_eq!(actor.inbound_queues.snapshot().heights[3], 0);
|
||||
}
|
||||
|
||||
/// Transport.py classifies after the size, tag, and stamp gates, so a
|
||||
/// rejected request never takes an ingress-limited slot.
|
||||
#[test]
|
||||
fn a_rejected_path_request_takes_no_ingress_limited_slot() {
|
||||
let (mut actor, sender) = registered(lengths(8, 8, 8, 1));
|
||||
prime_ingress_pr_burst(&mut actor, 1);
|
||||
sender
|
||||
.try_send(inbound(path_request_for(&[0x31; 16])))
|
||||
.unwrap();
|
||||
let payload = make_path_request_payload_with_tag([0x32; 16], None, [0x32; 16]);
|
||||
sender
|
||||
.try_send(inbound(path_request_for(&payload)))
|
||||
.unwrap();
|
||||
while let Some((_, msg)) = next(&mut actor) {
|
||||
actor.handle_inbound_event(msg);
|
||||
if actor.inbound_queues.snapshot().heights[3] == 1 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let snapshot = actor.inbound_queues.snapshot();
|
||||
assert_eq!(snapshot.heights, [0, 0, 0, 1]);
|
||||
assert_eq!(snapshot.dropped, [0; 4]);
|
||||
assert!(actor.inflight_path_requests.contains_key(&[0x32; 16]));
|
||||
assert!(!actor.inflight_path_requests.contains_key(&[0x31; 16]));
|
||||
}
|
||||
|
||||
/// Transport.py registers a request as in flight on receipt, so a second
|
||||
/// request during the burst is dropped instead of queued behind the first.
|
||||
#[test]
|
||||
fn a_queued_ingress_limited_path_request_is_already_in_flight() {
|
||||
let (mut actor, sender) = registered(lengths(8, 8, 8, 8));
|
||||
actor.is_transport_enabled = true;
|
||||
prime_ingress_pr_burst(&mut actor, 1);
|
||||
for tag in [1u8, 2] {
|
||||
sender.try_send(inbound(path_request(tag))).unwrap();
|
||||
let (_, msg) = next(&mut actor).unwrap();
|
||||
actor.handle_inbound_event(msg);
|
||||
}
|
||||
assert!(actor.inflight_path_requests.contains_key(&[0x77; 16]));
|
||||
assert_eq!(actor.inbound_queues.snapshot().heights[3], 1);
|
||||
assert!(
|
||||
!actor.discovery_path_requests.contains_key(&[0x77; 16]),
|
||||
"an ingress-limited duplicate is not batched"
|
||||
);
|
||||
}
|
||||
|
||||
/// Transport.py:2271,2294@1.6.1 drops a request at a full queue or from an
|
||||
/// interface gone offline, and leaves it in flight; nothing is pending here.
|
||||
#[test]
|
||||
fn a_dropped_ingress_limited_path_request_releases_the_gate() {
|
||||
let (mut actor, sender) = registered(lengths(8, 8, 8, 1));
|
||||
actor.is_transport_enabled = true;
|
||||
prime_ingress_pr_burst(&mut actor, 1);
|
||||
for dest in [0x41u8, 0x42] {
|
||||
let payload = make_path_request_payload_with_tag([dest; 16], None, [dest; 16]);
|
||||
sender
|
||||
.try_send(inbound(path_request_for(&payload)))
|
||||
.unwrap();
|
||||
let (_, msg) = next(&mut actor).unwrap();
|
||||
actor.handle_inbound_event(msg);
|
||||
}
|
||||
assert!(actor.inflight_path_requests.contains_key(&[0x41; 16]));
|
||||
assert!(
|
||||
!actor.inflight_path_requests.contains_key(&[0x42; 16]),
|
||||
"dropped at the full queue"
|
||||
);
|
||||
|
||||
actor.interfaces.get_mut(&1).unwrap().online = Some(Arc::new(AtomicBool::new(false)));
|
||||
let (class, msg) = next(&mut actor).unwrap();
|
||||
assert_eq!(class, TrafficClass::IngressLimited);
|
||||
actor.handle_inbound_event(msg);
|
||||
assert!(
|
||||
!actor.inflight_path_requests.contains_key(&[0x41; 16]),
|
||||
"dropped from an offline interface"
|
||||
);
|
||||
}
|
||||
|
||||
/// Python decides at preprocess time and passes `ingress_limited` into
|
||||
/// `path_request`, so a queued ingress-limited request is never forwarded
|
||||
/// recursively even if the burst ended meanwhile (Transport.py).
|
||||
#[test]
|
||||
fn an_ingress_limited_path_request_is_not_forwarded_recursively() {
|
||||
for (class, forwarded) in [
|
||||
(TrafficClass::PathRequest, true),
|
||||
(TrafficClass::IngressLimited, false),
|
||||
] {
|
||||
for limited in [false, true] {
|
||||
let (mut actor, tx) = TransportActor::new_with_queues(64, 1024, lengths(8, 8, 8, 8));
|
||||
actor.is_transport_enabled = true;
|
||||
let (mut entry, _wire) = make_test_interface("requestor");
|
||||
@@ -168,9 +249,24 @@ fn an_ingress_limited_path_request_is_not_forwarded_recursively() {
|
||||
actor.handle_message(TransportMessage::RegisterInterface { id: 1, entry });
|
||||
let (outbound, mut outbound_rx) = make_test_interface("outbound");
|
||||
actor.interfaces.insert(2, outbound);
|
||||
if limited {
|
||||
prime_ingress_pr_burst(&mut actor, 1);
|
||||
}
|
||||
sender.try_send(inbound(path_request(1))).unwrap();
|
||||
let (_, item) = next(&mut actor).unwrap();
|
||||
actor.handle_inbound_event(class, item);
|
||||
assert_eq!(outbound_rx.try_recv().is_ok(), forwarded, "{class:?}");
|
||||
actor.handle_inbound_event(item);
|
||||
if limited {
|
||||
assert!(outbound_rx.try_recv().is_err(), "deferred");
|
||||
actor.interfaces.get_mut(&1).unwrap().ingress =
|
||||
crate::ingress::IngressController::new();
|
||||
let (class, item) = next(&mut actor).unwrap();
|
||||
assert_eq!(class, TrafficClass::IngressLimited);
|
||||
actor.handle_inbound_event(item);
|
||||
}
|
||||
assert_eq!(
|
||||
outbound_rx.try_recv().is_ok(),
|
||||
!limited,
|
||||
"limited={limited}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -474,6 +474,31 @@ fn a_parent_takes_its_childrens_announce_bytes_but_not_their_counts() {
|
||||
assert_eq!(stats(&mut actor, 2).announces_received, 1);
|
||||
}
|
||||
|
||||
/// AutoInterface keeps the base counters, so its peers' announces count on it
|
||||
/// as well (AutoInterface.py, Interface.py).
|
||||
#[test]
|
||||
fn an_auto_interface_counts_its_peers_announces() {
|
||||
let mut actor = hub();
|
||||
let (mut parent, _parent_rx) = make_test_interface("auto");
|
||||
parent.inspection = Some(
|
||||
crate::messages::InterfaceInspectionSource::new(Default::default).with_identity(
|
||||
crate::messages::InterfaceIdentity::bracketed("AutoInterface", "auto"),
|
||||
),
|
||||
);
|
||||
actor.interfaces.insert(1, parent);
|
||||
let (mut peer, _peer_rx) = make_test_interface("auto/peer");
|
||||
peer.parent_id = Some(1);
|
||||
actor.interfaces.insert(2, peer);
|
||||
let (announce, _) = make_valid_announce("stats.auto.peer", 0);
|
||||
let size = announce.len() as u64;
|
||||
inbound(&mut actor, announce, 2);
|
||||
let parent = stats(&mut actor, 1);
|
||||
assert_eq!(
|
||||
(parent.announces_received, parent.announce_rx_bytes),
|
||||
(1, size)
|
||||
);
|
||||
}
|
||||
|
||||
/// Totals sum top-level interfaces other than the shared-instance server and
|
||||
/// keep what they counted when an interface leaves (Transport.py).
|
||||
#[test]
|
||||
@@ -494,14 +519,20 @@ fn traffic_totals_are_cumulative_over_top_level_interfaces() {
|
||||
actor.interfaces.insert(id, entry);
|
||||
}
|
||||
actor.count_traffic(1_000.0);
|
||||
for id in 1..=3 {
|
||||
actor.interfaces.get_mut(&id).unwrap().received.accepted += 100;
|
||||
}
|
||||
for counter in &counters {
|
||||
counter.fetch_add(100, std::sync::atomic::Ordering::Relaxed);
|
||||
counter.fetch_add(1_000, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
actor.count_traffic(1_001.0);
|
||||
let measured = totals(&mut actor);
|
||||
assert!(measured.measured);
|
||||
assert_eq!(measured.rxb, 100, "only the top-level non-shared interface");
|
||||
assert_eq!(
|
||||
measured.rxb, 100,
|
||||
"accepted bytes of the top-level non-shared interface, not the driver's wire count"
|
||||
);
|
||||
assert!(measured.rxs > 0.0);
|
||||
|
||||
actor.deregister_interface(1);
|
||||
@@ -524,3 +555,339 @@ fn traffic_totals_count_never_used_paths() {
|
||||
assert_eq!(measured.path_count, 3);
|
||||
assert_eq!(measured.unused_path_count, 2);
|
||||
}
|
||||
|
||||
fn received(actor: &mut TransportActor, id: InterfaceId) -> (u64, u64) {
|
||||
let entry = stats(actor, id);
|
||||
(entry.rx_bytes, entry.filtered_rx_bytes)
|
||||
}
|
||||
|
||||
/// Python 1.6.1 counts each frame once in `Transport.inbound`: accepted bytes
|
||||
/// in `rxb` and `rx_packets`, filtered ones in `frxb` (Transport.py:1973-1996).
|
||||
#[test]
|
||||
fn received_bytes_split_into_accepted_and_filtered() {
|
||||
let mut actor = hub();
|
||||
let _rx = attach(&mut actor, 1);
|
||||
let data = make_data_packet([0x71; 16], 0);
|
||||
let len = data.len() as u64;
|
||||
inbound(&mut actor, data.clone(), 1);
|
||||
assert_eq!(received(&mut actor, 1), (len, 0));
|
||||
assert_eq!(totals(&mut actor).rx_packets, 1);
|
||||
|
||||
inbound(&mut actor, data, 1);
|
||||
assert_eq!(
|
||||
received(&mut actor, 1),
|
||||
(len, len),
|
||||
"a duplicate is filtered"
|
||||
);
|
||||
assert_eq!(
|
||||
totals(&mut actor).rx_packets,
|
||||
1,
|
||||
"rx_packets counts accepted packets only"
|
||||
);
|
||||
|
||||
let short_request = path_request([0x72; 16], &[0xA2; 15]);
|
||||
inbound(&mut actor, short_request.clone(), 1);
|
||||
assert_eq!(
|
||||
received(&mut actor, 1),
|
||||
(len, len + short_request.len() as u64),
|
||||
"a path request of an invalid size is filtered"
|
||||
);
|
||||
|
||||
let request = path_request([0x73; 16], &[0xA3; 16]);
|
||||
inbound(&mut actor, request.clone(), 1);
|
||||
let accepted = len + request.len() as u64;
|
||||
assert_eq!(received(&mut actor, 1).0, accepted);
|
||||
assert_eq!(totals(&mut actor).rx_packets, 2);
|
||||
|
||||
let (announce, _) = make_valid_announce("stats.accepted.announce", 1);
|
||||
inbound(&mut actor, announce.clone(), 1);
|
||||
assert_eq!(received(&mut actor, 1).0, accepted + announce.len() as u64);
|
||||
assert_eq!(totals(&mut actor).rx_packets, 3);
|
||||
}
|
||||
|
||||
/// A path request joining one in flight is accepted but never reaches
|
||||
/// `rx_packets` (Transport.py:2256).
|
||||
#[test]
|
||||
fn a_batched_path_request_is_accepted_without_counting_a_packet() {
|
||||
let mut actor = hub();
|
||||
let _rx = attach(&mut actor, 1);
|
||||
let destination = [0x74; 16];
|
||||
actor.inflight_path_requests.insert(destination, now_f64());
|
||||
let request = path_request(destination, &[0xA4; 16]);
|
||||
inbound(&mut actor, request.clone(), 1);
|
||||
assert_eq!(received(&mut actor, 1), (request.len() as u64, 0));
|
||||
assert_eq!(totals(&mut actor).rx_packets, 0);
|
||||
}
|
||||
|
||||
/// IFAC failures are filtered with the IFAC bytes counted.
|
||||
#[test]
|
||||
fn an_ifac_failure_is_filtered() {
|
||||
let mut actor = hub();
|
||||
attach_ifac(&mut actor, 1, [0x5A; 64]);
|
||||
let raw = make_data_packet([0x75; 16], 0);
|
||||
let mut flagged = raw.to_vec();
|
||||
flagged[0] |= 0x80;
|
||||
flagged.splice(2..2, [0u8; 8]);
|
||||
let len = flagged.len() as u64;
|
||||
inbound(&mut actor, flagged, 1);
|
||||
assert_eq!(stats(&mut actor, 1).ifac_violations, 1);
|
||||
assert_eq!(received(&mut actor, 1), (0, len));
|
||||
assert_eq!(totals(&mut actor).rx_packets, 0);
|
||||
}
|
||||
|
||||
/// A held announce is filtered and its release counts again, now accepted
|
||||
/// (Transport.py:2165, Interface.py:339-341).
|
||||
#[test]
|
||||
fn a_held_announce_is_filtered_then_accepted_on_release() {
|
||||
let mut actor = hub();
|
||||
let _rx = attach(&mut actor, 1);
|
||||
let ingress = &mut actor.interfaces.get_mut(&1).unwrap().ingress;
|
||||
for _ in 0..50 {
|
||||
ingress.received_announce();
|
||||
}
|
||||
assert!(ingress.should_ingress_limit(), "precondition: a burst");
|
||||
let (announce, destination) = make_valid_announce("stats.held", 1);
|
||||
let len = announce.len() as u64;
|
||||
inbound(&mut actor, announce.clone(), 1);
|
||||
assert_eq!(actor.interfaces[&1].ingress.held_count(), 1);
|
||||
assert_eq!(received(&mut actor, 1), (0, len));
|
||||
assert_eq!(totals(&mut actor).rx_packets, 0);
|
||||
|
||||
// The burst is over by the time Python releases it.
|
||||
actor.interfaces.get_mut(&1).unwrap().ingress = crate::ingress::IngressController::new();
|
||||
actor.on_released_announce(crate::ingress::HeldAnnounce {
|
||||
raw: announce,
|
||||
destination_hash: destination,
|
||||
hops: 1,
|
||||
receiving_interface_id: 1,
|
||||
});
|
||||
assert!(actor.path_table.has_path(&destination));
|
||||
assert_eq!(received(&mut actor, 1), (len, len));
|
||||
assert_eq!(totals(&mut actor).rx_packets, 1);
|
||||
}
|
||||
|
||||
/// A spawned child adds both counters to its listener, and the traffic count
|
||||
/// samples filtered bytes into the totals.
|
||||
#[test]
|
||||
fn a_child_adds_accepted_and_filtered_bytes_to_its_parent() {
|
||||
let mut actor = hub();
|
||||
let _parent = attach(&mut actor, 1);
|
||||
let (mut child, _rx) = make_test_interface("stats_1/client_2");
|
||||
child.parent_id = Some(1);
|
||||
actor.interfaces.insert(2, child);
|
||||
actor.count_traffic(1_000.0);
|
||||
|
||||
let data = make_data_packet([0x76; 16], 0);
|
||||
let len = data.len() as u64;
|
||||
inbound(&mut actor, data.clone(), 2);
|
||||
inbound(&mut actor, data, 2);
|
||||
assert_eq!(received(&mut actor, 2), (len, len));
|
||||
assert_eq!(received(&mut actor, 1), (len, len));
|
||||
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
actor.count_traffic(1_001.0);
|
||||
let measured = totals(&mut actor);
|
||||
assert_eq!((measured.rxb, measured.frxb, measured.ftxb), (len, len, 0));
|
||||
assert!(measured.frxs > 0.0);
|
||||
let parent = stats(&mut actor, 1);
|
||||
assert!(
|
||||
parent
|
||||
.filtered_speeds
|
||||
.is_some_and(|[frxs, ftxs]| frxs > 0.0 && ftxs == 0.0)
|
||||
);
|
||||
assert_eq!(parent.filtered_tx_bytes, 0);
|
||||
}
|
||||
|
||||
fn transit_link(
|
||||
actor: &mut TransportActor,
|
||||
link_id: [u8; 16],
|
||||
destination_hash: [u8; 16],
|
||||
validated: bool,
|
||||
) {
|
||||
actor.link_table.insert(
|
||||
link_id,
|
||||
crate::link_table::LinkEntry {
|
||||
interface_owner: actor.interfaces.get(&2).map(|entry| entry.owner.clone()),
|
||||
receiving_owner: actor.interfaces.get(&1).map(|entry| entry.owner.clone()),
|
||||
requested_mode: 1,
|
||||
accepted_mtu_ceiling: 500,
|
||||
traffic: 0,
|
||||
timestamp: now_f64(),
|
||||
next_hop: Some([0xBB; 16]),
|
||||
interface_id: 2,
|
||||
remaining_hops: 1,
|
||||
destination_hash,
|
||||
validated,
|
||||
proof_timeout: now_f64() + 120.0,
|
||||
receiving_interface: 1,
|
||||
taken_hops: 1,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn link_packet(link_id: [u8; 16], tag: u8) -> Bytes {
|
||||
packet(
|
||||
DestinationType::Link,
|
||||
PacketType::Data,
|
||||
0,
|
||||
None,
|
||||
link_id,
|
||||
&[tag; 24],
|
||||
)
|
||||
}
|
||||
|
||||
/// Python 1.6.1 counts relayed Link packets in `link_rxb` and `link_txb`
|
||||
/// unless they come from or go to a local client, and every forwarded byte
|
||||
/// in the Link's `IDX_LT_TRXB` (Transport.py:2509-2549).
|
||||
#[test]
|
||||
fn relayed_link_packets_count_as_link_traffic() {
|
||||
let mut actor = hub();
|
||||
let mut initiator_rx = attach(&mut actor, 1);
|
||||
let mut destination_rx = attach(&mut actor, 2);
|
||||
let link_id = [0x81; 16];
|
||||
transit_link(&mut actor, link_id, [0x82; 16], true);
|
||||
|
||||
let outbound = link_packet(link_id, 1);
|
||||
inbound(&mut actor, outbound.clone(), 1);
|
||||
assert!(
|
||||
destination_rx.try_recv().is_ok(),
|
||||
"forwarded toward the destination"
|
||||
);
|
||||
let inbound_reply = link_packet(link_id, 2);
|
||||
inbound(&mut actor, inbound_reply.clone(), 2);
|
||||
assert!(
|
||||
initiator_rx.try_recv().is_ok(),
|
||||
"forwarded toward the initiator"
|
||||
);
|
||||
|
||||
let both = (outbound.len() + inbound_reply.len()) as u64;
|
||||
let measured = totals(&mut actor);
|
||||
assert_eq!((measured.lrxb, measured.ltxb), (both, both));
|
||||
assert_eq!(actor.link_table.get(&link_id).unwrap().traffic, both);
|
||||
|
||||
inbound(&mut actor, outbound.clone(), 1);
|
||||
assert!(
|
||||
destination_rx.try_recv().is_err(),
|
||||
"a duplicate is not relayed"
|
||||
);
|
||||
assert_eq!(stats(&mut actor, 1).packet_filter_hits, 1);
|
||||
assert_eq!(
|
||||
stats(&mut actor, 1).filtered_rx_bytes,
|
||||
outbound.len() as u64,
|
||||
"the deferred duplicate check filters, as Python's packet filter"
|
||||
);
|
||||
assert_eq!(totals(&mut actor).lrxb, both);
|
||||
|
||||
actor.interfaces.get_mut(&1).unwrap().role = InterfaceRole::LocalClient;
|
||||
// A local client's packets keep zero hops.
|
||||
actor.link_table.get_mut(&link_id).unwrap().taken_hops = 0;
|
||||
let from_client = link_packet(link_id, 3);
|
||||
inbound(&mut actor, from_client.clone(), 1);
|
||||
assert!(destination_rx.try_recv().is_ok());
|
||||
let to_client = link_packet(link_id, 4);
|
||||
inbound(&mut actor, to_client.clone(), 2);
|
||||
assert!(initiator_rx.try_recv().is_ok());
|
||||
let measured = totals(&mut actor);
|
||||
assert_eq!(
|
||||
(measured.lrxb, measured.ltxb),
|
||||
(
|
||||
both + to_client.len() as u64,
|
||||
both + from_client.len() as u64
|
||||
),
|
||||
"local client legs are not link traffic"
|
||||
);
|
||||
assert_eq!(
|
||||
actor.link_table.get(&link_id).unwrap().traffic,
|
||||
both + (from_client.len() + to_client.len()) as u64,
|
||||
"the per-link counter keeps every forwarded byte"
|
||||
);
|
||||
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
actor.count_traffic(1_000.0);
|
||||
let measured = totals(&mut actor);
|
||||
assert!(measured.lrxs > 0.0 && measured.ltxs > 0.0);
|
||||
}
|
||||
|
||||
/// Python's `link_distribution()` groups relayed Links by destination with
|
||||
/// their traffic and the hashes of the interfaces they came in on.
|
||||
#[test]
|
||||
fn link_distribution_groups_relayed_links_by_destination() {
|
||||
let mut actor = hub();
|
||||
let _initiator_rx = attach(&mut actor, 1);
|
||||
let mut destination_rx = attach(&mut actor, 2);
|
||||
let destination = [0x83; 16];
|
||||
transit_link(&mut actor, [0x84; 16], destination, true);
|
||||
transit_link(&mut actor, [0x85; 16], destination, false);
|
||||
transit_link(&mut actor, [0x86; 16], [0x87; 16], true);
|
||||
let relayed = link_packet([0x84; 16], 5);
|
||||
inbound(&mut actor, relayed.clone(), 1);
|
||||
assert!(destination_rx.try_recv().is_ok());
|
||||
|
||||
let TransportQueryResponse::LinkDistribution(entries) =
|
||||
actor.handle_query(TransportQuery::GetLinkDistribution)
|
||||
else {
|
||||
panic!("unexpected link distribution response");
|
||||
};
|
||||
let from = vec![rns_crypto::sha::sha256(b"stats_1")];
|
||||
assert_eq!(entries.len(), 2);
|
||||
assert_eq!(entries[0].destination_hash, destination);
|
||||
assert_eq!((entries[0].active, entries[0].pending), (1, 1));
|
||||
assert_eq!(entries[0].traffic, relayed.len() as u64);
|
||||
assert_eq!(entries[0].from_interfaces, from);
|
||||
assert_eq!(entries[1].destination_hash, [0x87; 16]);
|
||||
assert_eq!(
|
||||
(entries[1].active, entries[1].pending, entries[1].traffic),
|
||||
(1, 0, 0)
|
||||
);
|
||||
}
|
||||
|
||||
/// An own Link's packets count as link traffic: what it receives
|
||||
/// (`Link.receive`, Link.py:1034) and what it sends (Packet.py:312).
|
||||
#[test]
|
||||
fn an_own_links_packets_count_as_link_traffic() {
|
||||
let mut actor = hub();
|
||||
let mut rx = attach(&mut actor, 1);
|
||||
let link_id = [0x88; 16];
|
||||
let (delivery_tx, mut delivery_rx) = mpsc::channel(4);
|
||||
actor.local_destinations.insert(link_id);
|
||||
actor.destination_channels.insert(link_id, delivery_tx);
|
||||
let received_packet = link_packet(link_id, 6);
|
||||
inbound(&mut actor, received_packet.clone(), 1);
|
||||
assert!(delivery_rx.try_recv().is_ok());
|
||||
|
||||
let binding = crate::messages::LinkEndpointBinding {
|
||||
interface_owner: actor.interfaces.get(&1).map(|entry| entry.owner.id()),
|
||||
link_id,
|
||||
interface_id: 1,
|
||||
role: crate::messages::LinkEndpointRole::Initiator,
|
||||
};
|
||||
let (lifecycle_tx, _lifecycle_rx) = mpsc::unbounded_channel();
|
||||
let (bind_tx, _bind_rx) = tokio::sync::oneshot::channel();
|
||||
actor.handle_message(TransportMessage::BindLinkEndpoint {
|
||||
binding,
|
||||
lifecycle_tx,
|
||||
result_tx: bind_tx,
|
||||
});
|
||||
let sent = link_packet(link_id, 7);
|
||||
let (send_tx, mut send_rx) = tokio::sync::oneshot::channel();
|
||||
actor.handle_message(TransportMessage::SendLinkEndpoint {
|
||||
link_id,
|
||||
role: crate::messages::LinkEndpointRole::Initiator,
|
||||
request: OutboundRequest {
|
||||
raw: sent.clone(),
|
||||
destination_hash: link_id,
|
||||
},
|
||||
result_tx: send_tx,
|
||||
});
|
||||
assert_eq!(
|
||||
send_rx.try_recv().unwrap(),
|
||||
crate::messages::LinkEndpointSendResult::Sent
|
||||
);
|
||||
assert!(rx.try_recv().is_ok());
|
||||
|
||||
let measured = totals(&mut actor);
|
||||
assert_eq!(
|
||||
(measured.lrxb, measured.ltxb),
|
||||
(received_packet.len() as u64, sent.len() as u64)
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! A local client's path response to a pending external request against
|
||||
//! upstream RNS 1.6.0. Expected values come from
|
||||
//! `tests/fixtures/local_client_path_response/generate.py`.
|
||||
//! upstream RNS 1.6.1, and the path state of a local client's announce.
|
||||
//! Expected values come from `tests/fixtures/local_client_path_response/generate.py`.
|
||||
|
||||
use super::*;
|
||||
use crate::InterfaceTransportSender;
|
||||
@@ -27,7 +27,7 @@ fn golden() -> Value {
|
||||
"../../../tests/fixtures/local_client_path_response/local_client_path_response.json"
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(v["provenance"]["rns_version"], "1.6.0");
|
||||
assert_eq!(v["provenance"]["rns_version"], "1.6.1");
|
||||
v
|
||||
}
|
||||
|
||||
@@ -47,14 +47,15 @@ fn iface(name: &str, tx: mpsc::Sender<Bytes>) -> InterfaceEntry {
|
||||
}
|
||||
|
||||
/// A local client's path response to a pending external request enters the
|
||||
/// announce table and is rebroadcast once, context NONE, on every interface.
|
||||
/// announce table and goes once, as a path response, to the requester only
|
||||
/// (Transport.py 1.6.1, 70eb417d).
|
||||
#[tokio::test]
|
||||
async fn local_client_path_response_is_rebroadcast_once_everywhere() {
|
||||
async fn local_client_path_response_goes_only_to_the_requester() {
|
||||
let g = golden();
|
||||
let lp = &g["local_pr"];
|
||||
assert_eq!(lp["pending_cleared"], true);
|
||||
assert_eq!(lp["announce_table_entry"]["block_rebroadcasts"], true);
|
||||
assert!(lp["ext_a_sent_before_jobs"].as_array().unwrap().is_empty());
|
||||
let none_ctx = g["consts"]["NONE"].as_u64().unwrap() as u8;
|
||||
let raw = Bytes::from(hexv(&lp["announce_raw"]));
|
||||
let dest: [u8; 16] = hexv(&lp["destination_hash"]).try_into().unwrap();
|
||||
|
||||
@@ -105,14 +106,66 @@ async fn local_client_path_response_is_rebroadcast_once_everywhere() {
|
||||
}
|
||||
}
|
||||
assert_eq!(seen.len(), expected.len(), "{name}: {seen:?}");
|
||||
assert_eq!(
|
||||
seen[0],
|
||||
(HeaderType::Header2, none_ctx, Some(transport_id)),
|
||||
"{name}"
|
||||
);
|
||||
assert_eq!(expected[0]["context"].as_u64(), Some(u64::from(none_ctx)));
|
||||
assert_ne!(seen[0].1, PacketContext::PathResponse.to_byte());
|
||||
for (seen, expected) in seen.iter().zip(expected) {
|
||||
assert_eq!(expected["header_type"], 1, "{name}");
|
||||
let context = expected["context"].as_u64().unwrap() as u8;
|
||||
assert_eq!(context, PacketContext::PathResponse.to_byte(), "{name}");
|
||||
assert_eq!(
|
||||
*seen,
|
||||
(HeaderType::Header2, context, Some(transport_id)),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
tx.send(TransportMessage::Shutdown).await.unwrap();
|
||||
running.await.unwrap();
|
||||
}
|
||||
|
||||
fn inbound(actor: &mut TransportActor, raw: Bytes, interface_id: InterfaceId) {
|
||||
actor.on_inbound(InboundPacket {
|
||||
raw,
|
||||
interface_id,
|
||||
rssi: None,
|
||||
snr: None,
|
||||
q: None,
|
||||
});
|
||||
}
|
||||
|
||||
/// Transport.py 1.6.1 (833f6cf2): a local client's announce leaves its path
|
||||
/// responsive and used, also when the rate limit holds it back; another
|
||||
/// announce leaves the path unknown and unused.
|
||||
#[test]
|
||||
fn local_client_announce_marks_its_path_responsive() {
|
||||
let (mut actor, _tx) = TransportActor::new();
|
||||
let (external, _external_rx) = make_test_interface("external");
|
||||
let (mut client, _client_rx) = make_test_interface("local-client");
|
||||
client.role = InterfaceRole::LocalClient;
|
||||
client = client.with_announce_rate(3600.0, 0, 0.0);
|
||||
actor.interfaces.insert(1, external);
|
||||
actor.interfaces.insert(2, client);
|
||||
|
||||
let (remote, remote_dest) = make_valid_announce("t16.remote", 0);
|
||||
inbound(&mut actor, remote, 1);
|
||||
assert_eq!(actor.path_table.get_state(&remote_dest), PathState::Unknown);
|
||||
assert_eq!(actor.path_table.get(&remote_dest).unwrap().used, 0.0);
|
||||
|
||||
let identity = rns_identity::identity::Identity::new();
|
||||
let mut queued = None;
|
||||
for emitted in [1_000, 2_000] {
|
||||
let (raw, dest) =
|
||||
make_announce_for_with_random_blob(&identity, "t16.local", 0, random_blob(1, emitted));
|
||||
inbound(&mut actor, raw, 2);
|
||||
// The second is rate-blocked: its rebroadcast is not queued.
|
||||
let entry = actor.announce_table.get(&dest).unwrap().packet_raw.clone();
|
||||
assert_eq!(*queued.get_or_insert_with(|| entry.clone()), entry);
|
||||
let path = actor.path_table.get(&dest).unwrap();
|
||||
assert!(path.has_random_blob(&random_blob(1, emitted)));
|
||||
assert_eq!(path.hops, 0);
|
||||
assert!(path.used > 0.0, "emitted {emitted}");
|
||||
assert_eq!(
|
||||
actor.path_table.get_state(&dest),
|
||||
PathState::Responsive,
|
||||
"emitted {emitted}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -247,6 +247,7 @@ fn packet_capacity_authenticated_proof_obeys_request_ceiling_and_keeps_original_
|
||||
receiving_owner: Some(first_owner),
|
||||
requested_mode: 1,
|
||||
accepted_mtu_ceiling: 1000,
|
||||
traffic: 0,
|
||||
},
|
||||
);
|
||||
for signal in [SignallingData::new(2, 500), SignallingData::new(1, 1001)] {
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
//! The path-request in-flight gate (Transport.py `inflight_path_requests`):
|
||||
//! a request that leaves nothing pending releases it, and a local client's
|
||||
//! request for a live path is answered from the table instead of batched.
|
||||
use super::*;
|
||||
use rns_wire::header::PacketHeader;
|
||||
|
||||
fn relay() -> TransportActor {
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
actor.is_transport_enabled = true;
|
||||
actor.transport_identity_hash = Some([0x44; 16]);
|
||||
actor
|
||||
}
|
||||
|
||||
fn network(
|
||||
actor: &mut TransportActor,
|
||||
id: InterfaceId,
|
||||
mode: InterfaceMode,
|
||||
) -> mpsc::Receiver<Bytes> {
|
||||
let (mut entry, rx) = make_test_interface(&format!("if{id}"));
|
||||
entry.mode = mode;
|
||||
entry.ingress = crate::ingress::IngressController::disabled();
|
||||
actor.interfaces.insert(id, entry);
|
||||
rx
|
||||
}
|
||||
|
||||
fn request(actor: &mut TransportActor, dest: [u8; 16], tag: u8, interface: InterfaceId) {
|
||||
actor.handle_inbound_path_request(
|
||||
&make_path_request_payload_with_tag(dest, None, [tag; 16]),
|
||||
interface,
|
||||
);
|
||||
}
|
||||
|
||||
fn pr_dest() -> [u8; 16] {
|
||||
rns_identity::destination::Destination::hash_from_name_and_identity(
|
||||
"rnstransport.path.request",
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
/// Drains `rx`; whether it carried a path request for `dest`.
|
||||
fn requested(rx: &mut mpsc::Receiver<Bytes>, dest: [u8; 16]) -> bool {
|
||||
let mut seen = false;
|
||||
while let Ok(raw) = rx.try_recv() {
|
||||
let (header, offset) = PacketHeader::unpack(&raw).unwrap();
|
||||
seen |= header.destination_hash == pr_dest() && raw[offset..offset + 16] == dest;
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
/// Drains `rx`; whether it carried a path response for `dest`.
|
||||
fn answered(rx: &mut mpsc::Receiver<Bytes>, dest: [u8; 16]) -> bool {
|
||||
let mut seen = false;
|
||||
while let Ok(raw) = rx.try_recv() {
|
||||
let (header, _) = PacketHeader::unpack(&raw).unwrap();
|
||||
seen |= header.destination_hash == dest
|
||||
&& header.context == rns_wire::context::PacketContext::PathResponse;
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
/// A live path via interface 2, its cached announce edited by `cached`;
|
||||
/// returns the destination and the announce as received.
|
||||
fn known_path(
|
||||
actor: &mut TransportActor,
|
||||
tag: &str,
|
||||
cached: impl FnOnce(&mut Vec<u8>),
|
||||
) -> ([u8; 16], Vec<u8>) {
|
||||
let dir = unique_temp_dir(tag);
|
||||
actor.storage_dir = Some(dir.clone());
|
||||
actor.kd.attach_storage(&dir);
|
||||
let (raw, dest) = make_valid_announce(&format!("test.pr_gate.{tag}"), 1);
|
||||
let mut stored = raw.to_vec();
|
||||
cached(&mut stored);
|
||||
crate::store::seed_cached_announce(&dir, &cache_key(&raw), &stored, None).unwrap();
|
||||
let mut path = PathEntry::new(Some([0xAB; 16]), 2, 2, InterfaceMode::Full);
|
||||
path.packet_hash = Some(cache_key(&raw));
|
||||
actor.path_table.insert(dest, path);
|
||||
(dest, raw.to_vec())
|
||||
}
|
||||
|
||||
fn cache_key(raw: &[u8]) -> [u8; 32] {
|
||||
rns_wire::hash::packet_hash(raw, rns_wire::flags::HeaderType::Header1)
|
||||
}
|
||||
|
||||
/// Transport.py:4178-4179@1.6.1 ignores a request for an unknown
|
||||
/// destination on an interface that does not search, leaving it in flight
|
||||
/// (:2242-2243), so a gateway requester was batched instead of searched for.
|
||||
#[test]
|
||||
fn an_ignored_request_releases_the_gate() {
|
||||
let mut actor = relay();
|
||||
let _full = network(&mut actor, 1, InterfaceMode::Full);
|
||||
let _gateway = network(&mut actor, 2, InterfaceMode::Gateway);
|
||||
let mut other = network(&mut actor, 3, InterfaceMode::Full);
|
||||
let dest = [0x51; 16];
|
||||
request(&mut actor, dest, 1, 1);
|
||||
assert!(
|
||||
!requested(&mut other, dest),
|
||||
"a Full interface does not search"
|
||||
);
|
||||
request(&mut actor, dest, 2, 2);
|
||||
assert!(requested(&mut other, dest), "a gateway requester searches");
|
||||
assert!(
|
||||
actor.inflight_path_requests.contains_key(&dest),
|
||||
"searching"
|
||||
);
|
||||
}
|
||||
|
||||
/// Transport.py:4120-4123@1.6.1 aborts the search of an ingress-limited
|
||||
/// request and leaves it in flight.
|
||||
#[test]
|
||||
fn an_ingress_limited_abort_releases_the_gate() {
|
||||
let mut actor = relay();
|
||||
let _limited = network(&mut actor, 1, InterfaceMode::Gateway);
|
||||
actor.interfaces.get_mut(&1).unwrap().ingress = crate::ingress::IngressController::new();
|
||||
prime_ingress_pr_burst(&mut actor, 1);
|
||||
let _gateway = network(&mut actor, 2, InterfaceMode::Gateway);
|
||||
let mut other = network(&mut actor, 3, InterfaceMode::Full);
|
||||
let dest = [0x52; 16];
|
||||
request(&mut actor, dest, 1, 1);
|
||||
drain_ingress_limited(&mut actor);
|
||||
assert!(
|
||||
!requested(&mut other, dest),
|
||||
"a limited request does not search"
|
||||
);
|
||||
request(&mut actor, dest, 2, 2);
|
||||
assert!(requested(&mut other, dest), "a gateway requester searches");
|
||||
}
|
||||
|
||||
/// A requester that cannot be admitted starts no search (RNS-D0133 (2)), so
|
||||
/// nothing is pending.
|
||||
#[test]
|
||||
fn an_unadmitted_requester_releases_the_gate() {
|
||||
let mut actor = relay();
|
||||
let _inbound_only = network(&mut actor, 1, InterfaceMode::Gateway);
|
||||
actor.interfaces.get_mut(&1).unwrap().direction.outbound = false;
|
||||
let _gateway = network(&mut actor, 2, InterfaceMode::Gateway);
|
||||
let mut other = network(&mut actor, 3, InterfaceMode::Full);
|
||||
let dest = [0x53; 16];
|
||||
request(&mut actor, dest, 1, 1);
|
||||
assert!(!requested(&mut other, dest));
|
||||
request(&mut actor, dest, 2, 2);
|
||||
assert!(requested(&mut other, dest), "a gateway requester searches");
|
||||
}
|
||||
|
||||
/// Transport.py:4038@1.6.1 returns before the pop when the cached announce
|
||||
/// does not unpack, so a repaired cache went unused while the gate held.
|
||||
#[test]
|
||||
fn an_unreadable_cached_announce_releases_the_gate() {
|
||||
let mut actor = relay();
|
||||
let mut requester = network(&mut actor, 1, InterfaceMode::Gateway);
|
||||
let _route = network(&mut actor, 2, InterfaceMode::Full);
|
||||
let (dest, raw) = known_path(&mut actor, "unreadable", |raw| raw[1] = PATHFINDER_M);
|
||||
for tag in [1, 2] {
|
||||
request(&mut actor, dest, tag, 1);
|
||||
assert!(actor.announce_table.get(&dest).is_none());
|
||||
}
|
||||
let dir = actor.storage_dir.clone().unwrap();
|
||||
crate::store::seed_cached_announce(&dir, &cache_key(&raw), &raw, None).unwrap();
|
||||
request(&mut actor, dest, 3, 1);
|
||||
actor.flush_pending_announces();
|
||||
assert!(answered(&mut requester, dest), "answered once readable");
|
||||
assert!(!actor.discovery_path_requests.contains_key(&dest));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Transport.py batches every request for an in-flight destination
|
||||
/// (:2244-2259@1.6.1), so a local client waited for a new announce although
|
||||
/// the shared instance held the path. The gate is held here by a network
|
||||
/// request that a leaf only forwards to its local clients (:4166-4177), or
|
||||
/// one a relay has deferred behind an ingress burst.
|
||||
#[test]
|
||||
fn a_local_client_is_answered_from_the_table_behind_a_network_request() {
|
||||
for transport in [false, true] {
|
||||
let mut actor = relay();
|
||||
actor.is_transport_enabled = transport;
|
||||
let mut client = network(&mut actor, 1, InterfaceMode::Full);
|
||||
actor.interfaces.get_mut(&1).unwrap().role = InterfaceRole::LocalClient;
|
||||
let _network = network(&mut actor, 2, InterfaceMode::Full);
|
||||
let (dest, _) = known_path(&mut actor, &format!("local_client_{transport}"), |_| {});
|
||||
if transport {
|
||||
actor.interfaces.get_mut(&2).unwrap().ingress =
|
||||
crate::ingress::IngressController::new();
|
||||
prime_ingress_pr_burst(&mut actor, 2);
|
||||
}
|
||||
request(&mut actor, dest, 1, 2);
|
||||
assert_eq!(
|
||||
requested(&mut client, dest),
|
||||
!transport,
|
||||
"a leaf forwards it to local clients"
|
||||
);
|
||||
assert!(actor.inflight_path_requests.contains_key(&dest));
|
||||
|
||||
request(&mut actor, dest, 2, 1);
|
||||
actor.flush_pending_announces();
|
||||
assert!(answered(&mut client, dest), "transport={transport}");
|
||||
assert!(!actor.inflight_path_requests.contains_key(&dest));
|
||||
let _ = std::fs::remove_dir_all(actor.storage_dir.clone().unwrap());
|
||||
}
|
||||
}
|
||||
@@ -218,6 +218,7 @@ async fn blocked_interface_rediscovery_shares_one_tag() {
|
||||
receiving_owner: None,
|
||||
requested_mode: 0,
|
||||
accepted_mtu_ceiling: 500,
|
||||
traffic: 0,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Path-table lifetime against upstream RNS 1.6.0: never-used linger on a
|
||||
//! leaf and a transport node, the never-used pool cap, traffic marking use
|
||||
//! Path-table lifetime against upstream RNS 1.6.1: never-used linger on a
|
||||
//! leaf and a transport node, instance-local (0-hop) paths, the hop limiter,
|
||||
//! the never-used pool cap and its used-count scaling, traffic marking use
|
||||
//! without renewing a path, and rediscovery after a local Link that never
|
||||
//! established.
|
||||
//!
|
||||
@@ -17,7 +18,7 @@ fn golden() -> Value {
|
||||
"../../../tests/fixtures/path_table_lifecycle/path_table_lifecycle.json"
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(v["provenance"]["version"], "1.6.0");
|
||||
assert_eq!(v["provenance"]["version"], "1.6.1");
|
||||
v
|
||||
}
|
||||
|
||||
@@ -99,12 +100,14 @@ async fn linger_case(case: &Value) {
|
||||
ids.insert(kind, i as u64 + 1);
|
||||
keep.push(rx);
|
||||
}
|
||||
// An interface Transport no longer has.
|
||||
ids.insert("gone", 99);
|
||||
let t = now();
|
||||
let entries = case["entries"].as_array().unwrap();
|
||||
for (i, e) in entries.iter().enumerate() {
|
||||
let mut p = PathEntry::new(
|
||||
None,
|
||||
1,
|
||||
e["hops"].as_u64().unwrap() as u8,
|
||||
ids[e["iface"].as_str().unwrap()],
|
||||
InterfaceMode::Full,
|
||||
);
|
||||
@@ -118,7 +121,7 @@ async fn linger_case(case: &Value) {
|
||||
assert_eq!(
|
||||
live.contains_key(&h16(i as u64 + 1)),
|
||||
e["survives"].as_bool().unwrap(),
|
||||
"transport={transport} {}: upstream cull (Transport.py:1118-1160@1.6.0)",
|
||||
"transport={transport} {}: upstream cull (Transport.py:1180-1220@1.6.1)",
|
||||
e["label"]
|
||||
);
|
||||
}
|
||||
@@ -174,16 +177,86 @@ async fn never_used_pool_is_culled_to_the_upstream_target() {
|
||||
.iter()
|
||||
.map(|v| v.as_u64().unwrap())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
removed, want,
|
||||
"PATH_POOL_UNUSED_TARGET cull (Transport.py:1150-1156@1.6.0)"
|
||||
);
|
||||
assert_eq!(removed, want, "pool cull (Transport.py:1220-1228@1.6.1)");
|
||||
assert_eq!(
|
||||
(0..field("used_count")).all(|j| live.contains_key(&h16(count + j + 1))),
|
||||
c["used_survive"].as_bool().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn paths_beyond_the_hop_limiter_are_culled() {
|
||||
let g = golden();
|
||||
let c = &g["hop_limit"];
|
||||
let (mut actor, tx) = TransportActor::new();
|
||||
tx.try_send(TransportMessage::SetTransportEnabled { enabled: true })
|
||||
.unwrap();
|
||||
tx.try_send(TransportMessage::SetFilterPolicy {
|
||||
policy: crate::destination_filter::FilterPolicy {
|
||||
hop_limiter: c["hop_limiter"].as_u64().unwrap() as u8,
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.unwrap();
|
||||
let (entry, _rx) = iface("a", 10_000_000, InterfaceMode::Full);
|
||||
tx.try_send(TransportMessage::RegisterInterface { id: 1, entry })
|
||||
.unwrap();
|
||||
let t = now();
|
||||
let entries = c["entries"].as_array().unwrap();
|
||||
for (i, e) in entries.iter().enumerate() {
|
||||
let hops = e["hops"].as_u64().unwrap() as u8;
|
||||
let mut p = PathEntry::new(None, hops, 1, InterfaceMode::Full);
|
||||
p.timestamp = t - 30.0;
|
||||
p.used = t - 1.0;
|
||||
actor.path_table.insert(h16(i as u64 + 1), p);
|
||||
}
|
||||
let live = run(actor, &tx).await;
|
||||
for (i, e) in entries.iter().enumerate() {
|
||||
assert_eq!(
|
||||
live.contains_key(&h16(i as u64 + 1)),
|
||||
e["survives"].as_bool().unwrap(),
|
||||
"hops {} (Transport.py:1216-1219@1.6.1)",
|
||||
e["hops"]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn never_used_pool_target_shrinks_as_used_paths_grow() {
|
||||
let g = golden();
|
||||
for c in g["pool_scaling"].as_array().unwrap() {
|
||||
let (mut actor, tx) = TransportActor::new();
|
||||
tx.try_send(TransportMessage::SetTransportEnabled { enabled: true })
|
||||
.unwrap();
|
||||
actor.path_pool_last_checked = 0.0;
|
||||
let (entry, _rx) = iface("a", 10_000_000, InterfaceMode::Full);
|
||||
tx.try_send(TransportMessage::RegisterInterface { id: 1, entry })
|
||||
.unwrap();
|
||||
let t = now();
|
||||
let (unused, used) = (c["unused"].as_u64().unwrap(), c["used"].as_u64().unwrap());
|
||||
for i in 0..unused {
|
||||
let mut p = PathEntry::new(None, 1, 1, InterfaceMode::Full);
|
||||
p.timestamp = t - 30.0;
|
||||
p.expires = t + 3600.0 + i as f64;
|
||||
actor.path_table.insert(h16(i + 1), p);
|
||||
}
|
||||
for j in 0..used {
|
||||
let mut p = PathEntry::new(None, 1, 1, InterfaceMode::Full);
|
||||
p.timestamp = t - 30.0;
|
||||
p.expires = t + 60.0;
|
||||
p.used = t - 1.0;
|
||||
actor.path_table.insert(h16(unused + j + 1), p);
|
||||
}
|
||||
let live = run(actor, &tx).await;
|
||||
let got = serde_json::json!({
|
||||
"unused": unused, "used": used,
|
||||
"removed": (0..unused).filter(|i| !live.contains_key(&h16(i + 1))).count(),
|
||||
"used_survive": (0..used).all(|j| live.contains_key(&h16(unused + j + 1))),
|
||||
});
|
||||
assert_eq!(&got, c, "pool target (Transport.py:1220-1222@1.6.1)");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn outbound_traffic_marks_use_without_renewing_the_path() {
|
||||
let g = golden();
|
||||
@@ -224,7 +297,7 @@ async fn outbound_traffic_marks_use_without_renewing_the_path() {
|
||||
"timestamp_unchanged": e.timestamp == ts0, "expires_unchanged": e.expires == exp0,
|
||||
"used_is_send_time": e.used >= before,
|
||||
});
|
||||
assert_eq!(&got, case, "Transport.py:1618@1.6.0");
|
||||
assert_eq!(&got, case, "Transport.py:1618@1.6.1");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,7 +318,8 @@ async fn link_never_established_expires_the_path_and_rediscovers_as_upstream() {
|
||||
.unwrap();
|
||||
let dest = h16(7);
|
||||
let t = now();
|
||||
let mut p = PathEntry::new(None, 1, 1, InterfaceMode::Full);
|
||||
let hops = case["hops"].as_u64().unwrap() as u8;
|
||||
let mut p = PathEntry::new(None, hops, 1, InterfaceMode::Full);
|
||||
p.timestamp = t - 10.0;
|
||||
p.used = t - 1.0;
|
||||
actor.path_table.insert(dest, p);
|
||||
@@ -311,10 +385,10 @@ async fn link_never_established_expires_the_path_and_rediscovers_as_upstream() {
|
||||
}
|
||||
let got = serde_json::json!({
|
||||
"transport_enabled": case["transport_enabled"], "shared_client": case["shared_client"],
|
||||
"last_request_age_s": case["last_request_age_s"],
|
||||
"last_request_age_s": case["last_request_age_s"], "hops": hops,
|
||||
"path_kept": path_table(&tx).await.contains_key(&dest),
|
||||
"rediscovery_queued": requested,
|
||||
});
|
||||
assert_eq!(&got, case, "Transport.py:839-866@1.6.0");
|
||||
assert_eq!(&got, case, "Transport.py:896-918@1.6.1");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//! Per-interface hop limits and the path-table getter (Transport.py 1.6.1).
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The interface's limit applies before the instance-wide one, on wire hops;
|
||||
/// 0 is off, as `None` is.
|
||||
#[test]
|
||||
fn interface_hop_limiter_drops_at_its_limit() {
|
||||
let (mut actor, _tx) = TransportActor::new();
|
||||
let mut keep = Vec::new();
|
||||
for (id, limit) in [(1, Some(1)), (2, Some(0)), (3, None)] {
|
||||
let (mut entry, rx) = make_test_interface(&format!("iface{id}"));
|
||||
entry.hop_limiter = limit;
|
||||
actor.interfaces.insert(id, entry);
|
||||
keep.push(rx);
|
||||
}
|
||||
let mut learned = Vec::new();
|
||||
for id in 1..=3 {
|
||||
for hops in [0, 1] {
|
||||
let (raw, dest) = make_valid_announce(&format!("hoplimit.i{id}.h{hops}"), hops);
|
||||
actor.on_inbound(InboundPacket {
|
||||
raw,
|
||||
interface_id: id,
|
||||
rssi: None,
|
||||
snr: None,
|
||||
q: None,
|
||||
});
|
||||
learned.push(actor.path_table.has_path(&dest));
|
||||
}
|
||||
}
|
||||
assert_eq!(learned, [true, false, true, true, true, true]);
|
||||
}
|
||||
|
||||
/// Reticulum.py 1.6.1 (c90a5d58, 41260ea1): each path names its interface's
|
||||
/// hash, as interface stats do, and its state.
|
||||
#[test]
|
||||
fn path_table_entries_carry_interface_hash_and_state() {
|
||||
let (mut actor, _tx) = TransportActor::new();
|
||||
let (mut named, _named_rx) = make_test_interface("radio");
|
||||
named.inspection = Some(
|
||||
crate::messages::InterfaceInspectionSource::new(Default::default).with_identity(
|
||||
crate::messages::InterfaceIdentity::new(
|
||||
"TCPInterface[radio/127.0.0.1:4242]",
|
||||
"radio",
|
||||
"TCPInterface",
|
||||
),
|
||||
),
|
||||
);
|
||||
actor.interfaces.insert(1, named);
|
||||
let (plain, _plain_rx) = make_test_interface("plain");
|
||||
actor.interfaces.insert(2, plain);
|
||||
let (a, b) = ([0x61; 16], [0x62; 16]);
|
||||
actor
|
||||
.path_table
|
||||
.insert(a, PathEntry::new(None, 1, 1, InterfaceMode::Full));
|
||||
actor
|
||||
.path_table
|
||||
.insert(b, PathEntry::new(None, 1, 2, InterfaceMode::Full));
|
||||
actor.mark_path_responsive(&a);
|
||||
|
||||
let TransportQueryResponse::PathTable(entries) =
|
||||
actor.handle_query(TransportQuery::GetPathTable)
|
||||
else {
|
||||
panic!("expected a path table");
|
||||
};
|
||||
let entry = |hash| entries.iter().find(|e| e.hash == hash).unwrap();
|
||||
assert_eq!(
|
||||
entry(a).interface_hash,
|
||||
rns_crypto::sha::sha256(b"TCPInterface[radio/127.0.0.1:4242]")
|
||||
);
|
||||
assert_eq!(entry(a).state, PathState::Responsive);
|
||||
assert_eq!(entry(b).interface_hash, rns_crypto::sha::sha256(b"plain"));
|
||||
assert_eq!(entry(b).state, PathState::Unknown);
|
||||
}
|
||||
@@ -181,3 +181,72 @@ fn a_ratchet_heard_again_after_a_restart_keeps_its_stored_receive_time() {
|
||||
restarted.on_shutdown();
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Restart with `prepare` run after the snapshot is staged and before the
|
||||
/// interface binds it, as a blackhole list loaded late would be.
|
||||
fn restarted_with(
|
||||
dir: &std::path::Path,
|
||||
prepare: impl FnOnce(&mut TransportActor),
|
||||
) -> TransportActor {
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
actor.initialize_storage(dir.to_path_buf());
|
||||
prepare(&mut actor);
|
||||
let (mut entry, _rx) = make_test_interface("uplink");
|
||||
entry.ingress = crate::ingress::IngressController::disabled();
|
||||
actor.handle_message(TransportMessage::RegisterInterface { id: 1, entry });
|
||||
actor
|
||||
}
|
||||
|
||||
/// Save paths to three destinations, the third's identity to be blackholed.
|
||||
fn three_saved_paths(dir: &std::path::Path) -> ([[u8; 16]; 3], [u8; 16]) {
|
||||
let now = crate::now_f64() as u64;
|
||||
let names = ["restored.kept", "restored.spam", "restored.blackholed"];
|
||||
let identities: [_; 3] = std::array::from_fn(|_| rns_identity::identity::Identity::new());
|
||||
let mut before = node(dir);
|
||||
let dests = std::array::from_fn(|i| {
|
||||
let (raw, dest) = announce(&identities[i], names[i], None, now, PacketContext::None);
|
||||
inbound(&mut before, &raw);
|
||||
assert!(before.path_table.has_path(&dest), "{}", names[i]);
|
||||
dest
|
||||
});
|
||||
before.on_shutdown();
|
||||
(dests, identities[2].hash)
|
||||
}
|
||||
|
||||
/// Transport.py 1.6.1 (20e25a9f, 350b7e26): a restored path skips a
|
||||
/// blackholed identity and a filtered destination type; under
|
||||
/// `required_only` only allowed types bind.
|
||||
#[test]
|
||||
fn restored_paths_skip_blackholed_identities_and_filtered_types() {
|
||||
let dir = unique_temp_dir("restored-filtered");
|
||||
let (dests, blackholed) = three_saved_paths(&dir);
|
||||
let mut restarted = restarted_with(&dir, |actor| {
|
||||
actor.handle_message(TransportMessage::SetFilterPolicy {
|
||||
policy: crate::destination_filter::FilterPolicy {
|
||||
ignored_types: vec!["restored.spam".into()],
|
||||
..Default::default()
|
||||
},
|
||||
});
|
||||
actor.blackhole_table.add(blackholed, None);
|
||||
});
|
||||
let bound = dests.map(|dest| restarted.path_table.has_path(&dest));
|
||||
assert_eq!(bound, [true, false, false]);
|
||||
restarted.on_shutdown();
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
|
||||
let dir = unique_temp_dir("restored-required");
|
||||
let (dests, _) = three_saved_paths(&dir);
|
||||
let mut required = restarted_with(&dir, |actor| {
|
||||
actor.handle_message(TransportMessage::SetFilterPolicy {
|
||||
policy: crate::destination_filter::FilterPolicy {
|
||||
required_only: true,
|
||||
allowed_types: vec!["restored.blackholed".into()],
|
||||
..Default::default()
|
||||
},
|
||||
});
|
||||
});
|
||||
let bound = dests.map(|dest| required.path_table.has_path(&dest));
|
||||
assert_eq!(bound, [false, false, true]);
|
||||
required.on_shutdown();
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ use super::*;
|
||||
fn relay() -> TransportActor {
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
actor.is_transport_enabled = true;
|
||||
actor.stamp_policy.stamp_prs = false;
|
||||
actor.transport_identity_hash = Some([0x44; 16]);
|
||||
actor
|
||||
}
|
||||
@@ -106,7 +107,8 @@ fn recursive_timeout_samples_only_known_online_useful_egress_and_stays_bounded()
|
||||
|
||||
#[test]
|
||||
fn recursive_requesters_share_one_fanout_and_response_reaches_same_radio() {
|
||||
for (mode, same_response) in [(InterfaceMode::Full, true), (InterfaceMode::Roaming, false)] {
|
||||
// Transport.py answers every requester, roaming radios included.
|
||||
for mode in [InterfaceMode::Full, InterfaceMode::Roaming] {
|
||||
let start = now_f64();
|
||||
let clock = crate::test_clock::Clock::at(start);
|
||||
let mut actor = relay();
|
||||
@@ -140,11 +142,7 @@ fn recursive_requesters_share_one_fanout_and_response_reaches_same_radio() {
|
||||
assert!(second_rx.try_recv().is_err());
|
||||
inbound(&mut actor, announce.clone(), 2);
|
||||
assert_response(first_rx.try_recv().unwrap(), dest);
|
||||
if same_response {
|
||||
assert_response(second_rx.try_recv().unwrap(), dest);
|
||||
} else {
|
||||
assert!(second_rx.try_recv().is_err());
|
||||
}
|
||||
assert_response(second_rx.try_recv().unwrap(), dest);
|
||||
inbound(&mut actor, announce, 2);
|
||||
assert!(first_rx.try_recv().is_err() && second_rx.try_recv().is_err());
|
||||
assert!(actor.discovery_path_requests.is_empty());
|
||||
@@ -523,6 +521,7 @@ fn transit_table_capacity_and_driver_refusal_do_not_create_untracked_forwarding(
|
||||
.map(|entry| entry.owner.clone()),
|
||||
requested_mode: 1,
|
||||
accepted_mtu_ceiling: 500,
|
||||
traffic: 0,
|
||||
|
||||
timestamp: now_f64(),
|
||||
next_hop: None,
|
||||
|
||||
@@ -63,10 +63,93 @@ fn cache_announce(dir: &std::path::Path, raw: &[u8], interface: Option<&str>) ->
|
||||
packet_hash
|
||||
}
|
||||
|
||||
/// A hub-side child of a TCP listener, which Python lets take a synthesis.
|
||||
fn attach_child(actor: &mut TransportActor, id: InterfaceId, name: &str) -> mpsc::Receiver<Bytes> {
|
||||
attach_class(actor, id, name, "TCPClientInterface")
|
||||
}
|
||||
|
||||
fn attach_class(
|
||||
actor: &mut TransportActor,
|
||||
id: InterfaceId,
|
||||
name: &str,
|
||||
class: &str,
|
||||
) -> mpsc::Receiver<Bytes> {
|
||||
let (mut entry, rx) = make_test_interface(name);
|
||||
entry.inspection = Some(InterfaceInspectionSource::identified(
|
||||
crate::messages::InterfaceIdentity::new(name, name, class),
|
||||
));
|
||||
actor.interfaces.insert(id, entry);
|
||||
rx
|
||||
}
|
||||
|
||||
/// A node whose wire identity can sign, with a control channel for detaches.
|
||||
fn signing(
|
||||
mut actor: TransportActor,
|
||||
) -> (
|
||||
TransportActor,
|
||||
Arc<Identity>,
|
||||
mpsc::UnboundedReceiver<crate::messages::InterfaceControl>,
|
||||
) {
|
||||
let identity = Arc::new(Identity::new());
|
||||
actor.transport_identity_hash = Some(identity.hash);
|
||||
actor.handle_message(TransportMessage::SetTunnelIdentity {
|
||||
identity: identity.clone(),
|
||||
});
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
actor.handle_message(TransportMessage::SetInterfaceControl { tx });
|
||||
(actor, identity, rx)
|
||||
}
|
||||
|
||||
fn extended(identity: &Identity, interface: &str) -> (Bytes, [u8; 32]) {
|
||||
let ext = crate::tunnel::TunnelExt::local(true, 8.0, 4.5);
|
||||
let raw = crate::tunnel::build_tunnel_synthesis_packet_with_ext(
|
||||
identity,
|
||||
crate::tunnel::interface_hash(interface),
|
||||
&ext,
|
||||
)
|
||||
.unwrap();
|
||||
let tunnel_id = TunnelSynthesisData::unpack(&raw[rns_wire::constants::HEADER_MINSIZE..])
|
||||
.unwrap()
|
||||
.tunnel_id();
|
||||
(Bytes::from(raw), tunnel_id)
|
||||
}
|
||||
|
||||
/// A PLAIN broadcast to `rnstransport.tunnel.synthesize` carrying `payload`.
|
||||
fn synthesis_packet(payload: &[u8]) -> Bytes {
|
||||
let mut raw = PacketHeader {
|
||||
flags: PacketFlags {
|
||||
header_type: HeaderType::Header1,
|
||||
context_flag: false,
|
||||
transport_type: TransportType::Broadcast,
|
||||
destination_type: DestinationType::Plain,
|
||||
packet_type: PacketType::Data,
|
||||
},
|
||||
hops: 0,
|
||||
transport_id: None,
|
||||
destination_hash: named_hash("rnstransport.tunnel.synthesize"),
|
||||
context: PacketContext::None,
|
||||
}
|
||||
.pack();
|
||||
raw.extend_from_slice(payload);
|
||||
Bytes::from(raw)
|
||||
}
|
||||
|
||||
/// The synthesis in a frame the actor sent, if it is one.
|
||||
fn sent_synthesis(frame: &[u8]) -> Option<TunnelSynthesisData> {
|
||||
let (header, offset) = PacketHeader::unpack(frame).ok()?;
|
||||
(header.destination_hash == named_hash("rnstransport.tunnel.synthesize"))
|
||||
.then(|| TunnelSynthesisData::unpack(&frame[offset..]))
|
||||
.flatten()
|
||||
}
|
||||
|
||||
fn violations(actor: &TransportActor, id: InterfaceId) -> u64 {
|
||||
actor.interfaces[&id].protocol_violations
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_synthesis_installs_a_tunnel_that_collects_announces() {
|
||||
let mut actor = hub();
|
||||
let _rx = attach(&mut actor, 1, "hub/client_1");
|
||||
let _rx = attach_child(&mut actor, 1, "hub/client_1");
|
||||
let (raw, tunnel_id) = synthesis(&Identity::new(), "TCPInterface[Uplink/127.0.0.1:4242]");
|
||||
inbound(&mut actor, raw, 1);
|
||||
assert!(
|
||||
@@ -82,62 +165,318 @@ fn valid_synthesis_installs_a_tunnel_that_collects_announces() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Python 1.6.1 runs the handler on its own verdict table; each case is
|
||||
/// signed here and must hash to Python's payload (Transport.py:3208-3297).
|
||||
#[test]
|
||||
fn synthesis_with_a_bad_signature_or_extra_bytes_installs_nothing() {
|
||||
let mut actor = hub();
|
||||
let _rx: Vec<_> = (1..=3)
|
||||
.map(|id| attach(&mut actor, id, &format!("hub/client_{id}")))
|
||||
.collect();
|
||||
let (valid, valid_id) = synthesis(&Identity::new(), "uplink-a");
|
||||
inbound(&mut actor, valid, 1);
|
||||
assert!(
|
||||
actor.tunnel_table.get(&valid_id).is_some(),
|
||||
"control: a valid synthesis installs"
|
||||
);
|
||||
fn the_handler_reaches_python_verdicts() {
|
||||
use crate::tunnel::python_vectors::{HANDLER_CASES, identity, payload};
|
||||
for (name, verdict, ext, digest) in HANDLER_CASES {
|
||||
let data = payload(name, ext);
|
||||
assert_eq!(
|
||||
hex::encode(rns_crypto::sha::sha256(&data)),
|
||||
*digest,
|
||||
"{name}: signed as Python signs it"
|
||||
);
|
||||
let (mut actor, _, mut control) = signing(hub());
|
||||
let mut rx = attach_child(&mut actor, 1, "hub/client_1");
|
||||
inbound(&mut actor, synthesis_packet(&data), 1);
|
||||
|
||||
let (raw, tampered_id) = synthesis(&Identity::new(), "uplink-b");
|
||||
let mut tampered = raw.to_vec();
|
||||
*tampered.last_mut().unwrap() ^= 0x01;
|
||||
inbound(&mut actor, Bytes::from(tampered), 2);
|
||||
assert!(
|
||||
actor.tunnel_table.get(&tampered_id).is_none(),
|
||||
"a flipped signature bit is rejected"
|
||||
);
|
||||
|
||||
let (raw, trailing_id) = synthesis(&Identity::new(), "uplink-c");
|
||||
let mut trailing = raw.to_vec();
|
||||
trailing.push(0);
|
||||
inbound(&mut actor, Bytes::from(trailing), 3);
|
||||
assert!(
|
||||
actor.tunnel_table.get(&trailing_id).is_none(),
|
||||
"a payload longer than 176 bytes is rejected (Transport.py:2791)"
|
||||
);
|
||||
assert_eq!(actor.tunnel_table.len(), 1);
|
||||
let tunnel_id = TunnelSynthesisData::unpack(&data[..176])
|
||||
.unwrap()
|
||||
.tunnel_id();
|
||||
let mut outcome = Vec::new();
|
||||
if rx
|
||||
.try_recv()
|
||||
.ok()
|
||||
.as_deref()
|
||||
.and_then(sent_synthesis)
|
||||
.is_some()
|
||||
{
|
||||
outcome.push("reply");
|
||||
}
|
||||
if actor.tunnel_table.get(&tunnel_id).is_some() {
|
||||
outcome.push("tunnel");
|
||||
}
|
||||
if control.try_recv().is_ok() {
|
||||
outcome.push("detach");
|
||||
}
|
||||
if actor
|
||||
.interfaces
|
||||
.get(&1)
|
||||
.is_some_and(|entry| entry.protocol_violations > 0)
|
||||
{
|
||||
outcome.push("violation");
|
||||
}
|
||||
if actor
|
||||
.interfaces
|
||||
.get(&1)
|
||||
.is_some_and(|entry| entry.tunnel.remote_transport == Some(identity().hash))
|
||||
{
|
||||
outcome.push("remote");
|
||||
}
|
||||
let expected = match *name {
|
||||
// Lead decision: costs may be ints.
|
||||
"cost_int" => "reply,tunnel,remote",
|
||||
_ => verdict,
|
||||
};
|
||||
assert_eq!(outcome.join(","), expected, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// UDP, RNode, serial, KISS, pipe, AX.25, Auto and local interfaces never
|
||||
/// take a synthesis (Transport.py:3211-3212).
|
||||
#[test]
|
||||
fn the_newer_synthesis_on_an_interface_takes_its_later_announces() {
|
||||
fn an_interface_without_tunnels_ignores_a_synthesis() {
|
||||
let mut actor = hub();
|
||||
let _rx = attach(&mut actor, 1, "hub/client_1");
|
||||
let (older, older_id) = synthesis(&Identity::new(), "uplink");
|
||||
let (newer, newer_id) = synthesis(&Identity::new(), "uplink");
|
||||
inbound(&mut actor, older, 1);
|
||||
inbound(&mut actor, newer, 1);
|
||||
assert!(
|
||||
actor.tunnel_table.get(&older_id).is_some() && actor.tunnel_table.get(&newer_id).is_some(),
|
||||
"both syntheses install"
|
||||
);
|
||||
let _rx = attach_class(&mut actor, 1, "udp", "UDPInterface");
|
||||
let (raw, tunnel_id) = extended(&Identity::new(), "uplink");
|
||||
inbound(&mut actor, raw, 1);
|
||||
assert!(actor.tunnel_table.get(&tunnel_id).is_none());
|
||||
assert_eq!(violations(&actor, 1), 0, "ignored silently");
|
||||
assert!(actor.interfaces[&1].tunnel.remote_transport.is_none());
|
||||
}
|
||||
|
||||
let (announce, dest) = make_valid_announce("tunnel.newer", 0);
|
||||
/// One synthesis per connection: a second is a violation whether or not the
|
||||
/// first established a tunnel, and a malformed first one uses up the chance.
|
||||
#[test]
|
||||
fn a_connection_takes_one_synthesis() {
|
||||
let mut actor = hub();
|
||||
let _rx: Vec<_> = (1..=2)
|
||||
.map(|id| attach_child(&mut actor, id, &format!("hub/client_{id}")))
|
||||
.collect();
|
||||
let (first, first_id) = synthesis(&Identity::new(), "uplink");
|
||||
let (second, second_id) = synthesis(&Identity::new(), "uplink");
|
||||
inbound(&mut actor, first, 1);
|
||||
inbound(&mut actor, second, 1);
|
||||
assert!(actor.tunnel_table.get(&first_id).is_some());
|
||||
assert!(actor.tunnel_table.get(&second_id).is_none());
|
||||
assert_eq!(violations(&actor, 1), 1, "already established");
|
||||
|
||||
inbound(&mut actor, synthesis_packet(&[0; 175]), 2);
|
||||
assert_eq!(violations(&actor, 2), 1, "undersize");
|
||||
let (valid, valid_id) = synthesis(&Identity::new(), "uplink-b");
|
||||
inbound(&mut actor, valid, 2);
|
||||
assert_eq!(violations(&actor, 2), 2, "the chance is spent");
|
||||
assert!(actor.tunnel_table.get(&valid_id).is_none());
|
||||
}
|
||||
|
||||
/// A bad signature tears the interface down (Transport.py:3245-3248); with no
|
||||
/// one to ask, the actor drops it itself.
|
||||
#[test]
|
||||
fn a_bad_signature_tears_the_interface_down() {
|
||||
let (mut actor, _, mut control) = signing(hub());
|
||||
let _rx = attach_child(&mut actor, 1, "hub/client_1");
|
||||
let (raw, tunnel_id) = extended(&Identity::new(), "uplink");
|
||||
let mut tampered = raw.to_vec();
|
||||
*tampered.last_mut().unwrap() ^= 0x01;
|
||||
inbound(&mut actor, Bytes::from(tampered), 1);
|
||||
assert_eq!(
|
||||
control.try_recv().unwrap(),
|
||||
crate::messages::InterfaceControl::Detach {
|
||||
interface_id: 1,
|
||||
reason: crate::messages::DetachReason::InvalidSynthesis,
|
||||
}
|
||||
);
|
||||
assert!(actor.tunnel_table.get(&tunnel_id).is_none());
|
||||
|
||||
let (announce, dest) = make_valid_announce("tunnel.detaching", 0);
|
||||
inbound(&mut actor, announce, 1);
|
||||
assert!(
|
||||
carries(&actor, &newer_id, &dest),
|
||||
"the last synthesis owns the interface (Transport.py:2827, :2834)"
|
||||
!actor.path_table.has_path(&dest),
|
||||
"frames from a detaching interface are dropped"
|
||||
);
|
||||
actor.deregister_interface(1);
|
||||
assert!(!actor.is_detaching(1));
|
||||
|
||||
let mut alone = hub();
|
||||
let _rx = attach_child(&mut alone, 2, "hub/client_2");
|
||||
let (raw, _) = synthesis(&Identity::new(), "uplink");
|
||||
let mut tampered = raw.to_vec();
|
||||
tampered[rns_wire::constants::HEADER_MINSIZE + 120] ^= 0x01;
|
||||
inbound(&mut alone, Bytes::from(tampered), 2);
|
||||
assert!(!alone.interfaces.contains_key(&2));
|
||||
}
|
||||
|
||||
/// A blackholed transport node is torn down at its synthesis, and when it is
|
||||
/// blackholed later (Transport.py:3249-3252, :4832-4839).
|
||||
#[test]
|
||||
fn a_blackholed_tunnel_peer_is_torn_down() {
|
||||
let (mut actor, _, mut control) = signing(hub());
|
||||
let _rx: Vec<_> = (1..=3)
|
||||
.map(|id| attach_child(&mut actor, id, &format!("hub/client_{id}")))
|
||||
.collect();
|
||||
let blackholed = Identity::new();
|
||||
actor.blackhole_table.add(blackholed.hash, None);
|
||||
let (raw, tunnel_id) = extended(&blackholed, "uplink");
|
||||
inbound(&mut actor, raw, 1);
|
||||
assert_eq!(
|
||||
control.try_recv().unwrap(),
|
||||
crate::messages::InterfaceControl::Detach {
|
||||
interface_id: 1,
|
||||
reason: crate::messages::DetachReason::BlackholedTransport,
|
||||
}
|
||||
);
|
||||
assert!(actor.tunnel_table.get(&tunnel_id).is_none());
|
||||
|
||||
let (later, other) = (Identity::new(), Identity::new());
|
||||
inbound(&mut actor, extended(&later, "uplink-2").0, 2);
|
||||
inbound(&mut actor, extended(&other, "uplink-3").0, 3);
|
||||
assert!(control.try_recv().is_err());
|
||||
actor.handle_query(crate::messages::TransportQuery::BlackholeIdentity {
|
||||
hash: later.hash,
|
||||
ttl: None,
|
||||
reason: crate::blackhole::BlackholeReason::Manual,
|
||||
reason_label: None,
|
||||
});
|
||||
assert_eq!(
|
||||
control.try_recv().unwrap(),
|
||||
crate::messages::InterfaceControl::Detach {
|
||||
interface_id: 2,
|
||||
reason: crate::messages::DetachReason::BlackholedTransport,
|
||||
}
|
||||
);
|
||||
assert!(control.try_recv().is_err(), "only the blackholed peer");
|
||||
}
|
||||
|
||||
/// A receiver answers an extended synthesis once, signed with its own wire
|
||||
/// identity and with its own costs; a legacy synthesis gets no answer
|
||||
/// (Transport.py:3286).
|
||||
#[test]
|
||||
fn a_receiver_answers_an_extended_synthesis_once() {
|
||||
let (mut actor, hub_identity, _control) = signing(hub());
|
||||
let mut rx = attach_child(&mut actor, 1, "hub/client_1");
|
||||
actor.interfaces.get_mut(&1).unwrap().destination_cost = Some(12.0);
|
||||
let client = Identity::new();
|
||||
let (raw, tunnel_id) = extended(&client, "uplink");
|
||||
inbound(&mut actor, raw, 1);
|
||||
let reply = sent_synthesis(&rx.try_recv().unwrap()).expect("a reverse synthesis");
|
||||
assert!(reply.is_signed());
|
||||
assert_eq!(reply.transport_identity_hash(), hub_identity.hash);
|
||||
assert_eq!(
|
||||
reply.interface_hash,
|
||||
crate::tunnel::interface_hash("hub/client_1")
|
||||
);
|
||||
let info = crate::tunnel::RemoteTransportInfo::decode(&reply.ext).unwrap();
|
||||
assert_eq!(info.implementation, "rsRNS");
|
||||
assert!(info.transport);
|
||||
assert_eq!(info.destination_cost, 12.0);
|
||||
assert_eq!(
|
||||
info.pr_cost,
|
||||
rns_identity::stamps::quantize_cost(15.8).unwrap()
|
||||
);
|
||||
assert!(actor.tunnel_table.get(&tunnel_id).is_some());
|
||||
assert!(rx.try_recv().is_err(), "answered once");
|
||||
|
||||
let stats = interface_stats(&mut actor, 1);
|
||||
assert_eq!(stats.tunnel_id, Some(tunnel_id));
|
||||
assert_eq!(stats.remote_transport_id, Some(client.hash));
|
||||
let remote = stats.remote_transport.expect("the client's extension");
|
||||
assert_eq!(
|
||||
(remote.implementation.as_str(), remote.version.clone()),
|
||||
(
|
||||
"rsRNS",
|
||||
crate::discovery::constants::IMPLEMENTATION_VERSION
|
||||
.split('.')
|
||||
.map(|part| part.parse().unwrap())
|
||||
.collect::<Vec<u64>>()
|
||||
)
|
||||
);
|
||||
assert_eq!((remote.destination_cost, remote.pr_cost), (8.0, 4.5));
|
||||
|
||||
let mut legacy_rx = attach_child(&mut actor, 2, "hub/client_2");
|
||||
inbound(&mut actor, synthesis(&Identity::new(), "uplink").0, 2);
|
||||
assert!(
|
||||
!carries(&actor, &older_id, &dest),
|
||||
"the superseded tunnel takes no new paths"
|
||||
legacy_rx.try_recv().is_err(),
|
||||
"no answer to the legacy form"
|
||||
);
|
||||
let legacy = interface_stats(&mut actor, 2);
|
||||
assert!(legacy.remote_transport_id.is_some() && legacy.remote_transport.is_none());
|
||||
}
|
||||
|
||||
/// An initiator sends the extended form, names its tunnel, records the hub's
|
||||
/// answer without binding a tunnel or answering back, and forgets the hub on
|
||||
/// its next connection (Transport.py:3205, :3290-3292).
|
||||
#[test]
|
||||
fn an_initiator_records_its_hub_without_binding_a_tunnel() {
|
||||
let (mut actor, client_identity, _control) = signing(hub());
|
||||
let name = "TCPInterface[Uplink/127.0.0.1:4242]";
|
||||
let mut rx = attach_class(&mut actor, 1, name, "TCPClientInterface");
|
||||
actor.interfaces.get_mut(&1).unwrap().online =
|
||||
Some(Arc::new(std::sync::atomic::AtomicBool::new(false)));
|
||||
actor.handle_message(TransportMessage::SynthesizeTunnel { interface_id: 1 });
|
||||
let sent = sent_synthesis(&rx.try_recv().unwrap())
|
||||
.expect("queued before the interface reports online");
|
||||
assert!(sent.is_signed());
|
||||
assert_eq!(sent.transport_identity_hash(), client_identity.hash);
|
||||
assert_eq!(sent.interface_hash, crate::tunnel::interface_hash(name));
|
||||
let info = crate::tunnel::RemoteTransportInfo::decode(&sent.ext).unwrap();
|
||||
assert_eq!(
|
||||
(info.destination_cost, info.pr_cost),
|
||||
(23.5, rns_identity::stamps::quantize_cost(15.8).unwrap())
|
||||
);
|
||||
assert_eq!(
|
||||
interface_stats(&mut actor, 1).tunnel_id,
|
||||
Some(sent.tunnel_id())
|
||||
);
|
||||
|
||||
let hub_identity = Identity::new();
|
||||
let (reply, reply_tunnel) =
|
||||
extended(&hub_identity, "TCPInterface[Client on Hub/10.0.0.1:5000]");
|
||||
inbound(&mut actor, reply, 1);
|
||||
assert!(rx.try_recv().is_err(), "an initiator never answers");
|
||||
assert!(actor.tunnel_table.get(&reply_tunnel).is_none());
|
||||
assert!(actor.tunnel_table.is_empty());
|
||||
let stats = interface_stats(&mut actor, 1);
|
||||
assert_eq!(stats.remote_transport_id, Some(hub_identity.hash));
|
||||
assert_eq!(stats.tunnel_id, Some(sent.tunnel_id()));
|
||||
|
||||
actor.handle_message(TransportMessage::SynthesizeTunnel { interface_id: 1 });
|
||||
assert!(
|
||||
rx.try_recv()
|
||||
.ok()
|
||||
.as_deref()
|
||||
.and_then(sent_synthesis)
|
||||
.is_some()
|
||||
);
|
||||
assert!(interface_stats(&mut actor, 1).remote_transport_id.is_none());
|
||||
let (again, _) = extended(&hub_identity, "TCPInterface[Client on Hub/10.0.0.1:5001]");
|
||||
inbound(&mut actor, again, 1);
|
||||
assert_eq!(
|
||||
violations(&actor, 1),
|
||||
0,
|
||||
"a new connection takes a new answer"
|
||||
);
|
||||
assert_eq!(
|
||||
interface_stats(&mut actor, 1).remote_transport_id,
|
||||
Some(hub_identity.hash)
|
||||
);
|
||||
}
|
||||
|
||||
/// Python skips a synthesis without `Transport.identity`; the actor also
|
||||
/// refuses to sign with an identity that is not its visible one.
|
||||
#[test]
|
||||
fn no_synthesis_without_the_wire_identity() {
|
||||
let mut actor = hub();
|
||||
let mut rx = attach_child(&mut actor, 1, "uplink");
|
||||
actor.handle_message(TransportMessage::SynthesizeTunnel { interface_id: 1 });
|
||||
assert!(rx.try_recv().is_err());
|
||||
actor.handle_message(TransportMessage::SetTunnelIdentity {
|
||||
identity: Arc::new(Identity::new()),
|
||||
});
|
||||
actor.handle_message(TransportMessage::SynthesizeTunnel { interface_id: 1 });
|
||||
assert!(rx.try_recv().is_err(), "its hash is not the transport hash");
|
||||
}
|
||||
|
||||
fn interface_stats(
|
||||
actor: &mut TransportActor,
|
||||
id: InterfaceId,
|
||||
) -> crate::messages::InterfaceStatRpcEntry {
|
||||
let crate::messages::TransportQueryResponse::InterfaceStats(entries) =
|
||||
actor.handle_query(crate::messages::TransportQuery::GetInterfaceStats)
|
||||
else {
|
||||
panic!("unexpected interface stats response");
|
||||
};
|
||||
entries.into_iter().find(|entry| entry.id == id).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -327,6 +666,65 @@ fn tunnels_without_an_interface_survive_a_reload() {
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// Python 1.6.1 caps a loaded tunnel's expiry at the reconnect window
|
||||
/// (Transport.py:636-637).
|
||||
#[test]
|
||||
fn loaded_tunnels_expire_within_the_reconnect_window() {
|
||||
let dir = unique_temp_dir("tunnel-reconnect-window");
|
||||
let now = now_f64();
|
||||
let window = crate::constants::TUNNEL_RECONNECT_WINDOW as f64;
|
||||
let path = |dest: u8| PersistedTunnelPath {
|
||||
used: None,
|
||||
destination_hash: vec![dest; 16],
|
||||
next_hop: None,
|
||||
hops: 1,
|
||||
expires: now + 600.0,
|
||||
timestamp: now,
|
||||
random_blobs: vec![vec![0x11; 10]],
|
||||
packet_hash: Some(vec![0x41; 32]),
|
||||
};
|
||||
let entry = |tunnel: u8, expires: f64| PersistedTunnelEntry {
|
||||
tunnel_id: vec![tunnel; 32],
|
||||
interface_id: 3,
|
||||
expires,
|
||||
paths: vec![path(tunnel)],
|
||||
interface_name: None,
|
||||
interface_hash: None,
|
||||
};
|
||||
let table = PersistedTunnelTable {
|
||||
entries: vec![
|
||||
entry(0x01, now + crate::constants::TUNNEL_TIMEOUT as f64),
|
||||
entry(0x02, now + 120.0),
|
||||
],
|
||||
version: PersistedTunnelTable::CURRENT_VERSION,
|
||||
};
|
||||
std::fs::write(
|
||||
dir.join("tunnel_table.msgpack"),
|
||||
rmp_serde::to_vec(&table).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut reader = hub();
|
||||
reader.handle_message(TransportMessage::SetStoragePaths {
|
||||
storage_dir: dir.clone(),
|
||||
role: crate::actor::StorageRole::Owner,
|
||||
done: None,
|
||||
});
|
||||
let long = reader.tunnel_table.get(&[0x01; 32]).unwrap().expires;
|
||||
assert!(
|
||||
long <= now_f64() + window && long > now + window - 5.0,
|
||||
"an eight-hour expiry loads capped at the window: {}",
|
||||
long - now
|
||||
);
|
||||
assert_eq!(
|
||||
reader.tunnel_table.get(&[0x02; 32]).unwrap().expires,
|
||||
now + 120.0,
|
||||
"a sooner expiry is kept"
|
||||
);
|
||||
stop(reader);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_sidecar_tunnels_without_an_interface_survive_a_reload() {
|
||||
let dir = unique_temp_dir("sidecar-tunnel");
|
||||
@@ -540,8 +938,8 @@ fn exempt_contexts_bypass_the_plain_hop_filter() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_owner_ingress_bypasses_the_plain_hop_filter() {
|
||||
#[tokio::test]
|
||||
async fn shared_owner_ingress_bypasses_the_plain_hop_filter() {
|
||||
let (mut actor, _) = TransportActor::new();
|
||||
actor.is_shared_instance = true;
|
||||
let (mut entry, _rx) = make_test_interface("SharedInstanceClient");
|
||||
@@ -558,3 +956,22 @@ fn shared_owner_ingress_bypasses_the_plain_hop_filter() {
|
||||
"the shared instance already filtered this packet (Transport.py:1627)"
|
||||
);
|
||||
}
|
||||
|
||||
/// The answer leaves through transport, so it carries the interface's IFAC
|
||||
/// (Transport.py `packet.send()`).
|
||||
#[test]
|
||||
fn a_reverse_synthesis_carries_ifac() {
|
||||
let (mut actor, _, _control) = signing(hub());
|
||||
let mut rx = attach_child(&mut actor, 1, "hub/client_1");
|
||||
let key = rns_identity::ifac::IfacKey::derive(Some("tunnels"), Some("ifac")).unwrap();
|
||||
let entry = actor.interfaces.get_mut(&1).unwrap();
|
||||
entry.ifac_key = Some(key.clone());
|
||||
entry.ifac_size = 16;
|
||||
let (raw, tunnel_id) = extended(&Identity::new(), "uplink");
|
||||
let masked = crate::ifac::try_ifac_sign(&raw, &key, 16).unwrap();
|
||||
inbound(&mut actor, Bytes::from(masked), 1);
|
||||
assert!(actor.tunnel_table.get(&tunnel_id).is_some());
|
||||
let reply = rx.try_recv().unwrap();
|
||||
let clear = crate::ifac::ifac_verify(&reply, &key, 16).expect("IFAC-valid");
|
||||
assert!(sent_synthesis(&clear).is_some_and(|synthesis| synthesis.is_signed()));
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
use super::*;
|
||||
use crate::messages::{DetachReason, InterfaceControl};
|
||||
use crate::tunnel::{RemoteTransportInfo, TunnelExt, TunnelSynthesisData};
|
||||
|
||||
impl TransportActor {
|
||||
/// Python 1.6.1 `Transport.synthesize_tunnel` (Transport.py:3170-3206). An
|
||||
/// initiator sends while still offline and names its tunnel; a receiver's
|
||||
/// reverse synthesis answers a peer's extension.
|
||||
pub(super) fn synthesize_tunnel(&mut self, interface_id: InterfaceId, reverse: bool) {
|
||||
let Some(identity) = self
|
||||
.tunnel_identity
|
||||
.clone()
|
||||
.filter(|identity| Some(identity.hash) == self.transport_identity_hash)
|
||||
else {
|
||||
debug!(
|
||||
interface_id,
|
||||
"no transport identity to sign a tunnel synthesis"
|
||||
);
|
||||
return;
|
||||
};
|
||||
let Some(entry) = self.interfaces.get(&interface_id) else {
|
||||
return;
|
||||
};
|
||||
let interface_hash = crate::tunnel::interface_hash(entry.upstream_name());
|
||||
let ext = TunnelExt::local(
|
||||
self.is_transport_enabled,
|
||||
self.interface_destination_cost(interface_id),
|
||||
self.interface_pr_cost(interface_id),
|
||||
);
|
||||
let Some(raw) =
|
||||
crate::tunnel::build_tunnel_synthesis_packet_with_ext(&identity, interface_hash, &ext)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let tunnel_id = TunnelSynthesisData::unpack(&raw[rns_wire::constants::HEADER_MINSIZE..])
|
||||
.map(|synthesis| synthesis.tunnel_id());
|
||||
if let Some(entry) = self.interfaces.get_mut(&interface_id) {
|
||||
entry.tunnel.synthesis_emitted = true;
|
||||
if !reverse {
|
||||
entry.tunnel.local_tunnel_id = tunnel_id;
|
||||
}
|
||||
}
|
||||
debug!(
|
||||
interface_id,
|
||||
reverse,
|
||||
len = raw.len(),
|
||||
"sending tunnel synthesis"
|
||||
);
|
||||
if reverse {
|
||||
self.send_to_interface(interface_id, &raw);
|
||||
} else {
|
||||
// The driver queues it just before the interface reports online.
|
||||
self.send_to_interface_unchecked(interface_id, &raw);
|
||||
}
|
||||
}
|
||||
|
||||
/// Python 1.6.1 `Transport.tunnel_synthesize_handler` (Transport.py:3208-3297).
|
||||
pub(super) fn tunnel_synthesize_handler(&mut self, data: &[u8], interface_id: InterfaceId) {
|
||||
let Some(entry) = self.interfaces.get_mut(&interface_id) else {
|
||||
return;
|
||||
};
|
||||
if !entry.tunnels_allowed() {
|
||||
return;
|
||||
}
|
||||
if entry.tunnel.remote_transport.is_some() || entry.tunnel.synthesis_received {
|
||||
debug!(interface_id, "additional tunnel synthesis");
|
||||
self.protocol_violation(interface_id);
|
||||
return;
|
||||
}
|
||||
// One chance per connection, spent before any check.
|
||||
entry.tunnel.synthesis_received = true;
|
||||
let Some(synthesis) = TunnelSynthesisData::unpack(data) else {
|
||||
debug!(
|
||||
interface_id,
|
||||
len = data.len(),
|
||||
"tunnel synthesis of invalid size"
|
||||
);
|
||||
self.protocol_violation(interface_id);
|
||||
return;
|
||||
};
|
||||
if !synthesis.is_signed() {
|
||||
self.request_detach(interface_id, DetachReason::InvalidSynthesis);
|
||||
return;
|
||||
}
|
||||
let remote_transport = synthesis.transport_identity_hash();
|
||||
if self.blackhole_table.is_blackholed(&remote_transport) {
|
||||
self.request_detach(interface_id, DetachReason::BlackholedTransport);
|
||||
return;
|
||||
}
|
||||
let remote_info = if synthesis.ext.is_empty() {
|
||||
None
|
||||
} else {
|
||||
match RemoteTransportInfo::decode(&synthesis.ext) {
|
||||
Ok(info) => Some(info),
|
||||
Err(error) => {
|
||||
debug!(interface_id, ?error, "invalid tunnel synthesis extension");
|
||||
self.protocol_violation(interface_id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
// Only an extension asks for an answer; the answer never asks again.
|
||||
if remote_info.is_some()
|
||||
&& self
|
||||
.interfaces
|
||||
.get(&interface_id)
|
||||
.is_some_and(|entry| !entry.tunnel.synthesis_emitted)
|
||||
{
|
||||
self.synthesize_tunnel(interface_id, true);
|
||||
}
|
||||
let Some(entry) = self.interfaces.get_mut(&interface_id) else {
|
||||
return;
|
||||
};
|
||||
entry.tunnel.remote_transport = Some(remote_transport);
|
||||
entry.tunnel.remote_info = remote_info;
|
||||
// An initiator learns its peer; only a receiver binds the tunnel.
|
||||
if entry.tunnel.local_tunnel_id.is_some() {
|
||||
return;
|
||||
}
|
||||
let tunnel_id = synthesis.tunnel_id();
|
||||
debug!(
|
||||
tunnel_id = hex::encode(&tunnel_id[..16]),
|
||||
interface_id, "tunnel synthesis validated"
|
||||
);
|
||||
crate::tunnel::handle_tunnel(&mut self.tunnel_table, tunnel_id, interface_id);
|
||||
self.state_dirty = true;
|
||||
self.restore_tunnel_paths(&tunnel_id, interface_id);
|
||||
}
|
||||
|
||||
/// Python `_detach_interface(None, interface_instance=..., internal_forced=True)`.
|
||||
/// The embedder stops the driver; without one, the actor drops the
|
||||
/// interface itself. Frames from it are ignored until it is gone.
|
||||
pub(super) fn request_detach(&mut self, interface_id: InterfaceId, reason: DetachReason) {
|
||||
if !self.interfaces.contains_key(&interface_id) || !self.detaching.insert(interface_id) {
|
||||
return;
|
||||
}
|
||||
tracing::info!(interface_id, ?reason, "tearing down tunnel interface");
|
||||
let sent = self.interface_control.as_ref().is_some_and(|control| {
|
||||
control
|
||||
.send(InterfaceControl::Detach {
|
||||
interface_id,
|
||||
reason,
|
||||
})
|
||||
.is_ok()
|
||||
});
|
||||
if !sent {
|
||||
self.deregister_interface(interface_id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Python 1.6.1 `remove_blackholed_paths` also tears down every interface
|
||||
/// whose tunnel peer is blackholed (Transport.py:4832-4839).
|
||||
pub(super) fn detach_blackholed_tunnel_peers(&mut self) {
|
||||
let blackholed: Vec<InterfaceId> = self
|
||||
.interfaces
|
||||
.iter()
|
||||
.filter(|(_, entry)| {
|
||||
entry
|
||||
.tunnel
|
||||
.remote_transport
|
||||
.is_some_and(|remote| self.blackhole_table.is_blackholed(&remote))
|
||||
})
|
||||
.map(|(id, _)| *id)
|
||||
.collect();
|
||||
for interface_id in blackholed {
|
||||
self.request_detach(interface_id, DetachReason::BlackholedTransport);
|
||||
}
|
||||
}
|
||||
|
||||
/// Frames from an interface transport asked to detach.
|
||||
pub(super) fn is_detaching(&self, interface_id: InterfaceId) -> bool {
|
||||
self.detaching.contains(&interface_id)
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,11 @@ pub struct AnnounceEntry {
|
||||
/// Receiving interface used by egress policy. Shared IPC peers are excluded
|
||||
/// from an echo; an eligible broadcast radio may relay on the same interface.
|
||||
pub source_interface: Option<InterfaceId>,
|
||||
/// Hash of the announce as received, Python's `IDX_AT_PACKET.packet_hash`.
|
||||
pub packet_hash: [u8; 32],
|
||||
/// Interfaces off a shared medium that already sent us this announce; the
|
||||
/// rebroadcast skips them (Python `IDX_AT_DEDUP_IFS`).
|
||||
pub dedup_interfaces: Vec<InterfaceId>,
|
||||
}
|
||||
|
||||
/// Destination-keyed rebroadcast records. Insertions replace matching entries;
|
||||
@@ -119,6 +124,8 @@ mod tests {
|
||||
block_rebroadcast: false,
|
||||
attached_interface: None,
|
||||
source_interface: None,
|
||||
packet_hash: [0; 32],
|
||||
dedup_interfaces: Vec::new(),
|
||||
},
|
||||
);
|
||||
assert_eq!(table.len(), 1);
|
||||
@@ -140,6 +147,8 @@ mod tests {
|
||||
block_rebroadcast: false,
|
||||
attached_interface: None,
|
||||
source_interface: None,
|
||||
packet_hash: [0; 32],
|
||||
dedup_interfaces: Vec::new(),
|
||||
},
|
||||
);
|
||||
table.insert(
|
||||
@@ -154,6 +163,8 @@ mod tests {
|
||||
block_rebroadcast: false,
|
||||
attached_interface: None,
|
||||
source_interface: None,
|
||||
packet_hash: [0; 32],
|
||||
dedup_interfaces: Vec::new(),
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@ use std::collections::{HashMap, VecDeque};
|
||||
|
||||
use rns_identity::stamps::{NETWORK_STAMP_SIZE, cost_to_fp};
|
||||
|
||||
const VALID_CACHE_MAX: usize = 128;
|
||||
const INVALID_CACHE_MAX: usize = 128;
|
||||
const VALID_CACHE_MAX: usize = 384;
|
||||
const INVALID_CACHE_MAX: usize = 384;
|
||||
|
||||
/// Why an announce was rejected, as upstream signals it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
@@ -238,18 +238,28 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caches_hold_128_entries_first_in_first_out() {
|
||||
fn caches_hold_384_entries_first_in_first_out() {
|
||||
let key = |i: u16| {
|
||||
let mut key = [0u8; 32];
|
||||
key[..2].copy_from_slice(&i.to_be_bytes());
|
||||
key
|
||||
};
|
||||
let mut cache = AnnounceValidationCache::new();
|
||||
for i in 0..=128u8 {
|
||||
cache.insert_valid([i; 32], result(None));
|
||||
cache.insert_invalid([i; 32], InvalidAnnounce::Invalid);
|
||||
for i in 0..=384u16 {
|
||||
cache.insert_valid(key(i), result(None));
|
||||
cache.insert_invalid(key(i), InvalidAnnounce::Invalid);
|
||||
}
|
||||
assert_eq!(cache.valid_len(), 128);
|
||||
assert_eq!(cache.invalid_len(), 128);
|
||||
// Identity.py 1.6.1.
|
||||
assert_eq!(cache.valid_len(), 384);
|
||||
assert_eq!(cache.invalid_len(), 384);
|
||||
assert!(matches!(
|
||||
cache.lookup(&[0; 32], 0.0, false),
|
||||
cache.lookup(&key(0), 0.0, false),
|
||||
CachedAnnounce::Miss
|
||||
));
|
||||
assert!(matches!(
|
||||
cache.lookup(&key(1), 0.0, false),
|
||||
CachedAnnounce::Rejected(InvalidAnnounce::Invalid)
|
||||
));
|
||||
cache.reset();
|
||||
assert_eq!((cache.valid_len(), cache.invalid_len()), (0, 0));
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
use bytes::Bytes;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock, Weak};
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio::sync::{Notify, mpsc, oneshot};
|
||||
|
||||
const MAX_REGISTERED: usize = 4096;
|
||||
type Registry = Mutex<Vec<(mpsc::WeakSender<Bytes>, Weak<Shared>)>>;
|
||||
@@ -34,6 +34,7 @@ struct State {
|
||||
struct Shared {
|
||||
state: Mutex<State>,
|
||||
ordinary: mpsc::WeakSender<Bytes>,
|
||||
offered: Notify,
|
||||
}
|
||||
struct Offer {
|
||||
owner: Option<crate::InterfaceOwner>,
|
||||
@@ -109,6 +110,7 @@ impl BackgroundAnnounceReceiver {
|
||||
active: false,
|
||||
generation: 0,
|
||||
}),
|
||||
offered: Notify::new(),
|
||||
});
|
||||
registry.push((ordinary.downgrade(), Arc::downgrade(&shared)));
|
||||
Ok(Self { shared })
|
||||
@@ -182,6 +184,13 @@ impl BackgroundAnnounceReceiver {
|
||||
pub fn has_offer(&self) -> bool {
|
||||
self.shared.state.lock().unwrap().offer.is_some()
|
||||
}
|
||||
|
||||
/// Resolve after the next offer lands. An offer made while no one waits is
|
||||
/// remembered for the next call, so a writer can check `has_offer` and then
|
||||
/// wait without missing one. One waiter per lane.
|
||||
pub async fn offered(&self) {
|
||||
self.shared.offered.notified().await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn lookup(ordinary: &mpsc::Sender<Bytes>) -> Option<BackgroundAnnounceSender> {
|
||||
@@ -242,6 +251,8 @@ impl BackgroundAnnounceSender {
|
||||
generation: state.generation,
|
||||
});
|
||||
state.active = true;
|
||||
drop(state);
|
||||
self.shared.offered.notify_one();
|
||||
Some(BackgroundOfferReceipt {
|
||||
started: rx,
|
||||
cancelled,
|
||||
@@ -275,6 +286,34 @@ mod tests {
|
||||
assert!(lookup(&tx).is_none());
|
||||
assert!(BackgroundAnnounceReceiver::register(&tx).is_ok());
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn offer_wakes_a_waiting_or_later_writer() {
|
||||
let (tx, _rx) = mpsc::channel(1);
|
||||
let driver = BackgroundAnnounceReceiver::register(&tx).unwrap();
|
||||
let sender = lookup(&tx).unwrap();
|
||||
let _early = sender
|
||||
.try_offer(Bytes::from_static(b"early"), 100.0, 0.0)
|
||||
.unwrap();
|
||||
let wait = std::time::Duration::from_secs(5);
|
||||
tokio::time::timeout(wait, driver.offered())
|
||||
.await
|
||||
.expect("an offer made before the wait is remembered");
|
||||
drop(driver.try_start(1.0).unwrap());
|
||||
|
||||
let waiter = tokio::spawn({
|
||||
let driver = driver.clone();
|
||||
async move { driver.offered().await }
|
||||
});
|
||||
tokio::task::yield_now().await;
|
||||
assert!(!waiter.is_finished());
|
||||
let _late = sender
|
||||
.try_offer(Bytes::from_static(b"late"), 100.0, 2.0)
|
||||
.unwrap();
|
||||
tokio::time::timeout(wait, waiter)
|
||||
.await
|
||||
.expect("an offer wakes a waiting writer")
|
||||
.unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn lease_bounds_offer_through_complete_write_and_expiry() {
|
||||
let (tx, _rx) = mpsc::channel(1);
|
||||
|
||||
@@ -42,8 +42,14 @@ pub const UNUSED_PATH_LINGER: f64 = 60.0 * 60.0 * 1.75;
|
||||
/// Never-used path linger on a leaf or shared-instance client (Transport.py).
|
||||
pub const UNUSED_PATH_LINGER_LEAF: f64 = 60.0 * 12.0;
|
||||
|
||||
/// Never-used paths kept by the pool cull (Transport.py).
|
||||
pub const PATH_POOL_UNUSED_TARGET: usize = 2048;
|
||||
/// Never-used paths the pool cull keeps at most (Transport.py).
|
||||
pub const PATH_POOL_UNUSED_MAX: usize = 1536;
|
||||
|
||||
/// Never-used paths the pool cull keeps however many paths are used.
|
||||
pub const PATH_POOL_UNUSED_MIN: usize = 512;
|
||||
|
||||
/// Used paths beyond this shrink the never-used pool target one for one.
|
||||
pub const PATH_POOL_USED_TARGET: usize = 2048;
|
||||
|
||||
/// Interfaces below this bitrate linger never-used paths longer (Transport.py).
|
||||
pub const PATH_SLOW_BITRATE: u64 = 25_000;
|
||||
@@ -52,8 +58,8 @@ pub const PATH_SLOW_LINGER_FACTOR: f64 = 10.0;
|
||||
/// Interval between never-used pool checks (Transport.py).
|
||||
pub(crate) const PATH_POOL_CHECK_INTERVAL: f64 = 5.0 * 60.0;
|
||||
|
||||
/// Reverse table entry timeout (8 minutes).
|
||||
pub const REVERSE_TIMEOUT: u64 = 480;
|
||||
/// Reverse table entry timeout (3 minutes, Transport.py).
|
||||
pub const REVERSE_TIMEOUT: u64 = 180;
|
||||
|
||||
/// Receipt-count ceiling applied during periodic maintenance. Registration can
|
||||
/// temporarily exceed it; maintenance culls the oldest receipts.
|
||||
@@ -192,8 +198,8 @@ pub const BLACKHOLE_CHECK_INTERVAL: f64 = 60.0;
|
||||
/// (0.02 means 2%). Supply a fraction, not a percentage, to transport APIs.
|
||||
pub const ANNOUNCE_CAP: f64 = 0.02;
|
||||
|
||||
/// Maximum ingress-limited announces to hold per interface.
|
||||
pub const MAX_HELD_ANNOUNCES: usize = 256;
|
||||
/// Maximum ingress-limited announces to hold per interface (Interface.py).
|
||||
pub const MAX_HELD_ANNOUNCES: usize = 64;
|
||||
|
||||
/// Held announce release interval (seconds).
|
||||
pub const IC_HELD_RELEASE_INTERVAL: f64 = 5.0;
|
||||
@@ -261,6 +267,10 @@ pub const TUNNEL_TIMEOUT: u64 = 28_800;
|
||||
/// Tunnel path timeout (8 hours, in seconds).
|
||||
pub const TUNNEL_PATH_TIMEOUT: u64 = 28_800;
|
||||
|
||||
/// How long an unbound tunnel awaits its interface's return (10 minutes, in
|
||||
/// seconds; Python `TUNNEL_RECONNECT_WINDOW`).
|
||||
pub const TUNNEL_RECONNECT_WINDOW: u64 = 600;
|
||||
|
||||
/// Exported announce-queue interval, in seconds. The current actor processes
|
||||
/// interface announce queues on its maintenance tick instead.
|
||||
pub const ANNOUNCE_QUEUE_INTERVAL: f64 = 1.0;
|
||||
|
||||
@@ -11,16 +11,21 @@ pub const NAME_HASH_LEN: usize = 10;
|
||||
|
||||
pub type NameHash = [u8; NAME_HASH_LEN];
|
||||
|
||||
/// The `[filter]` configuration (Reticulum.py).
|
||||
/// The `[filter]` configuration and the config directory's type-name files
|
||||
/// (Reticulum.py).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FilterPolicy {
|
||||
pub required_only: bool,
|
||||
/// Full destination names, Python `ignored_types`.
|
||||
/// Python `ignored_types`: full destination names, or `<hex>` name hashes.
|
||||
pub ignored_types: Vec<String>,
|
||||
/// Full destination names, Python `allowed_types`.
|
||||
/// Python `allowed_types`: full destination names, or `<hex>` name hashes.
|
||||
pub allowed_types: Vec<String>,
|
||||
/// Packets arriving with this many wire hops or more are dropped.
|
||||
pub hop_limiter: u8,
|
||||
/// Full names from `known_destination_types`, for logs only.
|
||||
pub known_types: Vec<String>,
|
||||
/// Full names from `flagged_destination_types`, for logs only.
|
||||
pub flagged_types: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for FilterPolicy {
|
||||
@@ -30,6 +35,8 @@ impl Default for FilterPolicy {
|
||||
ignored_types: Vec::new(),
|
||||
allowed_types: Vec::new(),
|
||||
hop_limiter: crate::constants::PATHFINDER_M,
|
||||
known_types: Vec::new(),
|
||||
flagged_types: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,12 +62,51 @@ pub(crate) struct DestinationTypeFilter {
|
||||
allowed: HashSet<NameHash>,
|
||||
client: HashMap<NameHash, HashSet<Vec<u8>>>,
|
||||
names: HashMap<NameHash, String>,
|
||||
flagged: HashMap<NameHash, String>,
|
||||
required_only: bool,
|
||||
}
|
||||
|
||||
/// A type-filter entry as Python's `block_destination_type` and
|
||||
/// `allow_destination_type` read it: `<…>` takes the next 20 characters as a
|
||||
/// hex name hash, else hashes those characters as a name. `None` for an empty
|
||||
/// entry, or hex that is not one name hash long, which upstream stores but can
|
||||
/// never match.
|
||||
fn parse_type_entry(full_name: &str) -> Option<(NameHash, String)> {
|
||||
if full_name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if !(full_name.starts_with('<') && full_name.ends_with('>')) {
|
||||
return Some((name_hash(full_name), full_name.to_string()));
|
||||
}
|
||||
let sliced: String = full_name.chars().skip(1).take(NAME_HASH_LEN * 2).collect();
|
||||
match py_fromhex(&sliced) {
|
||||
Some(bytes) if bytes.len() == NAME_HASH_LEN => {
|
||||
Some((bytes.try_into().expect("checked length"), sliced))
|
||||
}
|
||||
Some(bytes) if !bytes.is_empty() => None,
|
||||
_ => Some((name_hash(&sliced), sliced)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `bytes.fromhex`: hex pairs, with ASCII whitespace allowed between them.
|
||||
fn py_fromhex(text: &str) -> Option<Vec<u8>> {
|
||||
let digit = |c: char| c.to_digit(16).filter(|_| c.is_ascii());
|
||||
let mut out = Vec::new();
|
||||
let mut chars = text.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
if matches!(c, ' ' | '\t' | '\n' | '\x0b' | '\x0c' | '\r') {
|
||||
continue;
|
||||
}
|
||||
let high = digit(c)?;
|
||||
let low = digit(chars.next()?)?;
|
||||
out.push((high * 16 + low) as u8);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
impl DestinationTypeFilter {
|
||||
/// Apply a configuration: `ignored_types` through `block`, `allowed_types`
|
||||
/// through `allow`, in Python's order.
|
||||
/// through `allow`, then the type-name files, in Python's order.
|
||||
pub fn apply_policy(&mut self, policy: &FilterPolicy) {
|
||||
self.required_only = policy.required_only;
|
||||
for name in &policy.ignored_types {
|
||||
@@ -69,25 +115,37 @@ impl DestinationTypeFilter {
|
||||
for name in &policy.allowed_types {
|
||||
self.allow(name);
|
||||
}
|
||||
for name in &policy.known_types {
|
||||
self.names.insert(name_hash(name), name.clone());
|
||||
}
|
||||
for name in &policy.flagged_types {
|
||||
self.flagged.insert(name_hash(name), name.clone());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_required_only(&mut self, enabled: bool) {
|
||||
self.required_only = enabled;
|
||||
}
|
||||
|
||||
/// Python `block_destination_type`: a blocked type is no longer wanted.
|
||||
/// Python `block_destination_type`: a blocked type is no longer wanted,
|
||||
/// and its name is flagged.
|
||||
pub fn block(&mut self, full_name: &str) {
|
||||
let hash = name_hash(full_name);
|
||||
let Some((hash, name)) = parse_type_entry(full_name) else {
|
||||
return;
|
||||
};
|
||||
self.blocked.insert(hash);
|
||||
self.client.remove(&hash);
|
||||
self.names.insert(hash, full_name.to_string());
|
||||
self.names.insert(hash, name.clone());
|
||||
self.flagged.insert(hash, name);
|
||||
}
|
||||
|
||||
/// Python `allow_destination_type`.
|
||||
pub fn allow(&mut self, full_name: &str) {
|
||||
let hash = name_hash(full_name);
|
||||
let Some((hash, name)) = parse_type_entry(full_name) else {
|
||||
return;
|
||||
};
|
||||
self.allowed.insert(hash);
|
||||
self.names.insert(hash, full_name.to_string());
|
||||
self.names.insert(hash, name);
|
||||
}
|
||||
|
||||
/// Python `_wants_destination_type`: false only for a blocked type.
|
||||
@@ -132,9 +190,37 @@ impl DestinationTypeFilter {
|
||||
self.client.contains_key(hash)
|
||||
}
|
||||
|
||||
/// Python `destination_type_name`.
|
||||
pub fn type_name(&self, hash: &NameHash) -> &str {
|
||||
self.names.get(hash).map_or("unknown", String::as_str)
|
||||
/// Python `destination_type_name`: the known name, else the flagged
|
||||
/// name, else the hash in hex.
|
||||
pub fn type_name(&self, hash: &NameHash) -> String {
|
||||
self.names
|
||||
.get(hash)
|
||||
.or_else(|| self.flagged.get(hash))
|
||||
.cloned()
|
||||
.unwrap_or_else(|| hex::encode(hash))
|
||||
}
|
||||
|
||||
/// Python `prettynamehash`.
|
||||
pub fn pretty_name(&self, hash: &NameHash) -> String {
|
||||
format!("<{}>", self.type_name(hash))
|
||||
}
|
||||
|
||||
/// Python drops a blocked type silently, ahead of the required-only check.
|
||||
pub fn is_blocked(&self, hash: &NameHash) -> bool {
|
||||
self.blocked.contains(hash)
|
||||
}
|
||||
|
||||
/// Python's rule for a path restored from storage (Transport.py): a
|
||||
/// blocked type goes, and under `required_only` so does any type not
|
||||
/// allowed, client wants included. An unknown type goes only under
|
||||
/// `required_only`.
|
||||
pub fn admits_stored(&self, hash: Option<&NameHash>) -> bool {
|
||||
match hash {
|
||||
Some(hash) => {
|
||||
!self.blocked.contains(hash) && (!self.required_only || self.allowed.contains(hash))
|
||||
}
|
||||
None => !self.required_only,
|
||||
}
|
||||
}
|
||||
|
||||
/// The decision inside Python `Transport.inbound` (Transport.py),
|
||||
@@ -169,6 +255,80 @@ mod tests {
|
||||
assert!(!f.wants("a.b", vec![1]));
|
||||
}
|
||||
|
||||
/// Transport.py 1.6.1 (e96c81c3): `<hex>` is a name hash; anything else
|
||||
/// in angle brackets is hashed as the 20 characters after `<`.
|
||||
#[test]
|
||||
fn angle_bracket_entries_are_name_hashes() {
|
||||
let hash: NameHash = hex::decode("c4ace368262d845c9dd3")
|
||||
.unwrap()
|
||||
.try_into()
|
||||
.unwrap();
|
||||
for entry in [
|
||||
"<c4ace368262d845c9dd3>",
|
||||
"<C4ACE368262D845C9DD3>",
|
||||
"<c4ace368262d845c9dd3aabbccddeeff00>",
|
||||
] {
|
||||
let mut f = DestinationTypeFilter::default();
|
||||
f.block(entry);
|
||||
assert!(!f.admits(&hash, AnnounceSource::Other, 0), "{entry}");
|
||||
assert_eq!(f.type_name(&hash).to_lowercase(), "c4ace368262d845c9dd3");
|
||||
}
|
||||
let mut f = DestinationTypeFilter::default();
|
||||
f.block("<abcd>");
|
||||
assert!(!f.admits(&name_hash("abcd>"), AnnounceSource::Other, 0));
|
||||
f.set_required_only(true);
|
||||
f.allow("<0123456789abcdef0123>");
|
||||
let allowed: NameHash = hex::decode("0123456789abcdef0123")
|
||||
.unwrap()
|
||||
.try_into()
|
||||
.unwrap();
|
||||
assert!(f.admits(&allowed, AnnounceSource::Other, 0));
|
||||
// A client registration hashes the literal text.
|
||||
assert!(f.wants("<0011223344556677889a>", vec![1]));
|
||||
assert!(f.is_wanted(&name_hash("<0011223344556677889a>")));
|
||||
// Whitespace between pairs is skipped, as `bytes.fromhex` does; a
|
||||
// short result matches nothing.
|
||||
assert_eq!(parse_type_entry("<c4 ac e3 68 26 2d 84 5c 9d d3>"), None);
|
||||
assert_eq!(parse_type_entry(""), None);
|
||||
}
|
||||
|
||||
/// Transport.py 1.6.1: known name, else flagged name, else bare hex; a
|
||||
/// blocked type is flagged, and the name files apply after `[filter]`.
|
||||
#[test]
|
||||
fn type_names_fall_back_to_flagged_then_hex() {
|
||||
let mut f = DestinationTypeFilter::default();
|
||||
f.apply_policy(&FilterPolicy {
|
||||
ignored_types: vec!["spam.type".into()],
|
||||
known_types: vec!["lxmf.delivery".into(), "spam.type".into()],
|
||||
flagged_types: vec!["bad.type".into()],
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(f.type_name(&name_hash("lxmf.delivery")), "lxmf.delivery");
|
||||
assert_eq!(f.type_name(&name_hash("bad.type")), "bad.type");
|
||||
assert_eq!(f.flagged.get(&name_hash("spam.type")).unwrap(), "spam.type");
|
||||
let unknown = name_hash("other.type");
|
||||
assert_eq!(f.type_name(&unknown), hex::encode(unknown));
|
||||
assert_eq!(
|
||||
f.pretty_name(&unknown),
|
||||
format!("<{}>", hex::encode(unknown))
|
||||
);
|
||||
}
|
||||
|
||||
/// Transport.py 1.6.1 (20e25a9f): the load rule ignores client wants.
|
||||
#[test]
|
||||
fn stored_paths_follow_the_blocked_and_allowed_types_only() {
|
||||
let mut f = DestinationTypeFilter::default();
|
||||
f.block("a.blocked");
|
||||
f.allow("a.allowed");
|
||||
assert!(f.wants("a.wanted", vec![1]));
|
||||
let [blocked, allowed, wanted] = ["a.blocked", "a.allowed", "a.wanted"].map(name_hash);
|
||||
assert!(!f.admits_stored(Some(&blocked)));
|
||||
assert!(f.admits_stored(Some(&wanted)) && f.admits_stored(None));
|
||||
f.set_required_only(true);
|
||||
assert!(f.admits_stored(Some(&allowed)));
|
||||
assert!(!f.admits_stored(Some(&wanted)) && !f.admits_stored(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unwants_reports_registration_and_last_requester_drops_type() {
|
||||
let mut f = DestinationTypeFilter::default();
|
||||
|
||||
@@ -43,7 +43,7 @@ pub fn qualifies(info: &DiscoveryInfo, allow_unverified: bool) -> bool {
|
||||
|
||||
/// Python's `version_tuple`: the leading digits of each dot-separated
|
||||
/// component, up to the first without any (Discovery.py).
|
||||
fn version_tuple(version: &str) -> Option<Vec<u64>> {
|
||||
pub(crate) fn version_tuple(version: &str) -> Option<Vec<u64>> {
|
||||
let components: Vec<u64> = version
|
||||
.trim()
|
||||
.split('.')
|
||||
|
||||
@@ -411,9 +411,9 @@ impl ReceiverConfig {
|
||||
stamp: &[u8],
|
||||
) -> Result<ValidatedMaterial, Reason> {
|
||||
let infohash = rns_crypto::sha::full_hash(packed_info);
|
||||
if !self.stamper.valid(&infohash, stamp, self.required_value) {
|
||||
let Some(stamp_value) = self.stamper.validate(&infohash, stamp, self.required_value) else {
|
||||
return Err(Reason::StampInvalid);
|
||||
}
|
||||
};
|
||||
|
||||
let info: DiscoveryInfo = match app_data::decode_info(packed_info) {
|
||||
Ok(i) => i,
|
||||
@@ -426,7 +426,7 @@ impl ReceiverConfig {
|
||||
Ok(ValidatedMaterial {
|
||||
info,
|
||||
stamp: stamp.to_vec(),
|
||||
stamp_value: self.stamper.value(&infohash, stamp),
|
||||
stamp_value,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -567,17 +567,17 @@ impl ReceiverState {
|
||||
}
|
||||
|
||||
let infohash = rns_crypto::sha::full_hash(packed_info);
|
||||
if !self
|
||||
.config
|
||||
.stamper
|
||||
.valid(&infohash, stamp, self.config.required_value)
|
||||
{
|
||||
let Some(stamp_value) =
|
||||
self.config
|
||||
.stamper
|
||||
.validate(&infohash, stamp, self.config.required_value)
|
||||
else {
|
||||
let evicted = lock_unpoisoned(&self.caches).insert_invalid(key);
|
||||
if evicted {
|
||||
ReceiverMetrics::increment(&self.metrics.invalid_cache_evictions);
|
||||
}
|
||||
return Err(Reason::StampInvalid);
|
||||
}
|
||||
};
|
||||
|
||||
let info = match app_data::decode_info(packed_info) {
|
||||
Ok(info) => info,
|
||||
@@ -589,7 +589,7 @@ impl ReceiverState {
|
||||
let material = ValidatedMaterial {
|
||||
info,
|
||||
stamp: stamp.to_vec(),
|
||||
stamp_value: self.config.stamper.value(&infohash, stamp),
|
||||
stamp_value,
|
||||
};
|
||||
let evicted = lock_unpoisoned(&self.caches).insert_valid(key, material.clone());
|
||||
if evicted {
|
||||
@@ -845,6 +845,7 @@ mod tests {
|
||||
announce_packet_hash: [0x22; 32],
|
||||
is_path_response: false,
|
||||
hops: 3,
|
||||
emitted: 0,
|
||||
app_data: Some(app_data),
|
||||
public_key: None,
|
||||
ratchet: None,
|
||||
@@ -873,6 +874,32 @@ mod tests {
|
||||
assert_eq!(listed[0].network_id, [0x11; 16]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_a_non_expanded_stamp_with_its_value() {
|
||||
let dir = tmpdir("non_expanded");
|
||||
let store = Arc::new(DiscoveryStore::open(&dir).unwrap());
|
||||
let info = sample_info();
|
||||
let infohash = encode_info(&info).unwrap().infohash;
|
||||
let (stamp, value) = rns_identity::stamps::generate_stamp(
|
||||
&infohash,
|
||||
14.0,
|
||||
0,
|
||||
STAMP_SIZE,
|
||||
&StampControl::default(),
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let (blob, _) = stamped_blob(&info, &stamp);
|
||||
let cfg = make_cfg(
|
||||
Arc::new(crate::discovery::stamper::RnsDiscoveryStamper),
|
||||
store.clone(),
|
||||
None,
|
||||
None,
|
||||
);
|
||||
assert_eq!(cfg.process_event(&event_with(blob)), Outcome::Accepted);
|
||||
assert_eq!(store.list(None).unwrap()[0].stamp_value, value);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_stamp() {
|
||||
let dir = tmpdir("badstamp");
|
||||
@@ -921,6 +948,7 @@ mod tests {
|
||||
announce_packet_hash: [0; 32],
|
||||
is_path_response: false,
|
||||
hops: 0,
|
||||
emitted: 0,
|
||||
app_data: None,
|
||||
public_key: None,
|
||||
ratchet: None,
|
||||
|
||||
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user