Compare commits

..
451 Commits
Author SHA1 Message Date
DeFiDude b8c1446b93 serial: assert DTR and RTS on open so nRF52 RNodes answer on Windows 2026-11-08 16:24:13 -07:00
DeFiDude 14241a3839 Release 1.4.0 2026-11-08 11:52:10 -07:00
DeFiDude 302626c38a api: RNodeStream is an opaque struct; approve the removal and refresh the baseline 2026-11-07 21:21:56 -07:00
DeFiDude ac9ea27752 Replace invalid AGPL license with Reticulum License
This repository is a port of Reticulum, which is licensed under the Reticulum
License. The AGPL-3.0-or-later grant previously in LICENSE was never
effective, because there was no right to place the derived code under AGPL
terms. The Reticulum License now in LICENSE governs every revision in this
repository's history, not only revisions from this commit forward. Additions
and modifications by Ratspeak LLC remain its copyright and are licensed under
the same terms.
2026-11-07 20:49:18 -07:00
DeFiDude 4bf5679bd5 rnode: rewrite the TCP transport behind a shared link trait 2026-11-07 19:25:36 -07:00
DeFiDude 6ce6aa8dba rnode: initialize Android USB serial adapters 2026-11-05 20:06:40 -07:00
DeFiDude fdedbd2c8b docs: escape the rnid metadata file placeholder 2026-11-05 11:08:46 -07:00
DeFiDude 7071bae90e runtime: let an idle link manager sleep until it has work 2026-11-05 02:43:54 -07:00
DeFiDude b217cb3f59 docs: format command help 2026-11-02 11:42:21 -07:00
DeFiDude dc50ce5390 docs: refresh guides and reference help 2026-11-02 11:13:50 -07:00
DeFiDude 5b38cae702 api: record the RNode attempt-failure snapshot 2026-10-31 13:45:25 -06:00
DeFiDude 5a448fdebf rnode: name why a BLE attempt failed and signal a radio that never answers 2026-10-31 12:10:00 -06:00
DeFiDude bf7d16fc36 tests: keep child-spawning tests apart from lock and FIFO tests 2026-10-25 23:14:14 -06:00
DeFiDude 48adcf726e discovery: never announce Backbone clients and read only reachable_on 2026-10-25 21:49:07 -06:00
DeFiDude f1caa4571d docs: record the TCP client's i2p_tunneled option 2026-10-25 21:44:34 -06:00
DeFiDude 30e433a9cb runtime: read AutoInterface devices and I2P peers exactly as Python lists them 2026-10-25 21:11:23 -06:00
DeFiDude b56a427c4a docs: call the RPC key an admin credential 2026-10-25 21:05:17 -06:00
DeFiDude 0267f42001 rnstatus: show the network an auto-connected interface came from 2026-10-25 21:03:24 -06:00
DeFiDude 5ac4820b32 management: answer the status profiling flag as Python does 2026-10-25 20:53:59 -06:00
DeFiDude c3b3fd1c1f interfaces: wait for the real reconnect in local socket tests 2026-10-25 20:49:42 -06:00
DeFiDude 55072d1ca2 discovery: require an explicit reachable address 2026-10-25 19:38:38 -06:00
DeFiDude 06597b5869 tcp: honor I2P-tunneled client socket timeouts 2026-10-25 19:34:27 -06:00
DeFiDude 442196c71a runtime: read AutoInterface device lists from parsed config 2026-10-25 18:46:54 -06:00
DeFiDude 45b49db0c1 i2p: accept SAM reply lines up to Python's 64 KiB limit 2026-10-25 12:41:57 -06:00
DeFiDude 21100300fc i2p: keep the session's private key out of freed memory and debug output 2026-10-25 12:00:48 -06:00
DeFiDude 6aa1d4bbf1 transport: keep each IFAC key in one wiped allocation shared by its interface records 2026-10-25 11:50:58 -06:00
DeFiDude 3311c0a7b1 runtime: wipe the IFAC passphrase in interface options and keep it out of debug output 2026-10-25 11:39:52 -06:00
DeFiDude 6bdc82af93 identity: encode ratchet files into a pre-sized buffer and correct key-file notes 2026-10-25 11:23:44 -06:00
DeFiDude 215250d2b2 tests: control the residue harness and check secrets drop inside each check 2026-10-25 11:18:06 -06:00
DeFiDude 881f7b926d identity: test raw keys that begin like the older envelope format 2026-10-25 11:12:09 -06:00
DeFiDude d1c6d508c9 persistence: retry file readbacks that a signal interrupts 2026-10-25 11:09:40 -06:00
DeFiDude 5366b1d3d3 identity: decode legacy key files without leaving key copies in freed memory 2026-10-25 11:00:38 -06:00
DeFiDude 588fdfc123 ratkey: wipe security key responses that carry an ECDH shared secret 2026-10-25 10:34:56 -06:00
DeFiDude a551770f63 crypto: wipe HKDF output, including IFAC masks, when it is dropped 2026-10-25 10:34:56 -06:00
DeFiDude 416f1ae86c crypto: wipe AES key schedules and CBC state when ciphers are dropped 2026-10-25 10:09:58 -06:00
DeFiDude ad10380bbb crypto: keep plaintext, derived keys and key files out of freed memory 2026-10-25 09:34:02 -06:00
DeFiDude 708b37b017 persistence: verify writes through a wiped buffer and test real write failures 2026-10-25 09:33:48 -06:00
DeFiDude 6d2619cc48 docs: add operator notes for remote management on the transport identity 2026-10-25 07:14:41 -06:00
DeFiDude 8c841a92f1 docs: correct the Python release that gates auto-connect 2026-10-25 07:14:39 -06:00
DeFiDude 56b6bcefa5 docs: reword two discovery comments 2026-10-25 07:14:38 -06:00
DeFiDude efbc495e84 api: make discovery rejection reasons non-exhaustive 2026-10-25 07:14:26 -06:00
DeFiDude 2992377739 tests: check that a wire announce without valid IFAC is never held 2026-10-25 07:13:41 -06:00
DeFiDude 692260e79b status: name the network an auto-connected interface came from 2026-10-25 07:11:57 -06:00
DeFiDude 48e355a943 discovery: never auto-connect to onion or local addresses, or to an endpoint already in use 2026-10-25 07:09:37 -06:00
DeFiDude cd091604d2 management: refuse Resources on remote management Links, as Python does 2026-10-25 07:07:50 -06:00
DeFiDude 08d246ed22 management: filter remote path tables as Python compares destinations and hop limits 2026-10-25 07:07:16 -06:00
DeFiDude 04f9324cd5 transport: count dropped realtime Link packets in the interface's dropped bytes 2026-10-25 07:06:50 -06:00
DeFiDude e16c8b4d39 transport: count a path request only once its tag passes the duplicate check 2026-10-25 07:06:33 -06:00
DeFiDude 4683cb2c2a link: add a clock that keeps counting while the system is suspended 2026-10-25 06:35:18 -06:00
DeFiDude 379312e305 docs: describe I2P discovery generically 2026-10-25 06:24:04 -06:00
DeFiDude b79bcdb38b i2p: keep the server's key in Python's key file, and announce a new address on the interval 2026-10-25 06:23:59 -06:00
DeFiDude 4c6217597a i2p: give configured peers the global ingress settings, as Python does 2026-10-25 06:23:40 -06:00
DeFiDude cb929d5f65 i2p: never tear down a bootstrap-only I2P interface, as Python never detaches one 2026-10-25 06:21:47 -06:00
DeFiDude ef551de12b tests: time out the first connect in the backlog tests, so a slow refusal still fails first 2026-10-25 06:20:05 -06:00
DeFiDude 09ae5d6e26 transport: remember the identity of every validated announce before deciding its path 2026-10-25 06:04:12 -06:00
DeFiDude 9d7b2bd429 api: expose synthesis verification and the client drivers' Python names 2026-10-25 03:40:37 -06:00
DeFiDude f3f72ead60 i2p: announce one discoverable interface at its own b32 and keep peers at Python's defaults 2026-10-25 03:34:53 -06:00
DeFiDude 53515b3d41 docs: note that an I2P interface runs its server only when connectable 2026-10-25 03:21:41 -06:00
DeFiDude 846833a197 docs: describe the hub restart change generically 2026-10-25 03:21:08 -06:00
DeFiDude c44744ecee tests: give tunnel test names, paths and aspects neutral prefixes 2026-10-25 03:20:57 -06:00
DeFiDude 4ea028eb75 tests: run the Unix shared-instance tunnel tests only on Unix 2026-10-25 03:19:47 -06:00
DeFiDude fbbc311192 tunnel: expire handled tunnels after TUNNEL_TIMEOUT as Python does 2026-10-25 03:18:33 -06:00
DeFiDude 1801cf291a local: drop traffic queued while the shared instance was unreachable 2026-10-25 03:11:40 -06:00
DeFiDude 264b00eb3d interfaces: drop traffic queued while a client's connection attempts fail 2026-10-25 03:07:38 -06:00
DeFiDude 2e8fa290dc discovery: announce KISS TCP clients and unset radio parameters as Python does 2026-10-25 03:00:21 -06:00
DeFiDude feb11b0089 discovery: name rsRNS and auto-connect only to the stacks Python 1.5 trusts 2026-10-25 02:51:31 -06:00
DeFiDude 1371918851 transport: process released and replayed announces without re-checking IFAC or recounting bytes 2026-10-25 02:51:05 -06:00
DeFiDude 65d95eed33 status: give Python 1.5 rnstatus and rnpath full interface stats, locally and remotely 2026-10-25 02:50:33 -06:00
DeFiDude 6e412dc9e0 interfaces: open every TCP, Backbone and I2P client connection with a tunnel synthesis 2026-10-24 23:29:20 -06:00
DeFiDude b774544cbb transport: drop multi-hop PLAIN and GROUP packets as Python's packet filter does 2026-10-24 23:10:14 -06:00
DeFiDude af65181e49 transport: accept valid tunnel syntheses and bind tunnels as in Python 2026-10-24 23:06:26 -06:00
DeFiDude acd59b178e transport: never rebind saved paths to accepted clients and load tunnels unbound 2026-10-24 23:00:56 -06:00
DeFiDude 52ab6c02d7 transport: stop sharing interface id 0 and run every configured I2P peer 2026-10-24 22:52:07 -06:00
DeFiDude f9d848866e transport: give interface stat entries a default 2026-10-24 19:02:11 -06:00
DeFiDude 562bc99da7 android-usb: read one max-size packet per bulk transfer 2026-10-22 23:09:12 -06:00
DeFiDude d738238b4e tests: retry the listener signal check when startup was interrupted 2026-10-21 17:33:39 -06:00
DeFiDude e5e8401fc7 link: count the responder's LRPROOF as Link outbound, as in Python 2026-10-21 17:33:39 -06:00
DeFiDude d047641898 link: accept peer identification before the RTT packet, as in Python 2026-10-21 16:08:08 -06:00
DeFiDude 76cfd48b29 tests: skip long backdated timeouts on freshly booted Windows clocks 2026-10-20 23:30:56 -06:00
DeFiDude 42b53c5538 persistence: accept every filesystem and warn on network or RAM storage 2026-10-20 20:27:10 -06:00
DeFiDude 5468316087 ci: pin Rust 1.96.0 instead of floating stable 2026-10-20 20:08:40 -06:00
DeFiDude c4788883f3 api: record RNode rejection, IFAC status and interface enable additions 2026-10-20 18:50:36 -06:00
DeFiDude 8b046794f1 docs: note pending radio and status changes 2026-10-20 17:17:30 -06:00
DeFiDude 85f29bcfd3 config: start an interface only when it is enabled, as upstream 2026-10-20 17:16:28 -06:00
DeFiDude 465ec096a5 status: report IFAC like upstream, only for interfaces that have it 2026-10-20 16:33:12 -06:00
DeFiDude b6f9e788b2 rnode: confirm effective settings on every transport and retry unopenable ports 2026-10-20 15:17:08 -06:00
DeFiDude 1a835f0acc ble: hold native RNode startup until the Android bridge attaches 2026-10-20 12:46:18 -06:00
DeFiDude 506852837c ble: validate effective RNode settings and stop on definitive rejection 2026-10-20 10:27:03 -06:00
DeFiDude 8fcf0b678a ratchet: require prepared namespaces for durable received keys 2026-10-13 17:41:23 -06:00
DeFiDude 817a640ed1 runtime: defer bounded request work with exact endpoint ownership 2026-10-13 00:30:19 -06:00
DeFiDude 4bba059d93 persistence: qualify native Android locking and CI boundaries 2026-10-13 00:07:28 -06:00
DeFiDude 7a33f4297f protocol: enforce capacity, ownership and durable admission boundaries 2026-10-12 23:57:46 -06:00
DeFiDude df94572ff6 tests: retain RNode and cache-miss regression coverage 2026-10-12 23:57:45 -06:00
DeFiDude 799e946ac9 release: preserve committed documentation bytes in archives 2026-10-12 16:09:39 -06:00
DeFiDude 6a425e8d5a release: qualify native archives before tagging 2026-10-12 15:59:21 -06:00
DeFiDude 032c3fd6d3 release: consolidate pending API changes into 1.3.0 2026-10-12 15:25:17 -06:00
DeFiDude 1ff0134979 transport: repair discovery and bound background radio admission 2026-10-12 14:11:58 -06:00
DeFiDude 1a0a74ad06 link: bound peer-reported RTT before deriving Link timers 2026-10-12 11:52:59 -06:00
DeFiDude 5275fbb402 api: simplify compatibility metadata 2026-10-10 17:39:31 -06:00
DeFiDude 0f8731bb5b ble: reserve central sessions until disconnect completes 2026-10-08 23:17:37 -06:00
DeFiDude 6bbac52ea0 build: keep fixed-size parsing compatible with current Clippy 2026-10-08 23:10:41 -06:00
DeFiDude cac8151fd8 build: complete Rust 1.89 lint updates on Linux 2026-10-08 22:58:27 -06:00
DeFiDude f64b4d22d9 ble: upgrade btleplug with bounded Windows address recovery
Require Rust 1.89 for the host workspace and align manifests, CI, source contracts and locks. Apply the compiler's required let-chain lint fixes without changing public API snapshots. Keep Apple bindings explicit, preserve native Android owners, and qualify Windows BLE tests alongside other platforms.
2026-10-08 22:53:21 -06:00
DeFiDude 5edb8f22f5 build: keep counter and BLE diagnostics compatible across toolchains 2026-10-08 16:20:35 -06:00
DeFiDude d4183434fc docs: summarize pending Bluetooth and readiness changes 2026-09-25 00:23:25 -06:00
DeFiDude 3ce9909f78 api: record compatible bind readiness addition 2026-09-24 10:19:46 -06:00
DeFiDude 56c7a6e5d8 transport: fix BLE packet flow control and add bind readiness 2026-09-24 10:17:15 -06:00
DeFiDude 49aa33db1b build: align API manifest and consumer lock with socket floor 2026-09-17 14:42:10 -06:00
DeFiDude bdbb6e9f63 net: require non-inheritable Windows socket backend 2026-09-17 14:13:30 -06:00
DeFiDude 8be3725a35 tests: bound Python RPC fixtures and retain listener ports 2026-09-17 13:49:21 -06:00
DeFiDude 306eaa8a18 tests: await daemon readiness before shutdown signal 2026-09-17 10:25:51 -06:00
DeFiDude 6abe1f3d4a api: record the reviewed 1.3 discovery migration 2026-09-10 11:59:45 -06:00
DeFiDude 92b91d6ba3 transport: encapsulate recursive discovery ownership for 1.3 2026-09-10 11:56:19 -06:00
DeFiDude 25c69c6f37 tests: cover discovery fairness and USB event races 2026-09-08 21:49:54 -06:00
DeFiDude 0279d2475a docs: fix platform-specific BLE Rustdoc references 2026-09-08 19:57:28 -06:00
DeFiDude a7515f3f5a api: record reviewed bounded delivery ownership additions 2026-09-08 19:50:07 -06:00
DeFiDude 61f9573bc1 runtime: preserve exact packet admission and Resource wait ownership 2026-09-08 19:45:09 -06:00
DeFiDude c64f0d238a protocol: expose finite Link and Resource owner waits 2026-09-08 19:29:30 -06:00
DeFiDude 3e56135fd8 transport: cancel exact packets awaiting Link admission 2026-09-08 19:28:34 -06:00
DeFiDude 70fe70fbbe transport: invalidate exact failed Links before shared recovery 2026-09-08 19:28:34 -06:00
DeFiDude 9122eba38c runtime: fence initial shared attachment before publishing client 2026-09-08 19:06:01 -06:00
DeFiDude 23045c6a0f transport: report bounded exact Link packet dispatch 2026-09-08 18:54:16 -06:00
DeFiDude f3518ff7c1 transport: bound slow-media relay and recursive discovery lifetimes 2026-09-08 18:34:47 -06:00
DeFiDude e209c8789c android-usb: gate radio writes and retain exact completion ownership 2026-09-08 18:30:50 -06:00
DeFiDude edc3964823 transport: separate exact packet route invalidation from discovery 2026-09-08 18:21:02 -06:00
DeFiDude a90f7e1ec7 transport: retry only unadmitted path request interfaces 2026-09-08 18:10:37 -06:00
DeFiDude ca729453e0 resource: bound request-driven transfer progress and terminal waits 2026-09-08 18:06:37 -06:00
DeFiDude 62e144ed27 transport: admit routed packets before dedup and relay shared radios 2026-09-08 18:05:06 -06:00
DeFiDude 9bc7ee5ff9 tests: accept Windows reset as authenticated-admission cleanup 2026-09-05 22:44:47 -06:00
DeFiDude bd3c1d61ba api: record unique recovery additions in compatibility ledger 2026-09-05 19:27:39 -06:00
DeFiDude 1af490682f api: review exact route recovery and receipt timing additions 2026-09-05 19:14:02 -06:00
DeFiDude f6523fd5c5 transport: track exact packet routes and share canonical receipt timing 2026-09-05 19:08:47 -06:00
DeFiDude 555bb33fdf tests: distinguish RNode socket admission from radio readiness 2026-09-05 18:42:45 -06:00
DeFiDude 9f65990536 transport: recover only the route used by a failed local Link 2026-09-05 18:40:08 -06:00
DeFiDude 8f1d650614 api: qualify zero-hop shared-client interoperability 2026-08-30 17:40:46 -06:00
DeFiDude 67b60362aa transport: keep zero-hop shared-client packets directly addressed 2026-08-30 17:37:09 -06:00
DeFiDude 9a18435b75 api: record reviewed shared-instance ownership surface 2026-08-30 17:34:34 -06:00
DeFiDude 795058e5bf runtime: report interface startup failures and qualify strict sharing 2026-08-30 17:32:08 -06:00
DeFiDude c0fa43664b runtime: add explicit authenticated shared-instance ownership 2026-08-30 17:09:02 -06:00
DeFiDude 3b3eb29c16 runtime: align RNS 1.4.2 utility versions 2026-08-26 21:30:04 -06:00
DeFiDude 6f2a6e8759 docs: promote RNS 1.4.2 release baseline 2026-08-26 20:46:30 -06:00
DeFiDude 7ffefa5b8c channel: enforce upstream receive window 2026-08-26 20:27:19 -06:00
DeFiDude 5b6b5eb951 api: record BLE startup policy 2026-08-23 22:25:20 -06:00
DeFiDude 8fac96aed8 rnode: persist Bluetooth for opted-in BLE clients 2026-08-23 22:24:09 -06:00
DeFiDude 199eeb43cb ci: retain Linux pairing error stages 2026-08-21 03:20:46 -06:00
DeFiDude d3c28b1247 ci: make platform lint deterministic 2026-08-21 03:14:57 -06:00
DeFiDude 1d27e8140b ci: restore Rust 1.87 compatibility 2026-08-21 03:03:51 -06:00
DeFiDude 6705e9804f ble: retain Android RNode traffic across reconnects 2026-08-21 00:31:13 -06:00
DeFiDude ef4b54b0a5 ble: wake RNode reconnect on adapter recovery 2026-08-20 22:08:38 -06:00
DeFiDude 340291f234 ble: support Apple nRF bond transitions 2026-08-20 20:30:17 -06:00
DeFiDude 45bbe47506 transport: acknowledge actual announce enqueue 2026-08-20 17:56:16 -06:00
DeFiDude 041cfbed91 rnode: gate interface traffic on protocol readiness 2026-08-20 16:02:48 -06:00
DeFiDude 8b7e20d5bf ble: bound reconnect generations and preserve queues 2026-08-20 02:24:26 -06:00
DeFiDude 61f625e6ed ble: add non-disruptive radio reassertion 2026-08-20 02:24:20 -06:00
DeFiDude b4c0358beb transport: coalesce queued announce rebroadcasts 2026-08-18 14:57:11 -06:00
DeFiDude 02e1b3f090 rnode: restore upstream-compatible BLE startup 2026-08-18 10:21:17 -06:00
DeFiDude a1639cc065 release: keep maintainer policy internal 2026-08-17 17:08:06 -06:00
DeFiDude e0889f7188 api: organize compatibility evidence 2026-08-17 16:46:21 -06:00
DeFiDude dc6bc4ee82 ci: fetch API history for source qualification 2026-08-17 15:53:47 -06:00
DeFiDude 4a924ce281 release: prepare rsReticulum 1.2.0 2026-08-17 14:57:46 -06:00
DeFiDude ab53670f98 api: require clean snapshot source 2026-08-17 12:52:42 -06:00
DeFiDude 31472d9251 api: bind snapshots to reviewed source 2026-08-17 12:36:12 -06:00
DeFiDude 51763a97dc docs: correct application runtime example 2026-08-17 12:29:35 -06:00
DeFiDude cfb7253f99 api: qualify application prelude contract 2026-08-17 11:41:18 -06:00
DeFiDude c9b210a52b api: record public compatibility baseline 2026-08-17 10:22:38 -06:00
DeFiDude 47dbbf1feb lint: adopt Rust 1.87 integer divisibility 2026-08-17 02:18:41 -06:00
DeFiDude b927f26ca6 release: raise unified MSRV to Rust 1.87 2026-08-17 01:41:12 -06:00
DeFiDude 092cf5ac30 ci: pin source qualification actions 2026-08-17 00:38:54 -06:00
DeFiDude ccf2f11419 release: enforce source qualification contract 2026-08-17 00:10:21 -06:00
DeFiDude d9a1024a16 runtime: own finite announce discovery 2026-08-16 20:13:02 -06:00
DeFiDude bd8c2d8264 transport: isolate announce subscription ownership 2026-08-16 20:05:31 -06:00
DeFiDude b3bcd2b886 docs: distinguish Reticulum reference baselines 2026-08-16 18:41:18 -06:00
DeFiDude 31c5269695 runtime: preserve Rust 1.85 link cleanup syntax 2026-08-16 16:44:10 -06:00
DeFiDude 9300253cee link: keep invalid proof test pending 2026-08-16 16:44:06 -06:00
DeFiDude 0aeb4f02c9 runtime: cancel terminal pending Link binds 2026-08-16 16:31:59 -06:00
DeFiDude f66047e2a2 runtime: drain lifecycle before Link reuse 2026-08-16 16:27:46 -06:00
DeFiDude 3c527bd5cf runtime: fence Link cleanup generations 2026-08-16 16:20:10 -06:00
DeFiDude 2252b83470 transport: release atomic Link destinations on terminal drain 2026-08-16 16:13:35 -06:00
DeFiDude 1d38688b8f runtime: retain ordered Link cleanup ownership 2026-08-16 16:07:10 -06:00
DeFiDude 0049231139 docs: document established Link ownership 2026-08-16 15:41:16 -06:00
DeFiDude d1b5659169 runtime: bind all established Link owners 2026-08-16 15:40:32 -06:00
DeFiDude 2fd604b4aa transport: defer Link cleanup until teardown drains 2026-08-16 15:15:05 -06:00
DeFiDude a9d26472d0 link: ignore unauthenticated proof races 2026-08-16 15:13:54 -06:00
DeFiDude e43fefbc54 transport: drain Link teardown before unbind 2026-08-16 15:09:59 -06:00
DeFiDude e19944f6c1 transport: bound realtime Link egress 2026-08-16 15:00:27 -06:00
DeFiDude 921eac40c2 transport: bind established Links to exact interfaces 2026-08-16 14:56:51 -06:00
DeFiDude f7ae0274c3 link: enforce role-safe packet proofs 2026-08-16 14:54:59 -06:00
DeFiDude fbc2f1938b auto: retry multicast membership joins 2026-08-16 12:43:15 -06:00
DeFiDude 2e0d0a6888 transport: preserve ordered Link delivery outcomes 2026-08-14 13:49:37 -06:00
DeFiDude 6c77c9e69d transport: preserve BLE and Link delivery under pressure 2026-08-13 22:53:30 -06:00
DeFiDude 27352fd0d4 ble: fence reconnect writer leases 2026-08-13 21:58:44 -06:00
DeFiDude fd973420f2 rnode: gate feature-bound admission test 2026-08-13 15:09:01 -06:00
DeFiDude b12f331082 rnode: expose typed capability admission failure class 2026-08-13 14:56:29 -06:00
DeFiDude 04300ecdf4 rnode: admit unprovisioned eeprom images without model bounds 2026-08-13 14:56:17 -06:00
DeFiDude a1b78564e0 resource: bound split payload memory 2026-08-13 12:42:25 -06:00
DeFiDude 70b739988b android: harden native RNode recovery 2026-08-13 05:10:13 -06:00
DeFiDude 140d0aeed4 rncp: settle proven Resources before teardown 2026-08-13 00:44:54 -06:00
DeFiDude ec61a566d3 runtime: harden proof and Link control delivery 2026-08-12 23:58:10 -06:00
DeFiDude 1285e06cf6 ci: install PCSC headers for all-feature lint 2026-08-07 00:12:19 -06:00
DeFiDude bc419b109d ci: enforce strict Clippy across supported targets 2026-08-06 18:49:06 -06:00
DeFiDude eee619ef3b interfaces: align Android USB and RNodeMulti behavior 2026-08-06 14:59:18 -06:00
DeFiDude e47a1d4932 transport: bound control request admission 2026-08-05 13:38:33 -06:00
DeFiDude 07ca72179e runtime: clean Windows shared-instance build 2026-08-02 13:20:46 -06:00
DeFiDude d24e4e3ce3 runtime: simplify resource policy callback type 2026-08-02 01:04:20 -06:00
DeFiDude 869322fa80 transport: route same-runtime links internally 2026-07-28 15:57:03 -06:00
DeFiDude 2bce74c74c transport: document link timeout policy boundary 2026-07-27 03:41:15 -06:00
DeFiDude 8e58e1b708 transport: bound relay link proof lifetime 2026-07-27 03:38:34 -06:00
DeFiDude 7a187a7aa0 transport: centralize pending link proof deadlines 2026-07-27 03:35:46 -06:00
DeFiDude d424c96fa3 runtime: expose responder policy options 2026-07-27 00:09:19 -06:00
DeFiDude 6547f8370d runtime: carry default app data in announces 2026-07-27 00:00:02 -06:00
DeFiDude 740051c41e runtime: allow responder sends while links recover 2026-07-26 23:57:09 -06:00
DeFiDude 04db8c9f46 runtime: make link packet delivery lossless 2026-07-26 23:55:04 -06:00
DeFiDude 9928abed26 runtime: remove closed links from destinations 2026-07-26 23:17:28 -06:00
dude.eth 9e7dd7d9b6 Merge pull request #17 from ratspeak/feature/api-parity
runtime: complete application API parity and RNode hardening
2026-07-26 13:23:13 -06:00
DeFiDude 690c0faf05 tests: await RNode packet accounting completion 2026-07-26 13:17:20 -06:00
DeFiDude 5db4ca3eb5 tests: remove wall-clock delay from RNode fragments 2026-07-26 13:13:29 -06:00
DeFiDude 5d010fb6fb ci: restore MSRV and stabilise RNode preflight test 2026-07-26 13:09:35 -06:00
DeFiDude 7119f8019d release: prepare v1.1.0 2026-07-26 12:53:08 -06:00
DeFiDude df7c8decc1 ci: keep public rustdoc warning-free 2026-07-26 06:57:55 -06:00
DeFiDude 8c8ec46da8 docs: repair public API links 2026-07-26 06:55:43 -06:00
DeFiDude b2068105ae runtime: keep handle-drop shutdown quiet 2026-07-26 04:42:38 -06:00
DeFiDude fb250c7a83 rnsh: register protocol channel types 2026-07-26 04:42:33 -06:00
DeFiDude 52e501fcfc channel: isolate consumer callback panics 2026-07-26 02:19:47 -06:00
DeFiDude dabe75fbb5 link: expose established metric helpers 2026-07-26 02:18:30 -06:00
DeFiDude b9130e6002 identity: isolate persistence test storage 2026-07-26 02:15:47 -06:00
DeFiDude 126d974909 transport: order routing snapshot publication 2026-07-26 02:15:00 -06:00
DeFiDude f9b457d329 transport: reject foreign IFAC ingress 2026-07-26 02:11:21 -06:00
DeFiDude 93c4e3c4b1 runtime: make inbound Resource accounting terminal-safe 2026-07-25 21:02:17 -06:00
DeFiDude 5003e0ec8d runtime: add lossless Link accounting 2026-07-25 20:13:05 -06:00
DeFiDude ed58938c99 runtime: derive Link establishment timing 2026-07-25 19:34:54 -06:00
DeFiDude ac3239d221 runtime: enforce shared control authority 2026-07-25 19:24:09 -06:00
DeFiDude fc97b9931a runtime: stream exact RNode state 2026-07-25 18:25:57 -06:00
DeFiDude e7b76f8272 runtime: expose strict RNode startup options 2026-07-25 18:03:06 -06:00
DeFiDude ba2845e166 rnode: admit Android USB capabilities 2026-07-25 18:02:59 -06:00
DeFiDude f9bb83e089 rnode: admit BLE startup capabilities 2026-07-25 18:02:51 -06:00
DeFiDude 808430d26d rnode: gate startup on validated capabilities 2026-07-25 17:11:38 -06:00
DeFiDude 01fa84bf1f rnode: centralize capability admission 2026-07-25 16:41:27 -06:00
DeFiDude 52998569fb runtime: expose startup RNode observers 2026-07-25 16:20:48 -06:00
DeFiDude 5e310b7069 runtime: return exact observers from RNode spawns 2026-07-25 14:51:09 -06:00
DeFiDude 580ff63224 rnode: validate BLE and USB settings before I/O 2026-07-25 14:51:01 -06:00
DeFiDude 6f24711a38 runtime: expose exact RNode readiness observers 2026-07-25 14:35:53 -06:00
DeFiDude 12b43cebac rnodeconf: verify configuration transactions 2026-07-25 13:56:40 -06:00
DeFiDude 97193439db tools: fix SIGTERM persistence fixture 2026-07-25 13:54:16 -06:00
DeFiDude fb976c4bc3 rnode: restore Rust 1.85 compatibility 2026-07-25 13:51:56 -06:00
DeFiDude 6b79393f58 rnode: share validated radio settings 2026-07-25 13:21:49 -06:00
DeFiDude b9287b7ecf runtime: drain interfaces before transport shutdown 2026-07-25 13:13:00 -06:00
DeFiDude 76410efa50 runtime: retain exact RNode drivers 2026-07-25 12:15:36 -06:00
DeFiDude b671acd51b interface: reclaim rejected accepted children 2026-07-25 11:55:52 -06:00
DeFiDude 2aada8b4db runtime: own interface tasks per instance 2026-07-25 11:42:13 -06:00
DeFiDude 390146247d rnode: request exact driver shutdown 2026-07-25 03:29:48 -06:00
DeFiDude 31632d7a90 rnode: project Android USB lifecycle state 2026-07-25 03:12:35 -06:00
DeFiDude 4146eeb743 rnode: own Android USB teardown deterministically 2026-07-25 02:53:33 -06:00
DeFiDude 60a3b72146 rnode: expose native BLE lifecycle observations 2026-07-25 01:31:16 -06:00
DeFiDude 4e1abca4ea tools: share RNode capability inspection 2026-07-25 01:28:53 -06:00
DeFiDude b1854b62aa rnode: add bounded EEPROM capability parser 2026-07-25 01:14:33 -06:00
DeFiDude b59e8849a7 rnode: expose desktop BLE lifecycle observations 2026-07-25 01:10:24 -06:00
DeFiDude 88d3d38277 rnode: restore TCP application idle probes 2026-07-25 00:46:32 -06:00
DeFiDude b2aee9dc2c rnode: consume flow permits at write boundary 2026-07-25 00:14:16 -06:00
DeFiDude ba4ee2881f rnode: serialize generation writes and teardown 2026-07-24 23:50:28 -06:00
DeFiDude d6c3a010c0 rnode: project protocol readiness into driver state 2026-07-24 22:54:38 -06:00
DeFiDude 3cccd8c7b0 rnode: preserve negative protocol observations 2026-07-24 22:33:23 -06:00
DeFiDude 74eb9949cb rnode: expose local driver lifecycle snapshots 2026-07-24 22:24:58 -06:00
DeFiDude 731fddcf73 rnode: validate generic radio configuration 2026-07-24 22:04:54 -06:00
DeFiDude 6f43913a6c tools: render Backbone inspection counts 2026-07-24 21:37:56 -06:00
DeFiDude 987cc947c7 runtime: expose aggregate Backbone inspection stats 2026-07-24 21:35:30 -06:00
DeFiDude 1c7a0ea035 rnode: add deterministic protocol reducer 2026-07-24 21:19:19 -06:00
DeFiDude aeeb3c1ab9 backbone: block fast-flapping clients 2026-07-24 21:16:46 -06:00
DeFiDude 7100021b75 discovery: align RNS 1.4 defaults 2026-07-24 20:51:25 -06:00
DeFiDude 59d59d335a transport: adopt canonical raw packet hashlist 2026-07-24 20:51:12 -06:00
DeFiDude e3bb3d171f discovery: bound stamp validation load 2026-07-24 20:35:52 -06:00
DeFiDude 0362446b74 rnode: preserve Android USB control frames 2026-07-24 20:25:19 -06:00
DeFiDude 2ec94069a4 link: preserve asymmetric keepalive liveness 2026-07-24 20:15:50 -06:00
DeFiDude bb7395b284 packet: centralize destination-aware packing 2026-07-24 19:22:11 -06:00
DeFiDude 4ae8638b3e destination: own persistent ratchet runtime 2026-07-24 19:05:25 -06:00
DeFiDude 69d9e8a5b5 packet: add resend and receipt controls 2026-07-24 18:44:53 -06:00
DeFiDude 06a9bdd63f link: expose live physical metrics 2026-07-24 18:25:48 -06:00
DeFiDude ca9bcae376 api: close compatibility surface gaps 2026-07-24 18:07:41 -06:00
DeFiDude 2be764308e runtime: close responder handshake races 2026-07-24 15:22:26 -06:00
DeFiDude a72c1215c1 build: enforce Rust 1.85 API gates 2026-07-24 13:11:03 -06:00
DeFiDude a788ab984a link: expire zero-duration requests immediately 2026-07-24 12:51:47 -06:00
DeFiDude 2a67960f1d runtime: add build-checked API examples 2026-07-24 12:42:07 -06:00
DeFiDude 8370a1be66 runtime: own inbound destination lifecycles 2026-07-24 12:16:51 -06:00
DeFiDude 30b40d8333 runtime: route large link requests through resources 2026-07-24 12:09:32 -06:00
DeFiDude a319855c62 runtime: add destination Link connector 2026-07-24 11:48:46 -06:00
DeFiDude ee2b882a50 destination: report announce preconditions 2026-07-24 11:44:21 -06:00
DeFiDude 24b3dc3cbc runtime: pin responder links to interfaces 2026-07-24 11:40:40 -06:00
DeFiDude acc0a3f93b transport: expose next-hop link metrics 2026-07-24 11:38:02 -06:00
DeFiDude e663260b11 transport: expose path request options 2026-07-24 11:32:06 -06:00
DeFiDude 69fa830d52 runtime: apply forced shared-instance bitrate 2026-07-24 11:26:13 -06:00
DeFiDude d406d76b35 transport: use path response on shared registration 2026-07-24 11:19:04 -06:00
DeFiDude 9eed85392e runtime: align cache cleanup lifetimes 2026-07-24 11:16:59 -06:00
DeFiDude 82195eb2de runtime: dispatch destination request handlers 2026-07-24 11:13:52 -06:00
DeFiDude 1562d72ce1 link: expose plaintext request parsing 2026-07-24 10:59:47 -06:00
DeFiDude 8ae733e68a runtime: expose live Destination controls 2026-07-24 10:54:05 -06:00
DeFiDude 9b64aea819 runtime: add explicit shared-instance init options 2026-07-24 10:51:16 -06:00
DeFiDude d9f510a5ad destination: complete library API helpers 2026-07-24 10:43:44 -06:00
DeFiDude cd816bee68 identity: expose ratchet decryption metadata 2026-07-24 10:37:07 -06:00
DeFiDude 10ec9e9b3e runtime: activate Destination packet dispatch 2026-07-24 07:55:18 -06:00
DeFiDude 4830142458 runtime: add owned announce subscriptions 2026-07-24 07:40:58 -06:00
DeFiDude dfe42f2194 transport: honor unfiltered announce deregistration 2026-07-24 07:31:00 -06:00
DeFiDude 2bf531180e runtime: add channel-backed Buffer streams 2026-07-24 07:28:32 -06:00
DeFiDude f284317d8d channel: expose outbound drain state 2026-07-24 07:19:16 -06:00
DeFiDude e15466bfb8 runtime: expose responder resource lifecycle 2026-07-24 07:14:34 -06:00
DeFiDude 226f4fa800 runtime: expose responder resource policy 2026-07-24 07:02:12 -06:00
DeFiDude a1ca1daa39 runtime: add inbound Link resource offers 2026-07-24 06:54:08 -06:00
DeFiDude 062170c541 runtime: add Link session resource lifecycle 2026-07-24 06:22:11 -06:00
DeFiDude 8777f62a38 runtime: expose reliable Link session channels 2026-07-24 05:40:11 -06:00
DeFiDude 8645fdfacd channel: complete handler and MDU semantics 2026-07-24 05:24:07 -06:00
DeFiDude b9819d3d66 runtime: add Link session request API 2026-07-24 05:17:25 -06:00
DeFiDude 4220b8d3d7 runtime: add tracked packet send API 2026-07-24 05:06:14 -06:00
DeFiDude e5cbded53f wire: distinguish packet and Link payload limits 2026-07-24 04:54:37 -06:00
DeFiDude 8a8256cf1c runtime: expose typed interface stats 2026-07-24 04:35:16 -06:00
DeFiDude 1605709a48 runtime: add typed path queries 2026-07-24 04:31:40 -06:00
DeFiDude a945ba0744 runtime: add keyed destination recall 2026-07-24 04:24:25 -06:00
DeFiDude 0c71ce1e09 runtime: drive resource watchdogs 2026-07-24 04:17:06 -06:00
DeFiDude d986749660 resource: retry lost advertisements 2026-07-24 04:11:59 -06:00
DeFiDude 065741d22b link: drive request receipt lifecycle 2026-07-24 04:10:34 -06:00
DeFiDude 6e12be1489 interface: reconnect Unix shared clients 2026-07-24 04:05:32 -06:00
DeFiDude ea9163338f runtime: await orderly signal shutdown 2026-07-24 03:58:56 -06:00
DeFiDude a9d3d7998f transport: authenticate delivery proofs 2026-07-24 03:48:23 -06:00
DeFiDude 25c5e448cf runtime: test stale link heartbeat recovery 2026-07-23 13:26:12 -06:00
DeFiDude 9b909c2093 runtime: pin persistent links to proof interface 2026-07-23 12:30:47 -06:00
DeFiDude d90f9390ca runtime: allow packets while links recover 2026-07-23 11:45:06 -06:00
DeFiDude 739e30d3da rnsh: preserve live authorization semantics 2026-07-21 21:26:33 -06:00
DeFiDude 44d8a13c62 rnid: register one-shot announce destinations 2026-07-21 20:30:20 -06:00
DeFiDude e8819edc3c runtime: add persistent application Link sessions 2026-07-21 18:52:08 -06:00
DeFiDude 3f8feb169c rnode: fix battery and temperature decoding 2026-07-21 16:28:09 -06:00
DeFiDude a79b9b3210 runtime: satisfy strict link cleanup lint 2026-07-21 13:28:17 -06:00
DeFiDude 8ac58e5f5e identity: replace state atomically on Windows 2026-07-20 17:33:42 -06:00
DeFiDude 670875008d identity: expose exact tagged path responses 2026-07-20 17:23:58 -06:00
DeFiDude f853086237 identity: make ratchet rotation crash-safe 2026-07-20 17:15:04 -06:00
DeFiDude 36fcfeb953 identity: verify atomic state persistence 2026-07-20 16:59:12 -06:00
DeFiDude 7267bd4f69 identity: preserve ratchet flag in path-response cache 2026-07-20 16:55:53 -06:00
DeFiDude 4095022ea6 rnsh: harden listener state model and add auth-bypass regression tests 2026-07-19 13:28:39 -06:00
DeFiDude c4c9f14448 runtime: gate request-resources, tear down invalid advertisements, route HMU cancels 2026-07-19 13:28:39 -06:00
DeFiDude 141a6e8889 resource: gate solicited HMUs and cancel on empty or invalid updates 2026-07-19 13:28:39 -06:00
DeFiDude 4509145b70 link: enforce first-verified-identity-wins on established links 2026-07-19 13:28:39 -06:00
DeFiDude 17e6107aa8 interface: refresh ble_peer module doc — no ID characteristic 2026-07-18 19:58:02 -06:00
DeFiDude c4b1301e6f interface: drop vestigial ble_peer feature alias (ble gates all BLE deps) 2026-07-17 08:38:48 -06:00
DeFiDude c65ce4c430 ratkey: drop internal hardware status ledger from the public tree 2026-07-17 08:38:11 -06:00
DeFiDude 27e6d03235 docs: retarget README to Reticulum 1.3.8 2026-07-17 08:38:11 -06:00
DeFiDude 6c8dba7dd4 tools: bump emulated Reticulum compat version to 1.3.8 2026-07-15 20:39:49 -06:00
DeFiDude 87ac41d93c style: rustfmt 2026-07-15 19:06:26 -06:00
DeFiDude ef1ff3f90c parity: 1.3.8 wave 3 — local_hops_delta (1.3.7 semantics) + logtimestamps in all binaries 2026-07-15 13:35:38 -06:00
DeFiDude 0baf1b4ad6 parity: 1.3.8 wave 2 — msgpack shared-instance RPC, config plumbing for new interface/identity/blackhole/logging keys, rnstatus monitor+internal mode 2026-07-15 12:40:20 -06:00
DeFiDude 3c1b43d8f6 parity: 1.3.8 wave 1 — transport announce/hop/mode/identity/blackhole, link stats, weave board-init, rnid signed messages 2026-07-15 11:18:41 -06:00
DeFiDude 46b699af1f tools: align prettysize output and rnprobe/rnpath default waits with Python, refresh README usage 2026-07-10 18:10:09 -05:00
DeFiDude 7d38b3f8d9 transport: prune on-disk announce cache against live references 2026-07-10 01:36:39 -05:00
DeFiDude 05f38400b9 runtime: inherit listener IFAC on accepted server children 2026-07-09 23:48:08 -05:00
DeFiDude 4aa505a7b6 interface: clear linux ble_peer clippy lints 2026-07-09 21:35:56 -05:00
DeFiDude 4afefd6bba interface: gate poll_read behind serial feature 2026-07-09 21:27:19 -05:00
DeFiDude 7e178ce8c4 test(rns-runtime): supply multipoint arg at interface registration test sites 2026-07-02 23:24:32 -06:00
DeFiDude ceafedd4ee style(ble-peer): rustfmt normalize 2026-07-02 02:08:02 -06:00
DeFiDude cbb0fc83bc feat(ble-peer): cross-platform mesh peer disconnect helper 2026-07-01 21:51:47 -06:00
DeFiDude 2336f166d7 chore: update Cargo.lock for rns-interface rns-identity dep 2026-07-01 21:47:19 -06:00
DeFiDude 011da1459c perf(ble-peer): scan/fan-out robustness pass
- RSSI-sort connect candidates so crowded rooms fill slots with nearest peers
- idle scan cadence when no actionable (unconnected/non-backoff) peer remains
- fan-out uses try_send so one slow peer can't head-of-line-block the broadcast
- bound per-peer btleplug writes with a timeout
- prune finished per-peer task handles instead of growing the vec per reconnect
- run blocking Android JNI disconnects off the async runtime
2026-07-01 21:47:11 -06:00
DeFiDude fade1f2e47 fix(ble-peer): stop advertising plaintext app name on Linux 2026-07-01 21:39:42 -06:00
DeFiDude 5e213f75cf fix(ble-peer): drop static identity-hash GATT read (MAC-rotation tracking vector) 2026-07-01 21:39:17 -06:00
DeFiDude a5ab014510 fix(ble-peer): bind peer identity only from a signature-verified announce 2026-07-01 21:30:53 -06:00
DeFiDude 198564c65d fix(ble-peer): engage backoff on connect-drop churn; stop rotation misclassification
Generic remote disconnects were classified as RPA rotation and cleared the
reconnect backoff on every drop; a churn tracker now backs off peers that keep
connecting and dropping within the stability window.
2026-07-01 21:22:59 -06:00
DeFiDude 24fc3e2912 fix(ble-peer): preserve Apple write order under radio backpressure 2026-07-01 21:16:03 -06:00
DeFiDude 20ad6061d8 fix(ble-peer): size writes to the real MTU to stop silent truncation
Apple central now reads maximumWriteValueLengthForType: (fixes truncation on
smaller-MTU links and unlocks larger writes); btleplug drops to the iOS-safe
182-byte floor since it exposes no MTU getter and there is no length field.
2026-07-01 21:14:24 -06:00
DeFiDude 7fb33dc83d fix(ble-peer): track real interface online state for transport + Halt/Resume 2026-07-01 21:11:39 -06:00
DeFiDude f2751f4b57 fix(transport): relay announces among peers of a multipoint interface
BLE Peer presents many hidden-from-each-other GATT links as one interface;
without back-out relay a hub never propagates announces between its peers,
breaking multi-hop discovery past two nodes.
2026-07-01 21:09:07 -06:00
DeFiDude 7d5ee2121d docs(ble-peer): correct false anti-loop claim on desktop notify legs 2026-07-01 21:02:49 -06:00
DeFiDude 1f6865c996 fix(ble-peer): correct central-role teardown (reset Apple scan lifecycle, disconnect desktop GATT links) 2026-07-01 20:59:48 -06:00
DeFiDude 753b49b83c fix(ble-peer): re-settable Apple peripheral manager across enable cycles 2026-07-01 20:49:30 -06:00
DeFiDude e9169eecbd fix(ble-peer): cap fragment reassembly total to bound memory use 2026-07-01 20:46:50 -06:00
DeFiDude 6d2b284753 ci: run BLE feature tests on macOS 2026-07-01 19:32:34 -06:00
DeFiDude 468d330322 transport: deflake periodic-save test by modeling tick retry 2026-07-01 19:08:06 -06:00
DeFiDude be3ac91d8a protocol: fix resource window-grow underflow after demote-then-promote 2026-07-01 18:48:25 -06:00
DeFiDude 936f19a200 docs: update Reticulum compatibility target 2026-07-01 01:57:31 -06:00
DeFiDude b9522bfab1 rnode: avoid duplicate BLE airtime init 2026-06-30 20:06:25 -06:00
DeFiDude e6dd6b3ab3 rnode: reset radio before init sequence 2026-06-17 10:30:01 -06:00
DeFiDude 3b91b36f3e runtime: group backbone IFAC spawn options 2026-06-13 23:27:57 -06:00
DeFiDude 3d7b989262 release: bump rsReticulum to 1.0.1 2026-06-13 23:21:14 -06:00
DeFiDude fdfbf09515 tools: report package version from CLIs 2026-06-13 23:12:57 -06:00
DeFiDude 5bfbcef47f runtime: add IFAC spawn support 2026-06-13 22:54:25 -06:00
DeFiDude 117f32e03e ci: satisfy release branch clippy 2026-06-13 21:51:02 -06:00
DeFiDude 07f0ecd900 release: align crates at 1.0.0 2026-06-13 21:40:21 -06:00
DeFiDude 4b8bc21a9b style: rustfmt transport cleanup 2026-06-13 19:56:34 -06:00
DeFiDude 6638c80c55 transport: skip path requests for outbound proofs 2026-06-13 19:56:20 -06:00
DeFiDude d2ad997caf rnode: trace queued packet writes 2026-06-13 19:56:08 -06:00
DeFiDude d8ff9f85b7 transport: disk-backed announce cache, 5-min state flush, cleanup linger parity 2026-06-12 11:50:14 -06:00
DeFiDude 069b653ee6 ble: run pairing read before subscribe on Android 2026-06-10 21:25:37 -06:00
DeFiDude 4158c5a8a9 transport: move periodic and falling-edge state flushes off the actor 2026-06-10 13:49:10 -06:00
DeFiDude ed66c62468 tools: register rncp and rnsh signal handlers before runtime init 2026-06-10 12:27:16 -06:00
DeFiDude f5ec2fb16f lifecycle: register SIGINT handler synchronously; de-flake listener signal tests 2026-06-10 04:34:46 -06:00
DeFiDude 01d0bb411b perf: gate debug hex in auto hot paths, snapshot peer fan-out, persistent rnsd log handle, single-pass receipt cull 2026-06-10 00:04:29 -06:00
DeFiDude 41587f80de interface, ratkey: remove dead trait and constants, wire pin re-verify with zeroized buffers 2026-06-09 23:57:12 -06:00
DeFiDude 83710bc24a runtime: extract shared-instance client adoption helper 2026-06-09 23:45:22 -06:00
DeFiDude 69b5f40d2d local: shared stream wiring for unix and tcp-fallback variants 2026-06-09 23:43:16 -06:00
DeFiDude 7d749a4f8b link: collapse prove and identify variants onto fallible cores 2026-06-09 23:40:02 -06:00
DeFiDude 51f4e56002 interface: shared blocking serial io shuttles 2026-06-09 23:38:04 -06:00
DeFiDude 72e49affa0 kiss: classic deframer delegates to raw engine 2026-06-09 23:33:04 -06:00
DeFiDude 8ead1d477c interface: generic socket tuning helpers over raw fd borrow 2026-06-09 23:31:43 -06:00
DeFiDude b27a7ce69f i2p: consolidate reconnect backoff into pacer and dereg on give-up 2026-06-09 23:29:38 -06:00
DeFiDude 5460f013f8 transport, tools: consolidate now_f64 and compat-version constants 2026-06-09 23:26:56 -06:00
DeFiDude 442c9441a0 runtime: validate config ports and ifac_size, wire udp device, dereg tcp on initial give-up 2026-06-09 23:21:36 -06:00
DeFiDude a5dcd3caf7 interface: flip shared online flag on deregister and scope rnode-multi subs independently 2026-06-09 23:14:45 -06:00
DeFiDude 8a41710550 tcp: apply tuned keepalive and user timeout on client, accepted, and i2p sockets 2026-06-09 23:03:59 -06:00
DeFiDude 3fd3fa9077 rnode: apply RSSI offset when decoding signal stats 2026-06-09 22:59:37 -06:00
DeFiDude 2262f9ee7e transport: route table persistence through shared fsync atomic-write helper 2026-06-09 22:56:53 -06:00
DeFiDude f0b564be0b protocol: bound hashmap-update segment writes by total_parts 2026-06-09 22:54:32 -06:00
DeFiDude 366ca6f02a protocol: bound inbound resource part count against advertised size 2026-06-09 22:52:16 -06:00
DeFiDude ac98369011 auto: tolerate transient recv errors in discovery and data loops 2026-06-09 20:58:34 -06:00
DeFiDude 849c23e624 ble: update rnode tests for init-sequence airtime and flow-control parity 2026-06-09 18:28:06 -06:00
DeFiDude db47d10d5a lint: rustfmt and clippy cleanup 2026-06-09 18:21:53 -06:00
DeFiDude a5f06b6d00 interfaces: config-key parity, station-ID beacons, explicit radio params 2026-06-09 17:45:05 -06:00
DeFiDude b0cfa3be78 identity: derive Clone/Copy on ReceivedRatchet 2026-06-09 17:45:05 -06:00
DeFiDude 72ad363435 runtime: support live RNode interface modes 2026-06-08 18:17:01 -06:00
DeFiDude bb2c1eab65 ble: satisfy peer feature clippy 2026-06-03 23:58:52 -06:00
DeFiDude 21aa4f6308 ble: redundantly fan out proof packets 2026-06-03 23:07:22 -06:00
DeFiDude f9b407ef5a ble: suppress peer role collisions 2026-06-03 20:50:46 -06:00
DeFiDude 924d27f4b1 interface: expose Android BLE availability 2026-06-03 15:53:17 -06:00
DeFiDude 36706c1eff interface: emit BLE peer status events 2026-06-03 15:46:14 -06:00
DeFiDude 5a0ea04ad0 runtime: seed BLE reconnects by address 2026-06-03 15:41:15 -06:00
DeFiDude 104f425b4f interface: prefer single BLE peer path 2026-06-03 15:34:48 -06:00
DeFiDude c3b75f7577 interface: key BLE peer writers 2026-06-03 15:31:37 -06:00
DeFiDude c460a7c9d4 interface: reset BLE peer sessions cleanly 2026-06-03 15:26:31 -06:00
DeFiDude 27f901ec5d tests: move interop generator to harness 2026-05-30 21:07:59 -06:00
DeFiDude ab529e875c runtime: support legacy Python RPC auth 2026-05-30 20:37:08 -06:00
DeFiDude 7942aee235 tests: track Python artifact generator 2026-05-30 17:24:06 -06:00
DeFiDude cd58bbc0ac ratkey: satisfy clippy 2026-05-29 23:52:58 -06:00
DeFiDude 4ee47d40ac style: apply rustfmt 2026-05-29 23:49:09 -06:00
DeFiDude a8daa46958 ratkey: switch recoverable phrases to 12 words 2026-05-29 22:52:53 -06:00
DeFiDude eeb3e4589a ratkey: add PIV PIN recovery support 2026-05-29 22:38:34 -06:00
DeFiDude 132d7a2d79 runtime: route backend link signing 2026-05-29 20:28:47 -06:00
DeFiDude 27beef4564 ratkey: extract testable APDU response-chaining fn + unit tests 2026-05-29 19:24:41 -06:00
DeFiDude 6cd28f0337 ratkey: hardware-validate attestation chain (on-card ATTEST + F9 fetch, response chaining, hw attest) 2026-05-29 19:18:26 -06:00
DeFiDude 4f011314d4 ratkey: document recovery-phrase re-display (persisted, protection tracks the key) 2026-05-29 18:59:49 -06:00
DeFiDude 88677cef2f ratkey: implement TDES (3DES EDE3) management keys for pre-5.7 YubiKeys 2026-05-29 18:41:43 -06:00
DeFiDude 6181a18254 ratkey: document recoverable-identity model (seed-restore, mnemonic create, passcode vault) 2026-05-29 16:15:18 -06:00
DeFiDude dda2470987 ratkey: document desktop-only release scope + mobile/seed-restore plan 2026-05-29 14:52:35 -06:00
DeFiDude 6c9792846e ratkey: add backend lock() to drop the on-card PIN cache 2026-05-29 10:37:52 -06:00
DeFiDude cc8927f0f9 ratkey: provision_hardware_only + read_existing helpers
Shared finalize_provision builds the .hwid for all real flows; provision_hardware_only generates on-device, read_existing registers an already-provisioned token.
2026-05-29 00:26:17 -06:00
DeFiDude a4083bd4fe ratkey: PIV key import + recoverable provisioning/restore
IMPORT ASYMMETRIC KEY APDU (Ed25519 tag 0x07 / X25519 0x08) + PivSession import methods (mgmt-key gated). provision_recoverable derives from a fresh 24-word phrase and imports both keys; restore does the same from an existing phrase. Mirrors ratkey-py's import path.
2026-05-29 00:07:25 -06:00
DeFiDude ad279dfb67 ratkey: BIP-39 seed-phrase identity derivation
24-word mnemonic -> deterministic Reticulum identity (scheme v1: PBKDF2-SHA512 seed -> HKDF-SHA256), verified byte-for-byte against ratkey-py. Foundation for recoverable hardware-key backup.
2026-05-29 00:01:44 -06:00
DeFiDude 1c63de4e0f rns-runtime: optional link signing key for hardware identities
LinkManager::with_destination takes Option<Ed25519PrivateKey>; hardware identities pass None (link-mode packet proofs skip until routed through the backend, TODO). Software callers wrap Some(...). Opportunistic delivery is unaffected.
2026-05-28 23:19:38 -06:00
DeFiDude a475caf407 ratkey: Identity LocalKeyBackend seam + hardware-backed identity
Identity gains an optional LocalKeyBackend (Ed25519 sign + X25519 ECDH delegation, used only when the in-memory key is absent; None for software identities, so wire output is unchanged). rns-ratkey HardwareBackend runs the PIV session on a card-service thread (Send+Sync) and load_hardware_identity builds an Identity::from_backend. Backend-aware Identity::clone keeps both clone_identity sites working for hardware (Arc-shared) without extracting a private key.
2026-05-28 23:10:52 -06:00
DeFiDude f6afe585ce ratkey: X.509 attestation chain verification
RSA PKCS#1 v1.5 chain from the per-key/F9 attestation certs to a fingerprint-pinned Yubico root (legacy + new-PKI A/B/B2 intermediates bundled) with validity-window checks. chain_verified is set only on a real signature verification; no revocation/OCSP/name-constraints. Pending validation against a physical device's ATTEST output.
2026-05-28 23:10:52 -06:00
DeFiDude 4623436c93 ratkey: PIV management-key auth for on-device provisioning
Witness/challenge mutual auth on slot 9B (AES-128/192/256; 5.7 default is AES-192) gates GENERATE, so hw provision now creates keys on-device. TDES (pre-5.7) left as a TODO. Validated end-to-end on a YubiKey 5.7.4.
2026-05-28 22:20:56 -06:00
DeFiDude fac4dc870d ratkey: PivTransport seam; back HardwareIdentity by real PIV session
PivSession<T> is transport-agnostic (PC/SC behind `hardware`); HardwareIdentity holds Box<dyn IdentityBackend>, ending the mock-only runtime and leaving room for a mobile transport. hw provision still lacks PIV management-key auth.
2026-05-28 21:59:37 -06:00
dude.eth 4e427a7ad5 Merge pull request #7 from kujeger/bzip2_vers
update bzip2 depencency
2026-05-28 20:18:06 -06:00
Nikolai Vincent Vaags a65fd2097f update bzip2 depencency
bzip2 0.6 (latest) is also fully in rust, making it easier to cross-compile.
2026-05-28 15:28:49 +02:00
DeFiDude 26e4919ce1 transport: align announce replay with upstream 2026-05-26 19:45:10 -06:00
DeFiDude bfb4bb4e14 transport: stop shared client announce replay 2026-05-26 19:19:05 -06:00
DeFiDude 8263bfbf4a tests: cover shared instance lifecycle edges 2026-05-24 23:51:37 -06:00
DeFiDude da56d5559a runtime: harden shared instance lifecycle 2026-05-24 22:59:36 -06:00
dude.eth 6e11324b6b Merge pull request #5 from strijar/fix/rnsd_log
Disable ansi for log file
2026-05-24 12:20:20 -06:00
Belousov Oleg b89e434a00 Disable ansi for log file 2026-05-20 15:34:16 +03:00
284 changed files with 131469 additions and 13944 deletions

No files matched your search

+71 -13
View File
@@ -10,6 +10,34 @@ permissions:
contents: read
jobs:
api-compat:
name: Public API baseline
runs-on: macos-15
timeout-minutes: 45
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
fetch-depth: 0
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: nightly-2026-08-01
targets: aarch64-apple-darwin
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
cache-bin: true
- name: Install API snapshot tool
run: cargo install cargo-public-api --version 0.52.0 --locked
- name: Check reviewed public API baseline
run: python3 tools/check-api-baseline.py
- name: Check manifest and feature contract
run: python3 tools/check-api-manifest.py
- name: Check additions-only compatibility floor
run: python3 tools/check-api-compatibility.py
- name: Check canonical and legacy external consumer
run: |
cargo check --manifest-path api/fixtures/Cargo.toml --locked
cargo check --manifest-path api/fixtures/Cargo.toml --all-features --locked
test:
name: Test (${{ matrix.os }})
timeout-minutes: 30
@@ -19,31 +47,61 @@ jobs:
os: [ubuntu-latest, macos-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: 1.96.0
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
cache-bin: false
- name: Install system deps (Linux)
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev libpcsclite-dev pkg-config
- name: Test (default features)
run: cargo test --workspace
- name: Test BLE interface features (Linux)
if: runner.os == 'Linux'
run: cargo test -p rns-interface --features ble,ble_peer
run: cargo test --workspace --locked
- name: Build application examples
run: cargo build -p rns-runtime --examples --locked
- name: Test BLE interface features
run: cargo test -p rns-interface --features ble --locked
lint:
name: Lint
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
fetch-depth: 0
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: 1.96.0
components: clippy, rustfmt
- name: Install system deps
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev libpcsclite-dev pkg-config
- name: Check source-release contract
run: python3 scripts/ci/check_source_release_contract.py
- run: cargo fmt --all -- --check
- run: cargo clippy --workspace --all-targets -- -D warnings
- run: cargo clippy -p rns-interface --features ble,ble_peer --all-targets -- -D warnings
- run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
- name: Check public API documentation
env:
RUSTDOCFLAGS: "-D warnings"
run: cargo doc --workspace --no-deps --locked
- run: cargo check --workspace --no-default-features --locked
msrv:
name: Rust 1.89 MSRV
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: 1.89.0
components: clippy
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
cache-bin: false
- name: Install system deps
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev libpcsclite-dev pkg-config
- name: Clippy (all targets and features)
run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
+84 -15
View File
@@ -7,20 +7,55 @@ on:
workflow_dispatch:
inputs:
tag_name:
description: "Release tag to create or update"
description: "Version tag (also used for untagged qualification)"
required: true
qualify_only:
description: "Build and verify archives without publishing or creating a tag"
type: boolean
default: true
required: true
permissions:
contents: read
actions: read
env:
SOURCE_REF: ${{ github.sha }}
RELEASE_TAG: ${{ github.event.inputs.tag_name || github.ref_name }}
PACKAGE_ROOT: rsReticulum
RETICULUM_BINS: rnsd-rs rnstatus-rs rnpath-rs rnid-rs rnprobe-rs rncp-rs rnsh-rs rnodeconf-rs
jobs:
verify:
name: Verify release source
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
ref: ${{ env.SOURCE_REF }}
fetch-depth: 0
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: 1.89.0
- shell: bash
env:
GH_TOKEN: ${{ github.token }}
QUALIFY_ONLY: ${{ github.event_name == 'workflow_dispatch' && inputs.qualify_only }}
run: |
set -euo pipefail
test "$(git rev-parse HEAD)" = "${SOURCE_REF}"
gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/ci.yml/runs?head_sha=${SOURCE_REF}&event=push&per_page=100" \
--jq '.workflow_runs | any(.head_sha == env.SOURCE_REF and .conclusion == "success")' | grep -qx true
if [[ "${QUALIFY_ONLY}" == "true" ]]; then
python3 scripts/ci/check_source_release_contract.py --candidate-tag "${RELEASE_TAG}"
else
python3 scripts/ci/check_source_release_contract.py --release-tag "${RELEASE_TAG}"
fi
build:
name: Build ${{ matrix.artifact_suffix }}
needs: verify
timeout-minutes: 30
strategy:
fail-fast: false
@@ -39,22 +74,29 @@ jobs:
env:
ARCHIVE_NAME: rsReticulum-${{ github.event.inputs.tag_name || github.ref_name }}-${{ matrix.artifact_suffix }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
ref: ${{ env.RELEASE_TAG }}
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
ref: ${{ env.SOURCE_REF }}
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: 1.89.0
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
cache-bin: false
- name: Install system deps (Linux)
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- name: Build release binaries
run: cargo build -p rns-tools --release --bins
run: cargo build -p rns-tools --release --bins --locked
- name: Stage archive contents
shell: bash
run: |
set -euo pipefail
for bin in ${RETICULUM_BINS}; do
suffix=""
if [[ "${RUNNER_OS}" == "Windows" ]]; then suffix=".exe"; fi
"target/release/${bin}${suffix}" --version
done
mkdir -p "dist/${PACKAGE_ROOT}/bin"
for bin in ${RETICULUM_BINS}; do
if [[ "${RUNNER_OS}" == "Windows" ]]; then
@@ -63,7 +105,10 @@ jobs:
cp "target/release/${bin}" "dist/${PACKAGE_ROOT}/bin/${bin}"
fi
done
cp README.md LICENSE "dist/${PACKAGE_ROOT}/"
# Read blobs directly so Windows checkout line endings cannot alter the package.
for doc in README.md LICENSE CHANGELOG.md; do
git show "HEAD:${doc}" > "dist/${PACKAGE_ROOT}/${doc}"
done
- name: Create tar archive
if: runner.os != 'Windows'
shell: bash
@@ -72,7 +117,7 @@ jobs:
if: runner.os == 'Windows'
shell: pwsh
run: Compress-Archive -Path "dist/${env:PACKAGE_ROOT}" -DestinationPath "${env:ARCHIVE_NAME}.zip" -Force
- uses: actions/upload-artifact@v7
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: ${{ env.ARCHIVE_NAME }}
path: |
@@ -80,22 +125,46 @@ jobs:
*.zip
if-no-files-found: error
package:
name: Verify release archives
needs: build
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
ref: ${{ env.SOURCE_REF }}
- uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
with:
pattern: rsReticulum-*
path: release-assets
merge-multiple: true
- name: Verify archive inventory and generate checksums
run: python3 scripts/ci/check_release_archives.py --tag "${RELEASE_TAG}" --directory release-assets
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: verified-release-assets
path: release-assets/*
if-no-files-found: error
publish:
name: Publish GitHub release
needs: build
if: github.event_name == 'push' || !inputs.qualify_only
needs: package
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/download-artifact@v7
- uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
with:
name: verified-release-assets
path: release-assets
merge-multiple: true
- name: Generate checksums
working-directory: release-assets
run: sha256sum * > SHA256SUMS
- uses: softprops/action-gh-release@v3
- uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3
with:
tag_name: ${{ env.RELEASE_TAG }}
name: ${{ env.RELEASE_TAG }}
body: ""
generate_release_notes: false
append_body: false
prerelease: ${{ contains(env.RELEASE_TAG, '-') }}
files: release-assets/*
+4 -1
View File
@@ -6,4 +6,7 @@ __pycache__/
/interop_artifacts/
/rust_artifacts/
proptest-regressions/
/tools/
/tools/*
!/tools/check-api-manifest.py
!/tools/check-api-compatibility.py
/api/fixtures/target/
+136
View File
@@ -0,0 +1,136 @@
# Changelog
## Unreleased
## 1.4.0 - 2026-11-08
- RNode drivers confirm the settings the radio applies once it is on, on every transport, and stop with the rejected setting named (for example TX power below an amplifier's minimum) instead of transmitting at other settings or retrying forever.
- Serial and TCP RNodes keep retrying a port that is missing, busy or not permitted every 5 seconds, as in Python Reticulum, and report which.
- Android Bluetooth RNode sessions wait for the bridge before starting, so a slow reconnect no longer drops a healthy link.
- Interface status reports IFAC like Python Reticulum: `rnstatus-rs` shows the network name and access line only for interfaces that use IFAC.
- Interfaces start only when `enabled` or `interface_enabled` is yes, as in Python Reticulum. A section with neither key is now skipped with a warning instead of starting, so add `enabled = yes` to it. An RNodeMulti subinterface with its own flag follows that flag, so a subinterface set to no never transmits.
- Durable storage works on any filesystem again, as in Python Reticulum, including ZFS, Docker overlays, external drives and network shares. A flush the filesystem lacks is skipped and logged once, and network or RAM-backed storage logs a warning instead of refusing to start.
- A Link accepts the peer's identification as soon as its handshake completes, as in Python Reticulum, so a request a Python client sends right after identifying no longer fails for lack of an identity. Only the receiving side of a Link accepts identification.
- The receiving side of a Link counts its Link proof as sent traffic, as in Python Reticulum, so it no longer answers keepalives before the Link is established and its traffic totals include the proof.
- A connectable I2P interface now starts alongside a Unix-socket shared instance or another connectable I2P interface, and an I2P interface runs one connection for every configured peer, plus its server when connectable, as in Python Reticulum.
- Hub restarts restore saved paths and tunnels as in Python Reticulum.
- Transport hubs now accept tunnel synthesis, so a Python client that reconnects gets its paths back without announcing again, and losing a tunnel's interface no longer drops paths the hub learned through other interfaces, as in Python Reticulum.
- PLAIN and GROUP packets that arrive from more than one hop away, and announces typed PLAIN or GROUP, are dropped before deduplication, as in Python Reticulum.
- TCP, Backbone and I2P client interfaces open every connection with a tunnel synthesis, so a transport hub restores their paths after a reconnect, and traffic queued while a connection was down or failing to open is dropped when it opens, as in Python Reticulum.
- A client of a Unix-socket shared instance drops traffic queued while the instance was unreachable, as in Python Reticulum.
- I2P interfaces announce their own address for discovery, and the peers listed in `peers` keep Python's defaults, sharing only the interface's IFAC, as in Python Reticulum.
- A bootstrap-only I2P interface keeps running once discovered interfaces connect, as in Python Reticulum, which never detaches an I2P interface.
- A connectable I2P interface keeps its I2P address across restarts. Its key is stored in Python Reticulum's key file under `storage/i2p`, readable by its owner only; as in Python Reticulum, a node without `enable_transport` or `static_transport_identity` gets a new address each start.
- Every validated announce refreshes the identity remembered for its destination, including path responses and replays that leave the path unchanged, so a destination's identity stays recallable as in Python Reticulum.
- Python Reticulum 1.5 `rnstatus` and `rnpath` work against `rnsd-rs`, locally and with `-R`: interface stats carry every field they read, including announce and path request counts, violation counters and the transport instance, and remote management answers on the transport identity, as in Python Reticulum.
- `rnstatus-rs -R` and `rnpath-rs -R` take the remote node's transport identity hash, which `rnstatus` shows as the transport instance on a transport node. A node with `enable_transport` off and no `static_transport_identity` gets a new management destination each start, as in Python Reticulum; set `static_transport_identity = yes` on a leaf you manage remotely. `storage/remote_management_identity` is no longer used and can be deleted.
- Announces held during an ingress burst on an IFAC interface are processed when released instead of being dropped, and released or replayed announces no longer count as received traffic again, as in Python Reticulum.
- Interface discovery announces name this stack, `rsRNS`, and its version. `rnsd-rs` auto-connects only to Backbone interfaces announced by Python Reticulum 1.5.2 or later, or to any announced Backbone interface with `autoconnect_unverified_implementations`, and no longer stores or lists discovered TCP client interfaces, as in Python Reticulum.
- Discovery announces a KISS-framed TCP client as a KISS interface and sends and reads unset radio parameters as nil, so Python and `rnsd-rs` read each other's KISS, Weave and RNode announces, as in Python Reticulum.
- `rns_link::clock::ContinuousInstant` reads a monotonic clock that keeps counting while the system is suspended, for deadlines that must hold in real time across a sleep.
- An interface counts a path request in its stats only once its tag passes the duplicate check, as in Python Reticulum 1.5.
- A realtime Link packet dropped at a full transmit queue counts toward the interface's dropped bytes.
- `rnpath -R` filters the remote path and rate tables as Python Reticulum compares them: a destination hash of another length matches nothing, and the hop limit compares as a number instead of wrapping above 255.
- Remote management Links refuse Resources other than requests and responses, as Python Reticulum's do.
- `rnsd-rs` never auto-connects a discovered interface at an onion address, at 127.0.0.1 or 0.0.0.0, or at a host and port that an interface already connects to, as in Python Reticulum.
- Interface stats name the network an auto-connected interface was discovered through (`autoconnect_source`), as in Python Reticulum.
- Decryption, key derivation and identity and ratchet file handling wipe temporary sensitive buffers, and decryption avoids an extra plaintext copy. Returned plaintext remains caller-owned and must be wrapped in `Zeroizing` when it needs wiping on drop. Identity files larger than 1 KiB are refused.
- A 64-byte identity file always loads as a raw key, as in Python Reticulum. About one key in 29,000 began with bytes that were misread as the older envelope format, and its identity failed to load.
- Writing, verifying and recovering state files retries a read that a signal interrupts instead of failing.
- Interface options wipe their IFAC passphrase when dropped, and the debug output of IFAC settings no longer shows it.
- Each interface's IFAC key lives in one allocation that is wiped when dropped, so interface tables no longer leave copies of it in freed memory.
- I2P interfaces no longer leave their private key in freed memory when they read it, store it or exchange it with the SAM bridge. They refuse a key file larger than 16 KiB and, as Python Reticulum's SAM client does, a SAM reply line longer than 64 KiB.
- Remote management answers the profiling flag of `rnstatus -R -z` with empty results, and leaves a status request that is not a list of flags unanswered, as Python Reticulum does.
- `rnstatus-rs` shows the network an auto-connected interface was discovered through on a `Source` line under its name, as Python's `rnstatus` does, and its JSON output carries it as `autoconnect_source`.
- AutoInterface's `devices` and `ignored_devices` take effect, and they and I2P `peers` are read as Python Reticulum reads lists: a quoted name that contains a comma stays one name, and `devices = ,` allows every interface.
- TCP client interfaces read `i2p_tunneled`, as Python Reticulum does, and give a connection tunneled over I2P its longer I2P socket timeouts.
- TCP server and Backbone interfaces are announced for discovery only with `reachable_on` set, and Backbone clients never, as in Python Reticulum. A discoverable server without `reachable_on` logs a warning and is not announced, so set `reachable_on` to keep announcing it. The `discovery_reachable_on` key is no longer read.
- Corrected packet-size limits across interfaces and Links, including IFAC overhead, and reject unsupported Link setups before sending them.
- Added application-controlled acknowledgements so propagation nodes can confirm a message only after safely storing it.
- Prevent stale interface or Link callbacks from acknowledging a different connection after reconnect or cancellation.
- Reject malformed Resource metadata and invalid timeout values without panics or excessive allocation.
- Added checked durable file operations for identities, ratchets, and application storage, with explicit recovery after interrupted writes.
- Updated public interface, Link, and storage APIs. Use the `~1.4.0` compatibility line for these source-breaking APIs.
## 1.3.0 - 2026-10-12
### Added
- Added Link bind-readiness polling so applications can start sending as soon as the transport is ready.
### Fixed and improved
- Represent unknown discovery latitude, longitude, and height independently as `None` instead of zero, accept Python nil coordinates, and preserve presence through configuration, storage, and `rnstatus-rs`.
- Register and own the interface-discovery destination, advance publication intervals only after driver admission, and preserve pending announcements across bounded backpressure and reconnect.
- Keep learned mesh announcements out of ordinary RNode control/data backlogs until the final writer can send them, while preserving same-radio relay and announce pacing.
- Retain refused local announcements and attached path answers under bounded ownership tied to the exact interface generation.
- Preserve multiple recursive-discovery requesters, slow-radio deadlines, interface replacement safety, and hidden-peer same-radio responses without letting one cancellation affect another requester.
- Updated btleplug to 0.13.4, including upstream Windows discovery and reconnect fixes. Windows can try an explicitly configured RNode MAC or an eligible remembered BLE Peer absent from scan results, with bounded GATT setup, existing backoff, and signed peer identity checks.
- Installed desktop BLE notification receivers before subscribing and limited packet fragments to the negotiated ATT payload.
- Improved Bluetooth Peer packet sizing and flow control, including Apple write handling and queued sends.
- Fixed a remotely triggerable Link panic when a peer reported an infinite, NaN, negative, or oversized RTT. Peer RTTs follow Python's handling and saturate at the 720-second stale window; initiators ignore LRRTT as Python does.
- Require the corrected Windows socket backend so spawned helper processes cannot keep network listeners alive after the owning runtime shuts down.
- Match Python RNS 1.4.2 Channel receive-window admission by dropping sequence numbers more than 48 slots ahead until a retry falls inside the window.
- Report the bundled `rnsh` compatibility level as 0.3.0 and the `rnsd-rs` interactive compatibility level as RNS 1.4.2.
### Build and compatibility
- Discovery coordinates now use `Option<f64>`, and recursive discovery exposes detached observations and exact requester cancellation instead of public mutable state. Both source-breaking changes are covered by the [1.3 migration guide](api/migrations/1.3.md).
- Project minor versions may include breaking APIs. Select `~1.3.0` or an exact reviewed source revision when adopting this release line.
- Raised the full Rust workspace minimum compiler to Rust 1.89. Apple native BLE bindings declare their required features explicitly; Android consumers must use btleplug's matching 0.13.4 Java bridge and JNI 0.22 initialization.
- Promote exact Python RNS 1.4.2 to the complete release baseline, including live interoperability, source oracles, utility vectors, and corpus provenance. RNS 1.5.0 remains deferred.
## 1.2.0 - 2026-08-17
- Designated the existing `rns_runtime::prelude` and compiled examples as the
canonical application spine while retaining every module-qualified path,
and added external-consumer, manifest/feature, and additions-only API
compatibility gates without changing runtime behavior or public signatures.
- Classified every library package and added pinned, CI-enforced public API
snapshots so compatibility drift is reviewed before any boundary change;
no visibility or signature changed in this baseline.
- Made source releases reproducible from an existing immutable component tag:
packages are non-publishable by default, release builds use the committed
lockfile and Rust 1.87.0, actions are commit-pinned, and CI verifies the
manifest, changelog, tag, and checkout contract.
- Isolate exact announce subscriptions from legacy aspect-wide deregistration,
and resolve finite destination identities through validated recall plus
deadline-bounded path discovery instead of temporary announce handlers.
- Distinguished the Reticulum 1.3.8 compatibility-floor corpus from the
current 1.4.2 behavior reference instead of presenting the old oracle as the
newest upstream target.
- Enforce role-specific Link packet proofs: initiators sign with the transient
LINKREQUEST key, responders sign with the destination identity, and external
identity backends no longer fall back to an unrelated key.
- Ignore unauthenticated invalid LRPROOF candidates without closing a pending
initiator, allowing the authentic proof to win an interface race.
- Bind every locally owned established Link endpoint to its validated
interface and role, with fail-closed routing, bounded ordered control egress,
terminal interface-loss notification, and bounded best-effort realtime
egress. Typed send rejection closes only the exact owner, while final
LINKCLOSE and temporary-destination cleanup drain atomically in order.
Initial LINKREQUEST discovery remains path-routed or broadcast.
- Forward authenticated non-Link packet delivery proofs from `LinkManager` to
owning applications through a lossless completion channel.
- Retain and retry destination announcements, including path responses, when
the bounded transport ingress is temporarily saturated.
- Let one-shot Link clients reuse a validated cached identity when its route is
still live, matching Python recall behavior and avoiding redundant path
discovery.
- Keep completed `rncp` Links alive for Python's receiver-side Resource
conclusion callback before sending the authenticated teardown.
- This source line includes application and runtime API evolution since 1.1.0;
downstream integrations should qualify against the 1.2 dependency line.
## 1.1.0 - 2026-07-26
- Added application-facing Destination, announce, receipt, Link, request,
Channel, Buffer, and Resource APIs.
- Added resilient long-running Link sessions with recovery, liveness,
cancellation, progress, metrics, and responder lifecycle support.
- Hardened delivery proofs, shared-instance authority and reconnection, IFAC
ingress, persistence, routing snapshots, and orderly shutdown.
- Expanded RNode lifecycle, capability, BLE, USB, TCP, serial, and safe
`rnodeconf-rs` support.
- Added compiled examples and stricter MSRV, Clippy, interoperability, and
public-documentation gates.
Generated
+552 -253
View File
File diff suppressed because it is too large. Load diff
+18 -15
View File
@@ -14,19 +14,21 @@ members = [
]
[workspace.package]
version = "0.9.4"
version = "1.4.0"
edition = "2024"
license = "AGPL-3.0-or-later"
rust-version = "1.85"
license-file = "LICENSE"
rust-version = "1.89"
[workspace.dependencies]
# Crypto
x25519-dalek = { version = "2", features = ["static_secrets"] }
ed25519-dalek = { version = "2", features = ["hazmat", "rand_core"] }
aes = "0.8"
cbc = { version = "0.1", features = ["alloc"] }
aes = { version = "0.8", features = ["zeroize"] }
des = "0.8"
cbc = { version = "0.1", features = ["alloc", "zeroize"] }
hkdf = "0.12"
hmac = "0.12"
md-5 = "0.10"
sha2 = "0.10"
subtle = "2"
zeroize = { version = "1", features = ["derive"] }
@@ -40,13 +42,14 @@ base64 = "0.22"
rmp-serde = "1"
rmpv = "1"
serde = { version = "1", features = ["derive"] }
serde_bytes = "0.11"
serde_json = "1"
# Async
tokio = { version = "1", features = ["full"] }
# Compression
bzip2 = "0.5"
bzip2 = "0.6"
# Serial
serialport = { version = "4", default-features = false }
@@ -77,12 +80,12 @@ nix = { version = "0.29", features = ["term", "fs"] }
proptest = "1"
# Workspace crates
rns-crypto = { path = "crates/rns-crypto", default-features = false }
rns-wire = { path = "crates/rns-wire", default-features = false }
rns-identity = { path = "crates/rns-identity" }
rns-transport = { path = "crates/rns-transport" }
rns-link = { path = "crates/rns-link" }
rns-protocol = { path = "crates/rns-protocol" }
rns-interface = { path = "crates/rns-interface" }
rns-runtime = { path = "crates/rns-runtime" }
rns-ratkey = { path = "crates/rns-ratkey" }
rns-crypto = { path = "crates/rns-crypto", version = "~1.4.0", default-features = false }
rns-wire = { path = "crates/rns-wire", version = "~1.4.0", default-features = false }
rns-identity = { path = "crates/rns-identity", version = "~1.4.0" }
rns-transport = { path = "crates/rns-transport", version = "~1.4.0" }
rns-link = { path = "crates/rns-link", version = "~1.4.0" }
rns-protocol = { path = "crates/rns-protocol", version = "~1.4.0" }
rns-interface = { path = "crates/rns-interface", version = "~1.4.0" }
rns-runtime = { path = "crates/rns-runtime", version = "~1.4.0" }
rns-ratkey = { path = "crates/rns-ratkey", version = "~1.4.0" }
+26 -653
View File
@@ -1,661 +1,34 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Reticulum License
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Derived from the reference implementation at
https://github.com/markqvist/Reticulum
Preamble
Copyright (c) 2016-2026 Mark Qvist, unless otherwise noted
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
Additions and modifications Copyright (c) 2026 Ratspeak LLC
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
- The Software shall not be used in any kind of system which includes amongst
its functions the ability to purposefully do harm to human beings.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
- The Software shall not be used, directly or indirectly, in the creation of
an artificial intelligence, machine learning or language model training
dataset, including but not limited to any use that contributes to the
training or development of such a model or algorithm.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
- The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+116 -52
View File
@@ -5,10 +5,10 @@
**A Rust implementation of Reticulum.**
[![License: AGPL-3.0-or-later](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue.svg)](LICENSE)
[![Rust 1.85+](https://img.shields.io/badge/rust-1.85%2B-orange.svg)](https://www.rust-lang.org)
[![Reticulum 1.2.5](https://img.shields.io/badge/target-Reticulum%201.2.5-success.svg)](https://reticulum.network/)
[![Status](https://img.shields.io/badge/status-experimental-yellow.svg)](#feature-status)
[![License: Reticulum License](https://img.shields.io/badge/license-Reticulum%20License-blue.svg)](LICENSE)
[![Rust 1.89+](https://img.shields.io/badge/rust-1.89%2B-orange.svg)](https://www.rust-lang.org)
[![Release baseline: Reticulum 1.4.2](https://img.shields.io/badge/release%20baseline-Reticulum%201.4.2-success.svg)](https://reticulum.network/)
[![Status](https://img.shields.io/badge/status-experimental-yellow.svg)](#compatibility-notes)
[Reticulum Manual](https://reticulum.network/manual/) |
[Ratspeak](https://github.com/ratspeak/Ratspeak) |
@@ -19,9 +19,12 @@
---
rsReticulum is a Rust implementation of Reticulum. This is not a fork of
Reticulum; it is Reticulum written in a different language, focused on staying
interoperable. It is not the source-of-truth implementation, do not treat it as one.
rsReticulum is a Rust port of
[Reticulum](https://github.com/markqvist/Reticulum), the reference
implementation by Mark Qvist. It was written from the reference source, not from
a specification, and tracks the reference's wire behavior release by release.
The Python reference implementation remains the source of truth. See
[License](#license).
Commands are intentionally namespaced for Rust with `*-rs` command names, so
rsReticulum can live beside other Reticulum tools on `PATH` without worry.
@@ -29,6 +32,7 @@ rsReticulum can live beside other Reticulum tools on `PATH` without worry.
## Contents
- [Build It](#build-it)
- [Rust API](api/README.md)
- [Tool Usage](#tool-usage)
- [Configuration](#configuration)
- [Interface Support](#interface-support)
@@ -38,6 +42,18 @@ rsReticulum can live beside other Reticulum tools on `PATH` without worry.
## Build It
This guide describes the 1.4.0 release, [v1.4.0](https://github.com/ratspeak/rsReticulum/releases/tag/v1.4.0), the source line Ratspeak builds from. For the 1.3.0 tools, use [the v1.3.0 README](https://github.com/ratspeak/rsReticulum/blob/v1.3.0/README.md) and that build's `--help`.
From a new working directory:
```bash
git clone https://github.com/ratspeak/rsReticulum.git
git -C rsReticulum checkout --detach 5b38cae702a5b3984adf12a435f6d3012fcf90e1
cd rsReticulum
```
Run the build commands below from that directory. The host crates require Rust 1.89 or newer.
### macOS
Install Rust with `rustup`, then install Apple's command-line build tools:
@@ -49,13 +65,12 @@ xcode-select --install
Build the tools:
```bash
cd rsReticulum
cargo build --release
cargo build --release --locked
```
### Linux, Raspberry Pi, and VPS Hosts
##### Install Rust with `rustup`, then install the needed packages:
Install Rust with `rustup`, then install the build packages:
Debian, Ubuntu, and Raspberry Pi OS:
@@ -76,11 +91,10 @@ Arch:
sudo pacman -S --needed base-devel pkgconf
```
##### Build the tools:
Build the tools:
```bash
cd rsReticulum
cargo build --release
cargo build --release --locked
```
### Windows
@@ -91,8 +105,7 @@ Build Tools, install the "Desktop development with C++" workload.
Build from PowerShell:
```powershell
cd rsReticulum
cargo build --release
cargo build --release --locked
```
After the build, use the commands below with `./target/release/<tool>` on
@@ -110,20 +123,20 @@ The `rns-tools` crate builds Rust-namespaced Reticulum utilities:
| rnid-rs | Identity generation, inspection, public/private import/export, hashing, signing, verification, encryption, and decryption. |
| rnprobe-rs | Destination probe utility with loss and round-trip reporting. |
| rncp-rs | File transfer utility with send, listen, and authenticated fetch modes. |
| rnodeconf-rs | RNode inspection, safe configuration, EEPROM backup, and trust utility. |
| rnodeconf-rs | RNode inspection, EEPROM backup, and saved TNC/normal startup configuration. |
| rnsh-rs | Reticulum shell listener/client. |
#### Commands:
Common command forms (use each binary’s `--help` for the complete option list):
```text
rnsd-rs [-c CONFIG_DIR] [-v|-q]... [--service] [--exampleconfig] [--version]
rnstatus-rs [--all] [--sort rate|traffic|rx|tx|rxs|txs|announces|arx|atx|held]
rnsd-rs [-c CONFIG_DIR] [-v|-q]... [-i] [--service] [--exampleconfig] [--version]
rnstatus-rs [--all] [--sort rate|traffic|rx|tx|rxs|txs|announces|arx|atx|arxc|atxc|prx|ptx|prxc|ptxc|held|pvs|ivs|flt|txdrp|txdrb]
[--reverse] [--announce-stats] [--link-stats] [--totals] [--json]
[--discovered|-D] [-m [-I SECONDS]] [FILTER]
[-d|--discovered] [-D] [-m [-I SECONDS]] [FILTER]
[-R <transport_hash> -i <identity_file>]
rnpath-rs [--table|--rates] [destination_hash] [--max HOPS]
rnpath-rs <destination_hash>
rnprobe-rs [-s SIZE] [-n COUNT] [-t TIMEOUT] [-w WAIT] [--json] <destination_hash>
rnprobe-rs [-s SIZE] [-n COUNT] [-t TIMEOUT] [-w WAIT] [--json] <full_name> <destination_hash>
rnid-rs [-i IDENTITY|-g FILE|-m PUB|-M PRV] [-p|-P] [-x|-X] [-H ASPECT]
[-a [ASPECT]] [-e FILE|-d FILE|-s FILE|-V FILE] [-w FILE] [-f]
[-R|-N] [-t SECONDS] [-b|-B] [--raw] [--version]
@@ -131,30 +144,42 @@ rncp-rs <file> <destination_hash>
rncp-rs -l [-b SECONDS] [-s DEST_DIR] [-a <allowed_hash>]...
rncp-rs -l -F [-j <jail_dir>] [-a <allowed_hash>|-n]...
rncp-rs -f <destination_hash> <remote_path> [-s DEST_DIR]
rnodeconf-rs [-i] [--config] [--eeprom-backup|--eeprom-dump] [--version] [PORT]
rnodeconf-rs -T --freq HZ --bw HZ --txp DBM --sf SF --cr CR PORT
rnodeconf-rs -N PORT
rnsh-rs -l [-i FILE] [-s NAME] [-b PERIOD] [-a HASH]... [-n] [-A|-C] [-- CMD...]
rnsh-rs [-i FILE] [-s NAME] [-N] [-m] [-w SECONDS] <destination_hash> [-- CMD...]
```
Add the release `bin/` directory or `target/release` to `PATH` if
you want to call them without a path prefix.
`rncp-rs` follows the established listener authentication model: without `-n`,
incoming senders must match `-a <hash>` or an `allowed_identities` file.
`rncp-rs -F` can serve fetch requests to authenticated clients; use
`-j <jail>` to bound file access unless unrestricted fetch paths are
intentional.
`rncp-rs` has a listener authorization limitation in 1.4.0 and 1.3.0: `-a <hash>` and `allowed_identities` are checked when a
peer identifies, but identification is not required before receiving a pushed
file. Do not rely on the allowlist to exclude unidentified senders.
`rnodeconf-rs` in the current build only covers safe inspection/device setting paths, EEPROM
dump/backup, and trusted-key storage.
Without `-n`, fetch requests require an identified peer on the allowlist.
`rncp-rs -F` enables fetch service and leaves push reception enabled. Use
`-j <jail>` to constrain fetched paths to a directory under trusted local
control; it is not an operating-system sandbox.
`rnid-rs` tracks the Reticulum 1.2.4 identity utility surface for normal
`rnodeconf-rs` in 1.4.0 and 1.3.0 supports inspection,
EEPROM dump/backup, and saving TNC/normal startup settings. `-T` requires all five
RF values shown above. Firmware installation, signing/trust enrollment and
Bluetooth, Wi-Fi, display and interference-avoidance changes are disabled.
Their options remain in the parser but return an error.
`rnid-rs` tracks the Reticulum 1.4.2 identity utility surface for normal
software identities: public/private import and export, destination hashing,
`.pub` public identity files, and signed `.rsg` signature files. The
hardware-backed `rnid-rs hw` path is a Rust extension behind the `hardware`
feature and should still be treated as experimental.
Common `rnid-rs` flows:
Common `rnid-rs` flows for a POSIX shell. Replace uppercase placeholders with your values. Private exports and imported private data grant control of the identity; keep them out of shared terminals, logs and shell history.
```bash
# Generate and inspect an identity.
mkdir -p ~/.rsReticulum/identities
rnid-rs -g ~/.rsReticulum/identities/mgmt
rnid-rs -i ~/.rsReticulum/identities/mgmt -p
rnid-rs -i ~/.rsReticulum/identities/mgmt -H lxmf.delivery
@@ -166,13 +191,13 @@ rnid-rs -i ~/.rsReticulum/identities/mgmt -X -B
# Write identity files. Without -X, -w writes a public .pub file.
rnid-rs -i ~/.rsReticulum/identities/mgmt -w mgmt.pub
rnid-rs -i ~/.rsReticulum/identities/mgmt -X -w mgmt.rid
rnid-rs -m <public_identity_data> -w peer.pub
rnid-rs -M <private_identity_data> -X -w restored_identity
rnid-rs -m "PUBLIC_IDENTITY_DATA" -w peer.pub
rnid-rs -M "PRIVATE_IDENTITY_DATA" -X -w restored_identity
# Sign and validate. New signatures are Reticulum 1.2.4 .rsg envelopes.
# Sign and validate. New signatures are Reticulum 1.4.2-compatible .rsg envelopes.
rnid-rs -i ~/.rsReticulum/identities/mgmt -s message.txt
rnid-rs -V message.txt.rsg
rnid-rs -i <signer_hash> -N -V message.txt.rsg
rnid-rs -i "SIGNER_IDENTITY_HASH" -N -V message.txt.rsg
# Encrypt to a public identity, decrypt with the matching private identity.
rnid-rs -i mgmt.pub -e message.txt
@@ -181,7 +206,7 @@ rnid-rs -i ~/.rsReticulum/identities/mgmt -d message.txt.rfe
Use `--raw -s <file>` only when a workflow intentionally needs the legacy raw
64-byte signature form. Normal `rnid-rs -s <file>` produces a `.rsg` file that
embeds the signer metadata needed for 1.2.4 validation.
embeds the signer metadata needed for current and retained compatibility.
## Configuration
@@ -193,13 +218,15 @@ directory is supplied, the default is:
| Linux/macOS | `/etc/rsReticulum/config`, then `~/.config/rsReticulum/config`, then `~/.rsReticulum/config` |
| Windows | `%APPDATA%\rsReticulum\config` |
Generate the annotated starter file:
On Linux/macOS, the first two locations are selected only when their `config` file exists; otherwise the home-directory fallback is used.
Print the annotated starter configuration to standard output:
```bash
rnsd-rs --exampleconfig
```
Minimal TCP client example:
Minimal TCP client example. Replace `reticulum.example.org` and the port with the endpoint supplied by your network operator:
```ini
[reticulum]
@@ -212,17 +239,15 @@ enable_transport = no
[[Default TCP]]
type = TCPClientInterface
enabled = yes
target_host = rns.ratspeak.org
target_host = reticulum.example.org
target_port = 4242
```
Existing Python Reticulum configs should work if every requested interface
is implemented here. Unknown or not-yet-wired interfaces should be removed or
disabled until support lands.
Review an imported Python or older Rust config before starting it. Each interface needs a supported type and an explicit `enabled = yes` or `interface_enabled = yes`. For an explicit IFAC size, use `ifac_size_unit = bits` with `ifac_size`, or the separate `ifac_size_bytes` key. Unmarked values from 1 to 64 are rejected as ambiguous; larger valid values are interpreted as bits. See the [configuration migration](api/migrations/capacity-and-receipts.md#explicit-ifac-units). The published 1.3.0 tools use the older byte convention. Keep unsupported interfaces disabled.
The default shared-instance data/control ports are `37428`/`37429`. Ratspeak
uses app-private `37430`/`37431` ports. If you run two daemons at the same
time, give one config a distinct port pair to avoid confliction, like:
time, give one config a distinct port pair to avoid a port conflict:
```ini
[reticulum]
@@ -230,15 +255,21 @@ shared_instance_port = 37432
instance_control_port = 37433
```
Programs use the control port with the instance's RPC key: `rpc_key` under
`[reticulum]` when it is set, otherwise a key derived from the transport
identity. That key is an admin credential: a program that has it can read the
daemon's network state, drop its paths and block identities, so treat it like
a password and give it only to programs you trust.
## Interface Support
###### Note: This is alpha, if something doesn't work, open an issue with enough context/information to help contribute to fixing it.
This stack is experimental. Include the source revision or binary version, platform, interface type and relevant logs when reporting a problem.
| Interface | Current behavior |
| --- | --- |
| TCP client/server | Config-backed IPv4 and IPv6 paths. |
| UDP | Config-backed unicast and multicast paths. |
| Auto | Config-backed UDP discovery plus TCP fallback. |
| UDP | Unicast and IPv4 broadcast datagrams; this driver does not join multicast groups. |
| Auto | IPv6 multicast discovery with unicast UDP data on the local network. |
| Local shared instance | Config-backed TCP loopback or Unix socket depending on platform. |
| I2P | Config-backed SAM v3.1 path. |
| Pipe | Config-backed subprocess stdio pipe. |
@@ -247,22 +278,41 @@ instance_control_port = 37433
| BLE RNode | Config-backed with the `ble` feature. |
| Bluetooth Peer | Runtime API used by Ratspeak. |
| Android USB-OTG | Runtime API for Android app embeddings. |
| Weave | Not implemented. |
| Weave | Partial: interface driver implemented, not yet config-wired in the runtime. |
| Bluetooth Classic RFCOMM | Not implemented. |
## Established Link Routing
An initial Link Request uses normal Reticulum path discovery and may be
broadcast when no path is known. Once the responder accepts that request and
the initiator validates its proof, each local Link endpoint is bound to the
exact interface and role selected by the handshake. Later Link packets,
Channels, Resources, proofs, keepalives, and teardown never fall back to a
different path or interface; loss of the selected interface closes that Link.
Reliable Link control uses a bounded ordered queue, while realtime media has a
separate bounded best-effort path that cannot overtake retained control
traffic. A proof sent by the initiator uses its temporary signing key from
the Link Request; a proof sent by the responder uses the accepting destination
identity.
## Compatibility Notes
Most daemon and utility flows are implemented for the public `*-rs` tools:
`rnsd-rs`, `rnstatus-rs`, `rnpath-rs`, `rnid-rs`, `rnprobe-rs`, `rncp-rs`,
`rnsh-rs`, and `rnodeconf-rs`.
The current compatibility target is Reticulum 1.2.4 where the matching Rust
surface is implemented and tested. `rnid-rs` has explicit 1.2.4 coverage for
the normal identity utility flow.
The release baseline for 1.3.0 and 1.4.0 is Python Reticulum 1.4.2. The complete byte-exact corpus,
utility vectors, source-truth oracles, and live Python interoperability matrix
are pinned to its exact source commit. Historical 1.3.8 audits and fixtures
retain their original provenance as backward-compatibility evidence. RNS 1.5.0
was not part of that complete release gate. The current source includes
selected later Python compatibility changes; those do not establish complete
parity with a later Python release.
Known gaps and intentional limits:
- `rnx`, `rnir`, `rnpkg`, `rngit`, and `git-remote-rns` are not implemented. There is on-going work in progress for supporting these.
- `rnx`, `rnir`, `rnpkg`, `rngit`, and `git-remote-rns` are not implemented.
- `rnodeconf-rs` is partial; safe inspection/configuration and EEPROM
dump/backup are furthest along. Firmware flashing, autoinstall/update, ROM
bootstrap, destructive EEPROM wipe, and full signing-key management are not
@@ -272,8 +322,14 @@ Known gaps and intentional limits:
- `rnpath-rs` remote mode is read-only for table/rates, including destination
filters, apart from the remote blackhole-list query path. Remote mutations
and remote active path requests are full gaps.
- Interface discovery announces name this stack `rsRNS` and its version. Python
Reticulum 1.5.5 and later auto-connects only to Backbone interfaces
announced by Python Reticulum 1.5.2 or later, so a Python node auto-connects
to an `rsRNS` interface only with `autoconnect_unverified_implementations =
yes` in its `[reticulum]` section. `rnsd-rs` follows the same rule, and the
same option lets it auto-connect to any announced Backbone interface.
- `rncp-rs` implements the listener `-b` announce interval. `-P/--phy-rates`
is not supported for the time being.
is not supported.
- `rns-ratkey` hardware identity support is feature-gated and still has known
hardware-verification gaps before it should be described as release-ready.
@@ -286,4 +342,12 @@ PRs are closed for now until I have time to catch up on everything. I'm tired.
## License
GNU Affero General Public License v3.0 or later. See [LICENSE](LICENSE).
rsReticulum is licensed under the [Reticulum License](LICENSE), the license of
the reference implementation it is ported from. Copyright (c) 2016-2026 Mark
Qvist, unless otherwise noted; additions and modifications Copyright (c) 2026
Ratspeak LLC.
The license is permissive with two conditions: no use in systems built to
purposefully harm people, and no use in or contribution to AI or language-model
training. The copyright and permission notice must stay in every copy.
[LICENSE](LICENSE) is the binding text.
+190
View File
@@ -0,0 +1,190 @@
# Rust API
This guide describes the 1.4.0 API, published as v1.4.0. For the 1.3.0
tools and libraries, use the documentation at that tag. The [1.4 migration
guide](migrations/1.4.md) covers source and configuration changes.
Application code should begin with `rns_runtime::prelude`. It collects the
runtime handle and the commonly used identity, destination, packet, Link,
request, Channel, Resource, interface, and shutdown types without wrapping or
replacing them. Existing module-qualified imports remain supported.
The examples in `crates/rns-runtime/examples/` are compiled as part of CI and
show complete flows for runtime startup, Destinations, announces, receipts,
Links, requests, Channels, Buffer streams, Resources, and RNode observation.
```rust
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use rns_runtime::prelude::*;
#[tokio::main]
async fn main() -> Result<(), ReticulumError> {
let runtime = init(
None,
None,
ShutdownSignal::new(),
Arc::new(AtomicBool::new(true)),
)
.await?;
let identity = Identity::new();
// Use `runtime` and `identity` to create application Destinations.
runtime.shutdown_and_wait().await;
Ok(())
}
```
Finite destination discovery uses `resolve_destination_on_transport` with one
deadline and validated identity recall. Long-lived announce observation uses
`ReticulumHandle::subscribe_announces`; the returned `AnnounceSubscription`
owns exactly one registration. Finite lookups do not install or remove
announce handlers.
## Explicit shared-instance ownership
Applications that require authenticated shared control can opt into
`reticulum::init_with_policy` and `shared_instance::InstancePolicy`:
- `Configured` retains the normal config-driven automatic owner/client behavior.
- `Standalone` owns local interfaces without exposing shared IPC.
- `SharedOwner` binds both configured shared endpoints or fails; it never joins
another owner. `SharedOwnerAt(endpoint)` selects them in memory without
rewriting the configuration file.
- `SharedClient(credentials)` requires the selected packet endpoint and
authenticated interface-status RPC before becoming ready. It reauthenticates
on reconnect and never falls back to local interfaces.
`SharedInstanceEndpoint::Tcp` is loopback-only. Explicit Unix endpoints use
Linux/Android abstract instance names. Keys are opaque HMAC bytes, supplied via
`SharedInstanceCredentials::new`; its debug representation redacts the key.
`credentials.test().await` checks availability without starting a runtime.
Observe reconnect/authentication state through `shared_instance_state()` and
typed control failures through `query_control_result()`. Client runtimes reject
dynamic local interface spawns. Non-fatal configured-interface startup failures
are available through `startup_interface_failures()`; other interfaces can
remain usable.
Upstream packet IPC is unauthenticated: successful RPC authenticates the control
endpoint, not the identity of the packet socket. Selecting a trustworthy matching
pair remains the application's responsibility. These policies do not move
AutoInterface's interoperable UDP ports or alter Reticulum wire formats.
The [capacity, IFAC and receipt migration guide](migrations/capacity-and-receipts.md) describes the current 1.4 source boundary, including custom-driver ownership and application-controlled admission.
## Stability
The 1.3 line changes the six discovery coordinate fields to `Option<f64>` so
unknown values remain distinct from real zero. It also replaces publicly mutable
recursive discovery state with detached observations and exact requester
cancellation. See the [1.3 migration guide](migrations/1.3.md) for both changes
and their source, wire, and storage behavior. Normal runtime lookup/recovery
APIs remain unchanged. Project minor releases can include breaking API changes;
select an explicit compatible dependency line or reviewed immutable source pin.
Applications that own retry policy can obtain
`ReticulumHandle::path_recovery_handle()` (also available from the application
prelude). `try_recover(destination, Some(failed_link_id))` requests an atomic
comparison with the route actually used by that locally originated Link. Only
the unchanged route can be invalidated; fresh routes on the same interface are
not suppressed. `None` requests bounded discovery without route invalidation.
The 64-operation admission queue reports backpressure; callers retain ownership
and bound their reply wait. Discovery is coalesced per destination, and the
result is not proof of radio transmission or delivery. Old or unobserved Link
attempts cannot delete routes. Shared clients only affect their own local
transport state and use normal packet IPC for discovery.
`try_recover_packet(destination, packet_hash)` provides the same comparison for
an atomically tracked local `SendPacket` attempt. Packet and Link ownership are
separate; failures cannot consume another kind of attempt. Packet receipt
windows can use `rns_wire::receipt::receipt_timeout_for_route`, also used by the
runtime's automatic packet receipt policy.
`try_invalidate_packet(destination, packet_hash)` and
`try_invalidate_link(destination, link_id)` perform only the exact
failed-attempt route comparison and invalidation, without starting a new path
request. A shared-client application can use this result to sequence its own
authenticated owner recovery before ordinary discovery. This does not make
legacy Python's destination-only owner reset an atomic route comparison or
cancel other callers' pre-existing discovery.
### Established-Link delivery clocks
Advanced Link owners can obtain `ReticulumHandle::link_endpoint_dispatch_handle()`.
Its opt-in bind receipt publishes an opaque token for one exact endpoint
generation. `token.try_send(request, deadline)` retains the ordinary packet in
the existing ordered endpoint FIFO until driver/local-peer admission, local
expiry, cancellation, or an exact terminal failure. The deadline includes
mailbox wait and is limited to 120 seconds. `Sent` contains the original local
dispatch time and packet hash; it is not physical transmission or delivery.
Dropping an unread bind receipt retires only its unpublished binding; published
bindings still require the normal explicit cleanup.
`LinkEndpointDispatchBindReceipt::poll_ready` registers a task waker without
publishing the binding. It retains a ready result until `try_recv` or awaiting
consumes it; cancellation between readiness and consumption still retires the
unpublished endpoint. This supports event-driven delivery owners without
changing existing periodic consumers or proof timing.
`try_send_cancellable` additionally returns an exact cancellation capability.
It requests removal while the packet is still awaiting local admission; it
cannot recall bytes already admitted to a driver or affect another binding.
The actor's final pre-admission check is the concurrent cancellation boundary.
`LinkManager::set_link_endpoint_dispatch_handle` enables these observations for
ordinary packet sends. Legacy mailbox `Queued` still means only FIFO acceptance.
`Link::packet_proof_timeout()` provides the measured-RTT proof budget, distinct
from local queue residence. The accounting stream's outbound wait events retain
the owner's original start time and finite timeout; delayed consumers must not
restart those clocks. `OutboundTransfer::timeout_window()` similarly describes
the current bounded Resource phase. Only genuine protocol progress renews it.
The application prelude is the recommended integration path, but the workspace
is not yet a blanket stability promise for every public Rust item.
- `rns-identity`, `rns-link`, `rns-protocol`, and `rns-interface` are candidate
stable.
- `rns-crypto`, `rns-wire`, and `rns-transport` are provisional low-level
packages.
- `rns-runtime` is provisional because it contains both the application
prelude and lower-level actor, RPC, manager, and command APIs.
- `rns-ratkey` is experimental, and the `rns-tools` library target supports the
repository's binaries rather than a public library integration.
Low-level actor, mailbox, RPC, transport-table, concrete-driver, and Link
endpoint ownership APIs remain available for compatibility. They should not be
treated as stable merely because they are publicly reachable.
## Compatibility checks
The `api/` directory contains the evidence used by CI:
- `stability.json` records package tiers, compatibility baselines, and snapshot
hashes;
- `snapshots/` records the explicit all-feature Apple ARM64 Rust API and the
manifest, feature, dependency, target, and MSRV contract; and
- `fixtures/` compiles recommended and retained import paths as an external
consumer.
These checks catch accidental changes, but they do not replace platform builds,
protocol interoperability tests, or manual review. In particular, the API
snapshot omits auto-derived, auto-trait, and blanket implementations and is not
by itself a complete SemVer verdict.
Run the checks with:
```sh
python3 tools/check-api-baseline.py
python3 tools/check-api-manifest.py
python3 tools/check-api-compatibility.py
cargo check --manifest-path api/fixtures/Cargo.toml --locked
cargo check --manifest-path api/fixtures/Cargo.toml --all-features --locked
```
After reviewing an API change, run
`python3 tools/check-api-baseline.py --update` and commit the source and snapshot
changes together. CI compares snapshots with the current source; compatibility
checks retain the historical baseline.
+2180
View File
File diff suppressed because it is too large. Load diff
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "rns-application-api-fixture"
version = "0.0.0"
edition = "2024"
publish = false
[workspace]
[features]
default = []
all = ["rns-runtime/ble", "rns-runtime/rnode-tcp", "rns-runtime/serial"]
[dependencies]
rns-protocol = { path = "../../crates/rns-protocol" }
rns-identity = { path = "../../crates/rns-identity" }
rns-transport = { path = "../../crates/rns-transport" }
rns-runtime = { path = "../../crates/rns-runtime", default-features = false }
+193
View File
@@ -0,0 +1,193 @@
//! External-consumer compile contract for canonical and retained Reticulum paths.
/// Advanced actor ownership uses detached discovery snapshots, never map edits.
pub mod recursive_discovery {
use rns_transport::actor::{DiscoveryPathRequest, TransportActor};
use rns_transport::messages::InterfaceId;
use rns_transport::path_discovery::{DiscoveryAdmission, DiscoveryError};
pub fn request(
actor: &mut TransportActor,
destination: [u8; 16],
interface: InterfaceId,
) -> Result<DiscoveryAdmission, DiscoveryError> {
actor.request_recursive_discovery(destination, interface)
}
pub fn observe_and_cancel(actor: &mut TransportActor, destination: &[u8; 16]) {
if let Some(snapshot) = actor.discovery_path_request(destination) {
let _: DiscoveryPathRequest = snapshot.clone(); // retained import
let _ = (snapshot.destination_hash(), snapshot.deadline());
for requester in snapshot.requesters() {
let _ = (requester.interface_id(), requester.destination_hash());
actor.cancel_discovery_requester(requester);
}
}
let _ = actor.discovery_path_requests();
}
}
pub mod canonical {
use rns_runtime::prelude::{
AnnounceSubscription, DestinationResolveError, DestinationResolveOptions,
LinkSessionHandle, PacketReceiptHandle, RecalledDestination, ReticulumHandle,
resolve_destination_on_transport,
};
pub fn compile_surface() {
let _ = resolve_destination_on_transport;
let _ = std::mem::size_of::<DestinationResolveOptions>();
let _ = std::mem::size_of::<DestinationResolveError>();
let _ = std::mem::size_of::<ReticulumHandle>();
let _ = std::mem::size_of::<RecalledDestination>();
let _ = std::mem::size_of::<AnnounceSubscription>();
let _ = std::mem::size_of::<PacketReceiptHandle>();
let _ = std::mem::size_of::<LinkSessionHandle>();
let _ = ReticulumHandle::path_recovery_handle;
let _ = ReticulumHandle::link_endpoint_dispatch_handle;
let _ = rns_runtime::prelude::PathRecoveryHandle::try_invalidate_packet;
let _ = rns_runtime::prelude::PathRecoveryHandle::try_invalidate_link;
let _ = std::mem::size_of::<rns_runtime::prelude::PathRecoveryHandle>();
let _ = std::mem::size_of::<rns_runtime::prelude::PathRecoveryOutcome>();
let _ = std::mem::size_of::<rns_runtime::prelude::PathRecoveryError>();
}
}
/// Advanced ownership remains opt-in and module-qualified.
pub mod delivery_ownership {
use rns_runtime::link_manager::{LinkManager, LinkManagerAccountingEvent};
use rns_runtime::prelude::ReticulumHandle;
pub fn install_dispatch(runtime: &ReticulumHandle, manager: &mut LinkManager) {
manager.set_link_endpoint_dispatch_handle(runtime.link_endpoint_dispatch_handle());
}
pub fn observe_wait(event: &LinkManagerAccountingEvent) {
match event {
LinkManagerAccountingEvent::OutboundPacketWait {
receipt,
started_at,
timeout,
awaiting_admission,
cancellation,
} => {
let _ = (
receipt.link_id,
receipt.packet_hash,
started_at,
timeout,
awaiting_admission,
cancellation,
);
}
LinkManagerAccountingEvent::OutboundResourceWait {
link_id,
resource_id,
started_at,
timeout,
} => {
let _ = (link_id, resource_id, started_at, timeout);
}
_ => {}
}
}
}
pub mod legacy {
use rns_runtime::destination_resolver::{
DestinationResolveError, DestinationResolveOptions, resolve_destination_on_transport,
};
use rns_runtime::link_session::LinkSessionHandle;
use rns_runtime::reticulum::{
AnnounceSubscription, PacketReceiptHandle, RecalledDestination, ReticulumHandle,
};
pub fn compile_surface() {
let _ = resolve_destination_on_transport;
let _ = std::mem::size_of::<DestinationResolveOptions>();
let _ = std::mem::size_of::<DestinationResolveError>();
let _ = std::mem::size_of::<ReticulumHandle>();
let _ = std::mem::size_of::<RecalledDestination>();
let _ = std::mem::size_of::<AnnounceSubscription>();
let _ = std::mem::size_of::<PacketReceiptHandle>();
let _ = std::mem::size_of::<LinkSessionHandle>();
}
}
/// Strict application ownership is additive; legacy imports above remain valid.
pub mod shared_ownership {
use rns_runtime::shared_instance::{
InstancePolicy, SharedInstanceCredentials, SharedInstanceEndpoint,
};
pub fn compile_surface() {
let endpoint = SharedInstanceEndpoint::Tcp {
packet_port: 37428,
control_port: 37429,
};
let credentials = SharedInstanceCredentials::new(endpoint.clone(), vec![1; 17]).unwrap();
let _ = InstancePolicy::SharedClient(credentials);
let _ = InstancePolicy::SharedOwnerAt(endpoint);
let _ = rns_runtime::reticulum::init_with_policy;
let _ = rns_runtime::reticulum::ReticulumHandle::shared_instance_state;
let _ = rns_runtime::reticulum::ReticulumHandle::startup_interface_failures;
}
}
/// The 1.3 discovery API distinguishes unknown components from true zeros.
pub mod nullable_discovery {
use rns_transport::discovery::DiscoveryInterfaceConfig;
use rns_transport::discovery::app_data::DiscoveryInfo;
pub fn literal() -> DiscoveryInfo {
DiscoveryInfo {
name: "coordinate-fixture".into(),
interface_type: "BackboneInterface".into(),
latitude: Some(0.0),
longitude: Some(0.0),
height: None,
..DiscoveryInfo::default()
}
}
pub fn configured() -> DiscoveryInterfaceConfig {
let mut config =
DiscoveryInterfaceConfig::backbone("relay".into(), "127.0.0.1".into(), 4965);
config.latitude = Some(0.0);
config.longitude = None;
config.height = Some(0.0);
config
}
pub fn read(info: &DiscoveryInfo) -> [Option<f64>; 3] {
[info.latitude, info.longitude, info.height]
}
}
/// Application admission carries non-cloneable authority separately from bytes.
pub mod application_packet_admission {
use rns_runtime::link_manager::{
InboundLinkPacket, LinkPacketReceiptOutcome, LinkPacketRejection,
};
pub async fn accept(packet: InboundLinkPacket) -> Option<LinkPacketReceiptOutcome> {
let (payload, receipt) = packet.into_parts();
let outcome = receipt?.accept().await.ok();
drop(payload);
outcome
}
pub fn compile_surface() {
let _ = LinkPacketRejection::InvalidPropagationStamp;
let _ = rns_runtime::link_manager::LinkManager::set_ordinary_packet_proof_strategy;
let _ = rns_runtime::interface_factory::InterfacePostInit::try_from_section;
let _ = rns_runtime::config::ifac::parse_ifac_size;
let _ = rns_runtime::config::ifac_lock::ConfigWriteLock::acquire;
let _ = rns_identity::persistence::durable_write;
let _ = rns_identity::persistence::durable_reconcile_hash;
let _ = rns_transport::messages::InterfacePacketCapacity::new(500, 508, false);
let _ = rns_transport::messages::InterfaceTransportSender::new;
let _ = rns_transport::link_messages::dispatch_link_request;
let _ = rns_transport::link_messages::LinkRequestDispatchError::NoInterface;
let _ = rns_transport::ifac::try_ifac_sign;
let _ = rns_protocol::resource_control::check_control_frame;
}
}
+116
View File
@@ -0,0 +1,116 @@
# Migrating to rsReticulum 1.3
Version 1.3 combines two discovery API changes since the published 1.2 release:
owned recursive discovery operations and independently optional interface
coordinates. Both changes belong to this release.
This project's version convention permits breaking Rust APIs in a minor release.
Version 1.3 is not source-compatible with direct mutation of the 1.2 discovery
map. Cargo's default caret requirement `"1.2"` permits 1.3; use an explicit
compatible line (for example `"~1.3.0"`) or an exact reviewed Git revision.
Existing external dependency requirements cannot be changed retroactively.
Packet, signature, RPC, and AutoInterface port formats remain unchanged.
Normal applications keep runtime `request_path`, finite destination resolution
and `PathRecoveryHandle`. They do not need this advanced actor API.
## Advanced synchronous actor owners
| Before | Supported replacement |
| --- | --- |
| Read `actor.discovery_path_requests[&destination]` | `actor.discovery_path_request(&destination)` returns an optional detached snapshot |
| Iterate the public map | `actor.discovery_path_requests()` returns snapshots sorted by destination |
| Read one `requesting_interface` | Iterate `snapshot.requesters()` and read each token's `interface_id()` |
| Read `timeout` | `snapshot.deadline()` is the original absolute Unix-seconds expiry |
| Insert a record to participate in recursive discovery | `actor.request_recursive_discovery(destination, interface)` validates admission and starts/joins the one bounded search |
| Remove/edit a record to cancel one requester | `actor.cancel_discovery_requester(token)` removes only that registration |
| Copy/extend a deadline | Clone a snapshot for observation; callers cannot renew an existing operation |
`actor::DiscoveryPathRequest` remains an import path, re-exporting the type in
`path_discovery`. Its public fields and `Copy` contract are removed deliberately.
The old single-requester shape could silently discard other registrations when
edited. Keeping a mutable compatibility mirror would retain that defect.
One operation admits at most 64 distinct requester channel generations; the
actor admits at most 1,024 destinations. Repeated joins of the same registration
return the same token without a new fanout or deadline. Requester identity is an
interface generation, not a count of individual people sharing one radio.
Snapshots are not live views. A removed first requester disappears from new
snapshots while other requesters remain. Offline but still registered/open
requesters may remain waiting; no response is sent while they are offline.
Expiry and interface replacement are checked without requiring a prior tick.
Tokens are opaque and actor/operation/registration-specific. Cloning or dropping
one does not change ownership. Cancellation is explicit and cannot act on a new
operation, a cancelled-and-rejoined requester, another actor, or a replacement
channel that reused the numeric ID. Cancelling the last waiter removes related
unadmitted search bytes; cancellation cannot recall transmitted bytes.
The advanced request API requires transport forwarding, an unknown nonlocal
destination, and an available normal interface with eligible discovery policy.
Typed errors distinguish policy, availability and capacity failures. It uses
normal ingress/egress limits and a new wire tag only for a newly started search.
`DiscoveryAdmission::started()` is local ownership/fanout intent, not a radio or
delivery receipt. Driver backpressure and network loss still require normal
caller policy. Normal runtime lookups should not use recursive actor control.
Use the compiled external fixture's `recursive_discovery` module as an example.
No shared IPC/JNI or application UI is added by this change. Package stability
classifications remain provisional; the compatibility gate records exactly the
approved removals and continues rejecting unrelated API loss.
## Interface discovery coordinates
The six public `latitude`, `longitude`, and `height` fields in `DiscoveryInfo`
and `DiscoveryInterfaceConfig` change from `f64` to `Option<f64>`, including the
re-export of `DiscoveryInterfaceConfig` from `rns_transport::discovery`.
Unknown coordinates are `None`; known coordinates, including zero, are `Some`.
The components are independent, so a known latitude and longitude do not imply
a known height. `Default` and discovery convenience constructors leave them
unknown. Update struct literals and assignments accordingly:
```rust,ignore
// Before
config.latitude = 0.0;
config.longitude = -105.0;
config.height = 0.0;
// After: latitude is genuinely zero; height is unknown.
config.latitude = Some(0.0);
config.longitude = Some(-105.0);
config.height = None;
```
Consumers should match the options or use `if let Some(value)` when displaying
or using a component. Do not use `unwrap_or(0.0)` to turn an unknown location
into a real map position. This change does not add new coordinate range rules.
## Wire, configuration, and storage
The discovery map retains its existing keys. An unknown component is encoded
as MessagePack `nil`, matching Python Reticulum; a known component remains a
number. Missing configuration leaves a component unknown, while an explicit
zero remains known. Existing configuration key precedence and units are retained.
No new wire protocol version or storage directory is required.
The Rust decoder continues accepting integer coordinates and missing coordinate
keys as a leniency: integers become `Some`, and missing values become `None`.
Those forms are not a claim of strict Python validation parity. Valid Python
`nil`, partial-coordinate, and floating-point records are supported.
Existing numeric discovery records remain numeric on disk reload. Old stored
zero cannot reveal whether it was deliberately configured or produced by the
previous defaulting behavior, so it is preserved as `Some(0.0)`. A fresh valid
announcement can replace it. Records containing `nil` or absent location keys
load as `None`. Downgrading to older Rust versions loses this distinction:
those versions coerce stored unknown components to zero.
`rnstatus-rs` represents unknown components as JSON `null`; text output uses
presence instead of treating zero as absent. This does not change an embedding
application's separate map display or location-sharing policy.
The historical API compatibility floor is retained. The exact removal ledger
contains three recursive-ownership paths and nine coordinate paths for six
fields because three are also re-exported. No unrelated removals are authorized.
+186
View File
@@ -0,0 +1,186 @@
# Migrating to the 1.4 source API
The 1.4 line is published as v1.4.0 and is the source line Ratspeak builds
from. These APIs and migration commands require a 1.4 build.
The 1.4 source line introduces explicit interface-capacity ownership and durable
application admission. Existing published releases are unchanged. Migrate
Reticulum dependents together to ~1.4.0; a source version alone is not publication.
Follow [capacity, IFAC configuration, receipts and timing](capacity-and-receipts.md)
for the full API and configuration transition. In particular:
- Replace `InterfacePostInit::from_section` with fallible `try_from_section`,
and propagate semantic configuration errors before spawning interfaces.
- `LinkManager::set_link_packet_channel` returns a result. The legacy tuple
receiver cannot enable ProveApp; use the bounded typed packet channel and
exact endpoint binding for application-controlled receipts.
- Custom interface handles and entries must supply exact owner and typed packet
capacity facts. Construct their bound sender before producer tasks start.
Link endpoint bindings retain the interface owner captured from the admitted
request/proof, rather than looking up whichever interface currently has an ID.
- Request admission and proof validation are separate. Retain one attempt-owned
result and deadline; cancelled/refused attempts cannot change a replacement.
- `rns_interface::rnode::RNodeStream` is an opaque struct; its `Serial` and `Tcp`
variants are no longer public. Open streams with `open_serial` or
`connect_tcp`; `try_clone`, `description`, and the `Read`/`Write`
implementations are unchanged.
Build `InterfaceStatRpcEntry` with `..Default::default()` and `InterfaceEntry`
with `..InterfaceEntry::new(...)`, so fields added on the 1.4 line stay
source compatible.
`rns_link::mtu_discovery::SignallingData` remains a public re-export of the
shared `rns_wire::link_signalling::SignallingData`; existing imports and checked
handshake callers can continue using that alias. Cargo-public-api renders
canonical type paths from rns-wire, so its twelve moved snapshot lines are
explicitly recorded despite preserved source identity. `new/pack/unpack` remain
low-level representation helpers; use checked signalling APIs for admission.
`rpc::InterfaceStatEntry::ifac_size` is now `Option<usize>`, `None` when the
interface has no IFAC, and the entry gains `ifac_signature` and `ifac_netname`,
as in Python's interface stats. Interface sections start only when
`interface_enabled` or `enabled` is true; add `enabled = yes` to sections that
relied on the old default. `ConfigSection::interface_enabled`, `has_enable_key`
and `invalid_enable_key` expose that rule to embedders.
Strict persistence accepts every filesystem; `DurabilityUnsupported` no longer
reports an unqualified filesystem. `persistence::storage_risk` classifies network
or user-space (`Remote`) and RAM-backed (`Volatile`) storage so applications can
warn their users.
`I2PServerConfig` gains `b32`, which receives the server's b32 address when
SAM creates its session, and `key_path`, the file that keeps the server's
private key, and so its address, across sessions; the runtime sets it to
Python's key file under `storage/i2p`. `i2p::destination_b32` derives the
address from a SAM private key; build the config with `new`.
`discovery::announcer::Announcer::reconfigure` replaces a registered
interface's config but keeps its announce interval.
`TunnelEntry::interface_id` is now `Option<InterfaceId>`, `None` while the
tunnel is unbound, instead of the id-0 sentinel. `spawn_local_server` and
`spawn_i2p_server` take the listener's allocated `InterfaceId`, which their
accepted clients report as `parent_id`. `InterfaceEntry::parent_id` carries it
into transport; set it from `InterfaceHandle::parent_id`. Persisted tunnels now
load unbound into the tunnel table, so `TransportActor::pending_tunnel_entries`
is gone.
`TunnelSynthesisData::unpack` accepts exactly 176 bytes, and `is_signed` is
the check transport applies before admitting one. The TCP, Backbone and I2P
client configs' `python_name` is the Python `str()` their syntheses hash. Announces join the
tunnel named by their interface's latest synthesis, which `handle_tunnel` and
`TunnelTable::insert` record and `TunnelTable::void_interface` clears; writing
`interface_id` directly no longer rebinds an interface. `handle_tunnel` no
longer takes a timeout: a tunnel expires `TUNNEL_TIMEOUT` after its synthesis,
as in Python. `TunnelTable::cull_expired` and `cull_expired_batch` also drop
tunnels set to expire more than twice `TUNNEL_TIMEOUT` ahead.
`TcpClientConfig`, `BackboneClientConfig` and `I2PClientConfig` gain
`tunnel_identity`. With a `TunnelIdentity` set, the client opens every
connection with a tunnel synthesis signed by it; the runtime sets it from
`ReticulumHandle::transport_identity`. Build these configs with `new` so the
field defaults to `None`. A KISS-framed TCP client never synthesizes. Every
TCP, Backbone and I2P client, the shared-instance TCP client included, drops
its queued traffic when a connection opens after an outage or a failed
attempt, and the Unix shared-instance client drops it when it reconnects.
`TcpClientConfig` gains `i2p_tunneled`, which gives a TCP connection tunneled
over I2P Python's longer I2P socket timeouts; the runtime reads it from the
interface's `i2p_tunneled` key. Build the config with `new` so it defaults to
`false`.
Interface stats carry Python 1.5's per-interface counters.
`IngressController` counts announces and path requests received and sent;
`InterfaceEntry` gains `protocol_violations`, `ifac_violations`,
`packet_filter_hits` and `tx_dropped_bytes`; `InterfaceStatRpcEntry` reports
all of them plus `parent_id`; `rpc::InterfaceStatEntry` carries them, the
listener's name, and now implements `Default`. Build it with
`..Default::default()`. The control port and remote management answer with
one Python-shaped stats dict, so `remote_management_schema` is removed:
decode a `/status` answer as `[stats, link_count?]`, and a `/path` answer with
`rpc::decode_response_for_request`. Remote management answers on the transport
identity, so `rnstatus -R` and `rnpath -R` take its hash. A node with
`enable_transport` off and no `static_transport_identity` gets a new management
destination each start, as in Python. The runtime no longer reads
`storage/remote_management_identity`, and leaves the file in place for the
operator to delete.
Interface discovery carries Python 1.5's implementation keys.
`DiscoveryInfo` gains `impl_name` and `impl_version`; build it with
`..Default::default()`. `discovery::autoconnect::qualifies` applies Python's
auto-connect rule, with `ReticulumConfig::autoconnect_unverified_implementations`
as its opt-in. The receiver no longer stores types that are never listed, so
`discovery::Reason` gains `UnlistedType` and becomes `#[non_exhaustive]`, so a
match needs a wildcard arm.
`rns_link::clock::ContinuousInstant` reads a monotonic clock that keeps
counting while the system is suspended: `CLOCK_BOOTTIME` on Linux and Android,
`CLOCK_MONOTONIC_RAW` on Apple platforms and the performance counter on
Windows, with `std::time::Instant` as a best-effort fallback elsewhere. Use it
for a deadline that must hold in real time across a sleep. Check that deadline
on a regular tick and when the runtime resumes; do not assume an outstanding
async timer enforces the same suspend-inclusive deadline on every platform.
Readings are process-local and do not convert to or from `std::time::Instant`.
rns-link gains the target dependencies `libc` (unix) and `windows-sys`
(Windows), so dependents that build with `--locked` refresh their lock files.
`hkdf::derive_key_64` returns `Zeroizing<[u8; 64]>` and `hkdf::hkdf_sha256`
returns `Zeroizing<Vec<u8>>`, so derived keys are wiped when they are dropped.
Pass `&key[..]` where a slice is expected and compare `&okm[..]` with a plain
`Vec`; the bytes are unchanged. `Zeroizing<[u8; 64]>` is not `Copy`, so code
that copied the key borrows it instead. `token::decrypt` still returns
`Vec<u8>` and wipes its buffer when decryption fails; wrap a secret plaintext
in `Zeroizing`. `Identity::from_file` reads at most 1025 bytes and refuses a
file larger than 1 KiB.
`InterfacePostInit::ifac_passphrase` is `Option<Zeroizing<String>>`, so the
passphrase is wiped when the options are dropped: read it with
`.as_deref().map(String::as_str)` and wrap a new one in `Zeroizing::new`.
`RuntimeInterfaceIfacConfig` prints `<redacted>` in place of its passphrase.
`InterfaceEntry::ifac_key` is `Option<rns_identity::ifac::IfacKey>`, one
allocation that clones share and that is wiped when the last one drops, so
interface tables never copy the key. `with_ifac` still takes the key bytes;
otherwise set `Some(key.into())` or `IfacKey::derive(network_name,
passphrase)`, and read the bytes through `&*key`.
rns-crypto re-exports `zeroize` for crates that hold its wiped types without
depending on it, and `rns_identity::persistence::read_secret_file` reads a
bounded secret file into one wiped buffer. An I2P interface refuses a key file
larger than 16 KiB and a SAM reply line longer than 64 KiB, and
`I2PServerConfig` prints `<redacted>` in place of a configured key.
rns-crypto enables the `zeroize` features of `aes` and `cbc`, so AES key
schedules and CBC state are wiped when dropped; dependents that build with
`--locked` refresh their lock files.
The compatibility floor remains unchanged. Its cumulative exact-removal list
also retains the already-reviewed [1.3 migration](1.3.md) for discovery ownership
and nullable coordinates; it is not reclassified as a new 1.4 change. Additive
struct fields can require literal-construction updates even when no old public
line disappears. No whole-crate waiver or baseline reset is used.
Disk-backed Destination handlers can use
`LinkManager::register_deferred_request_handler` after installing an exact
endpoint dispatch handle. Existing synchronous handlers remain supported. The
new callback receives `DestinationRequest` and a one-shot
`DeferredRequestResponder`; move both into the actual bounded worker and return
promptly. Read `response_byte_limit()` before allocating or retiring stored
items. Check `is_cancelled()` before work, and retain the responder until the
worker has actually stopped. `respond(RequestOutcome)` returns a typed completion
receiver: `Sent` means the packet was queued or the response Resource started,
not that the remote application accepted it.
Admission reserves one of four process-wide slots and a conservative share of
256 MiB before invoking the callback. Charge is sixteen times request capacity,
eight times the effective response capacity, plus 16 MiB of construction scratch.
The token may report a smaller limit than registration requested. This accounts
for the bounded handler's planning structures and current response/Resource
construction; arbitrary application allocations are outside this contract.
Response allocation capacity, including optional follow-up Resource metadata,
must fit the token. Requests expire after 120 seconds. Refused admission never
invokes the callback. Dropping a manager revokes response authority while a live
worker retains its reservation; completed response Resources retain that same
reservation until terminal cleanup.
Deferred handlers require exact endpoint ownership. Queued response packets and
Resource advertisement, part, request, hash-map update and cancellation commands
carry `SendLinkEndpointExact` authority. The actor rejects an old token even when
a replacement uses the same Link ID, interface and role. Existing legacy send
commands remain available; they do not acquire this generation-bound guarantee.
+120
View File
@@ -0,0 +1,120 @@
# Capacity, IFAC configuration, and application packet receipts
These changes are part of the 1.4.0 line, published as v1.4.0 and used by
Ratspeak. They are not in the 1.3.0 tools. The migration command below
requires a 1.4 build.
## Interface ownership and packet capacity
`InterfaceHandle` and `InterfaceEntry` carry an `InterfaceOwner` and an
`InterfacePacketCapacity`. The historical `mtu` field remains available for
statistics. Admission uses the separate clear-packet and IFAC-bearing wire
budgets, and `link_mtu_upgrade` explicitly controls upgrade permission.
Custom drivers must create `InterfaceTransportSender` before starting any task
or callback that can publish input or cleanup events. Copy its `owner()` into
the handle, and retain clones of that sender across carrier reconnects. Each
accepted child and replacement registration needs a fresh sender and owner.
Send inbound packets and driver-originated deregistration through this sender;
raw unowned events are refused. Do not wrap messages twice. Coordinated IFAC or
capacity changes use a new owner revision and rebind producers; ordinary
bitrate/online changes do not establish a new capacity promise.
Async driver sends wait until the actor accepts that owner registration. This
keeps the first packet of a newly accepted connection from racing registration;
retiring the owner releases pending sends with an error. Custom actor harnesses
must explicitly mark the owner registered when they accept its registration.
The conservative custom-driver default is `InterfacePacketCapacity::base(mtu)`.
Explicitly declare additional IFAC headroom or upgrade support only when the
whole-packet driver guarantee supports it. Framing and BLE fragmentation are
outside these budgets. TCP fixed MTUs must fit the actual wire budget after IFAC.
Active IFAC also limits the complete wire packet to HKDF-SHA256's 8160-byte
expansion limit; subtract the configured tag size for its clear-packet ceiling.
General Links require at least 500 clear packet bytes. An interface with less
capacity can still carry fitting non-Link traffic, but reports
`LinkCapacityUnavailable` for general Links. RNode's 508-byte wire budget carries
500 clear bytes with IFAC tags up to eight bytes. Larger tags are never silently
weakened. Current local endpoints remain capped at 500; safe transit can preserve
larger peer offers. Legacy or zero Link signalling means 500; nonzero values below
500, malformed shapes, disabled endpoint modes, and proofs above the original
offer are rejected before endpoint state changes.
Initiators send `SendLinkRequest` with a per-attempt oneshot result, or call
`link_messages::dispatch_link_request`. The result preserves typed capacity
errors before waiting for a proof. Keep one establishment deadline around both
admission and proof waiting. Drop the result receiver when cancelling: an actor
that has not dispatched that attempt then emits no request. This acknowledgement
means local driver admission, not peer receipt. It does not replace signature
verification or the exact interface owner retained from the request/proof path.
## Explicit IFAC units
Use `ifac_size_unit = bits` with `ifac_size` to state the unit explicitly.
Valid bit values are multiples of eight from 8 to 512. Without the unit key,
values from 1 to 64 are rejected as ambiguous; valid values from 72 to 512
are accepted as bits. The byte escape hatch is `ifac_size_bytes`, from 1 to 64;
it cannot coexist with either bits field. Migrate ambiguous old values using
their known source convention; the parser does not infer that convention.
Omitting all size keys retains the interface class default. Explicit malformed
sizes remain errors even when credentials are absent. Disabled interfaces may
retain old settings, but must be migrated before enabling them.
`InterfacePostInit::try_from_section` replaces the infallible constructor. Use
the shared `config::ifac::parse_ifac_size` decoder rather than another parser.
`validate_config_capacity` checks explicit driver promises before spawn.
Malformed file syntax still fails the file; semantic errors isolate the affected
enabled interface.
Preview an explicitly selected migration without starting the network:
```sh
rnsd-rs -c /path/to/config-directory config ifac-units --source-units bytes --interface Radio
```
Use `--source-units bits` when that is the known source convention. Add `--write`
to publish the reviewed plan. Publication checks that the source is unchanged,
takes the shared OS-backed config lock, and retains a unique private backup.
An older binary requires restoring its original configuration before rollback.
## Ordinary Link packet proofs
Ordinary `DATA` with context `None` follows explicit `ProofStrategy` policy.
`ProveNone` delivers without a proof. `ProveAll` preserves automatic proofs and
delivers independently of proof queue admission. `ProveApp` requires both an
exact endpoint dispatch handle and the bounded typed inbound channel; it cannot
use the legacy tuple channel. Configuration setters return a result.
For application-controlled admission, receive `InboundLinkPacket`, retain its
`Bytes` and non-cloneable `LinkPacketReceipt` through validation and persistence,
then consume the receipt with `accept()`. Awaiting its result distinguishes local
driver admission (`Sent`) from expiration, closed ownership, dropping, or failure.
`Sent` does not mean physical radio transmission or remote delivery. Dropping the
receipt produces no proof. `reject_and_close(InvalidPropagationStamp)` orders the
protocol rejection before teardown when it can be admitted. Use
`close_without_proof()` for a storage/quota failure that requires teardown without
claiming an invalid propagation stamp; it retains the same exact-owner checks.
Authority is tied to the exact Link generation. Expired, closed, or replaced
owners cannot send a late proof. Payload clones retain admission credits until
they are actually dropped, even if the receipt expires. Limits are 64 packets
and 2 MiB per Link, and 256 packets and 8 MiB process-wide for this ordinary
application-controlled ingress. Resource, Channel, RPC, Direct, and voice
protocol owners retain their own admission rules.
## Durable storage and local timing
`rns_identity::persistence::durable_write` returns a privately constructed receipt
only after exact verification and the native platform barriers succeed. It is
separate from the existing cache writer. Errors distinguish pre-publication
failure from `CommitUncertain`; keep recovery material and withhold higher-level
acceptance on uncertainty. `durable_reconcile` and bounded streaming
`durable_reconcile_hash` renew barriers as well as verifying bytes. A receipt
attests those calls, not hardware infallibility or the provenance of a message.
Directory migration still requires an application journal and native recovery.
Use `Link::try_extend_establishment_timeout` for checked timeout extension.
Invalid floating-point times and unrepresentable deadlines are rejected before
transport side effects. Channel RTTs have a finite local ceiling and its sending
window remains bounded even when public tuning fields contain extreme values.
File diff suppressed because it is too large. Load diff
+92
View File
@@ -0,0 +1,92 @@
pub mod rns_crypto
pub use rns_crypto::zeroize
pub mod rns_crypto::aes_cbc
pub enum rns_crypto::aes_cbc::AesCbcError
pub rns_crypto::aes_cbc::AesCbcError::DecryptionFailed
pub rns_crypto::aes_cbc::AesCbcError::EncryptionFailed
pub rns_crypto::aes_cbc::AesCbcError::InvalidIvLength(usize)
pub rns_crypto::aes_cbc::AesCbcError::InvalidKeyLength(usize)
pub rns_crypto::aes_cbc::AesCbcError::NotBlockAligned
pub fn rns_crypto::aes_cbc::decrypt(&[u8], &[u8], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_crypto::aes_cbc::AesCbcError>
pub fn rns_crypto::aes_cbc::encrypt(&[u8], &[u8], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_crypto::aes_cbc::AesCbcError>
pub mod rns_crypto::ed25519
pub enum rns_crypto::ed25519::Ed25519Error
pub rns_crypto::ed25519::Ed25519Error::InvalidPublicKey
pub rns_crypto::ed25519::Ed25519Error::InvalidSignature
pub rns_crypto::ed25519::Ed25519Error::VerificationFailed
pub struct rns_crypto::ed25519::Ed25519PrivateKey
impl rns_crypto::ed25519::Ed25519PrivateKey
pub fn rns_crypto::ed25519::Ed25519PrivateKey::from_bytes(&[u8; 32]) -> Self
pub fn rns_crypto::ed25519::Ed25519PrivateKey::generate() -> Self
pub fn rns_crypto::ed25519::Ed25519PrivateKey::public_key(&self) -> rns_crypto::ed25519::Ed25519PublicKey
pub fn rns_crypto::ed25519::Ed25519PrivateKey::sign(&self, &[u8]) -> [u8; 64]
pub fn rns_crypto::ed25519::Ed25519PrivateKey::to_bytes(&self) -> [u8; 32]
impl core::ops::drop::Drop for rns_crypto::ed25519::Ed25519PrivateKey
pub fn rns_crypto::ed25519::Ed25519PrivateKey::drop(&mut self)
impl zeroize::Zeroize for rns_crypto::ed25519::Ed25519PrivateKey
pub fn rns_crypto::ed25519::Ed25519PrivateKey::zeroize(&mut self)
pub struct rns_crypto::ed25519::Ed25519PublicKey
impl rns_crypto::ed25519::Ed25519PublicKey
pub fn rns_crypto::ed25519::Ed25519PublicKey::from_bytes(&[u8; 32]) -> core::result::Result<Self, rns_crypto::ed25519::Ed25519Error>
pub fn rns_crypto::ed25519::Ed25519PublicKey::to_bytes(&self) -> [u8; 32]
pub fn rns_crypto::ed25519::Ed25519PublicKey::verify(&self, &[u8], &[u8; 64]) -> core::result::Result<(), rns_crypto::ed25519::Ed25519Error>
pub mod rns_crypto::hkdf
pub enum rns_crypto::hkdf::HkdfError
pub rns_crypto::hkdf::HkdfError::ExpansionFailed
pub rns_crypto::hkdf::HkdfError::OutputTooLong(usize)
pub fn rns_crypto::hkdf::derive_key_64(&[u8], &[u8]) -> core::result::Result<zeroize::Zeroizing<[u8; 64]>, rns_crypto::hkdf::HkdfError>
pub fn rns_crypto::hkdf::hkdf_sha256(usize, &[u8], core::option::Option<&[u8]>, core::option::Option<&[u8]>) -> core::result::Result<zeroize::Zeroizing<alloc::vec::Vec<u8>>, rns_crypto::hkdf::HkdfError>
pub mod rns_crypto::hmac
pub fn rns_crypto::hmac::hmac_sha256(&[u8], &[u8]) -> [u8; 32]
pub fn rns_crypto::hmac::hmac_verify(&[u8], &[u8], &[u8; 32]) -> bool
pub mod rns_crypto::pkcs7
pub enum rns_crypto::pkcs7::Pkcs7Error
pub rns_crypto::pkcs7::Pkcs7Error::EmptyInput
pub rns_crypto::pkcs7::Pkcs7Error::InconsistentPadding
pub rns_crypto::pkcs7::Pkcs7Error::InvalidPaddingValue(u8)
pub fn rns_crypto::pkcs7::pad(&[u8]) -> alloc::vec::Vec<u8>
pub fn rns_crypto::pkcs7::unpad(&[u8]) -> core::result::Result<&[u8], rns_crypto::pkcs7::Pkcs7Error>
pub mod rns_crypto::random
pub fn rns_crypto::random::random_16() -> [u8; 16]
pub fn rns_crypto::random::random_32() -> [u8; 32]
pub fn rns_crypto::random::random_bytes(usize) -> alloc::vec::Vec<u8>
pub mod rns_crypto::sha
pub fn rns_crypto::sha::full_hash(&[u8]) -> [u8; 32]
pub fn rns_crypto::sha::name_hash(&str) -> [u8; 10]
pub fn rns_crypto::sha::sha256(&[u8]) -> [u8; 32]
pub fn rns_crypto::sha::sha512(&[u8]) -> [u8; 64]
pub fn rns_crypto::sha::truncated_hash(&[u8]) -> [u8; 16]
pub mod rns_crypto::token
pub enum rns_crypto::token::TokenError
pub rns_crypto::token::TokenError::AuthenticationFailed
pub rns_crypto::token::TokenError::DecryptionFailed
pub rns_crypto::token::TokenError::EncryptionFailed
pub rns_crypto::token::TokenError::InvalidKeyLength(usize)
pub rns_crypto::token::TokenError::TooShort
pub const rns_crypto::token::AES128_BLOCKSIZE: usize
pub const rns_crypto::token::AES256_BLOCKSIZE: usize
pub const rns_crypto::token::DERIVED_KEY_LENGTH_LEGACY: usize
pub const rns_crypto::token::KEY_LENGTH: usize
pub const rns_crypto::token::LEGACY_KEY_LENGTH: usize
pub const rns_crypto::token::TOKEN_OVERHEAD: usize
pub fn rns_crypto::token::decrypt(&[u8], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_crypto::token::TokenError>
pub fn rns_crypto::token::encrypt(&[u8], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_crypto::token::TokenError>
pub fn rns_crypto::token::generate_key() -> zeroize::Zeroizing<alloc::vec::Vec<u8>>
pub mod rns_crypto::x25519
pub struct rns_crypto::x25519::X25519PrivateKey
impl rns_crypto::x25519::X25519PrivateKey
pub fn rns_crypto::x25519::X25519PrivateKey::exchange(&self, &rns_crypto::x25519::X25519PublicKey) -> [u8; 32]
pub fn rns_crypto::x25519::X25519PrivateKey::from_bytes(&[u8; 32]) -> Self
pub fn rns_crypto::x25519::X25519PrivateKey::generate() -> Self
pub fn rns_crypto::x25519::X25519PrivateKey::public_key(&self) -> rns_crypto::x25519::X25519PublicKey
pub fn rns_crypto::x25519::X25519PrivateKey::to_bytes(&self) -> [u8; 32]
impl core::ops::drop::Drop for rns_crypto::x25519::X25519PrivateKey
pub fn rns_crypto::x25519::X25519PrivateKey::drop(&mut self)
impl zeroize::Zeroize for rns_crypto::x25519::X25519PrivateKey
pub fn rns_crypto::x25519::X25519PrivateKey::zeroize(&mut self)
pub struct rns_crypto::x25519::X25519PublicKey
impl rns_crypto::x25519::X25519PublicKey
pub fn rns_crypto::x25519::X25519PublicKey::from_bytes(&[u8; 32]) -> Self
pub fn rns_crypto::x25519::X25519PublicKey::to_bytes(&self) -> [u8; 32]
pub const rns_crypto::TOKEN_OVERHEAD: usize
pub fn rns_crypto::hex_encode(&[u8]) -> alloc::string::String
+431
View File
@@ -0,0 +1,431 @@
pub mod rns_identity
pub mod rns_identity::announce
pub enum rns_identity::announce::AnnounceError
pub rns_identity::announce::AnnounceError::HashCollision
pub rns_identity::announce::AnnounceError::HashMismatch
pub rns_identity::announce::AnnounceError::InvalidPublicKey
pub rns_identity::announce::AnnounceError::InvalidWireTime(u64)
pub rns_identity::announce::AnnounceError::NoPrivateKey
pub rns_identity::announce::AnnounceError::SignatureInvalid
pub rns_identity::announce::AnnounceError::TooShort(usize)
pub struct rns_identity::announce::AnnounceData
pub rns_identity::announce::AnnounceData::app_data: core::option::Option<alloc::vec::Vec<u8>>
pub rns_identity::announce::AnnounceData::name_hash: [u8; 10]
pub rns_identity::announce::AnnounceData::public_key: [u8; 64]
pub rns_identity::announce::AnnounceData::random_hash: [u8; 10]
pub rns_identity::announce::AnnounceData::ratchet: core::option::Option<[u8; 32]>
pub rns_identity::announce::AnnounceData::signature: [u8; 64]
impl rns_identity::announce::AnnounceData
pub fn rns_identity::announce::AnnounceData::create(&rns_identity::identity::Identity, &str, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>) -> core::result::Result<Self, rns_identity::announce::AnnounceError>
pub fn rns_identity::announce::AnnounceData::create_at(&rns_identity::identity::Identity, &str, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>, u64) -> core::result::Result<Self, rns_identity::announce::AnnounceError>
pub fn rns_identity::announce::AnnounceData::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_identity::announce::AnnounceData::unpack(&[u8], bool) -> core::result::Result<Self, rns_identity::announce::AnnounceError>
pub fn rns_identity::announce::AnnounceData::validate(&self, &[u8; 16]) -> core::result::Result<rns_identity::identity::Identity, rns_identity::announce::AnnounceError>
pub fn rns_identity::announce::AnnounceData::validate_destination_binding(&self, &[u8; 16], &rns_identity::identity::Identity, core::option::Option<&[u8; 64]>) -> core::result::Result<(), rns_identity::announce::AnnounceError>
pub fn rns_identity::announce::AnnounceData::validate_with_known_key(&self, &[u8; 16], core::option::Option<&[u8; 64]>) -> core::result::Result<rns_identity::identity::Identity, rns_identity::announce::AnnounceError>
pub fn rns_identity::announce::AnnounceData::verify_signature(&self, &[u8; 16]) -> core::result::Result<rns_identity::identity::Identity, rns_identity::announce::AnnounceError>
pub const rns_identity::announce::ANNOUNCE_TIME_MAX: u64
pub mod rns_identity::announce_state
pub struct rns_identity::announce_state::RatchetControlState
impl rns_identity::announce_state::RatchetControlState
pub fn rns_identity::announce_state::RatchetControlState::anchor_rotation_if_unknown(&mut self, u64)
pub fn rns_identity::announce_state::RatchetControlState::destination_hash(&self) -> [u8; 16]
pub fn rns_identity::announce_state::RatchetControlState::identity_hash(&self) -> [u8; 16]
pub fn rns_identity::announce_state::RatchetControlState::last_announce_wire(&self) -> core::option::Option<u64>
pub fn rns_identity::announce_state::RatchetControlState::last_rotation_wall(&self) -> core::option::Option<u64>
pub fn rns_identity::announce_state::RatchetControlState::load_verified(&std::path::Path, &rns_identity::identity::Identity, [u8; 16]) -> core::io::error::Result<Self>
pub fn rns_identity::announce_state::RatchetControlState::new([u8; 16], [u8; 16]) -> Self
pub fn rns_identity::announce_state::RatchetControlState::prepare_announce(&self, u64) -> core::io::error::Result<core::option::Option<Self>>
pub fn rns_identity::announce_state::RatchetControlState::rotation_due(&self, u64, u64) -> bool
pub fn rns_identity::announce_state::RatchetControlState::save_verified(&self, &std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<()>
pub fn rns_identity::announce_state::RatchetControlState::save_verified_durable(&self, &std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<()>
pub fn rns_identity::announce_state::RatchetControlState::with_rotation_at(&self, u64) -> Self
pub mod rns_identity::destination
#[repr(u8)] pub enum rns_identity::destination::AllowPolicy
pub rns_identity::destination::AllowPolicy::AllowAll = 1
pub rns_identity::destination::AllowPolicy::AllowList = 2
pub rns_identity::destination::AllowPolicy::AllowNone = 0
pub enum rns_identity::destination::DefaultAppData
pub rns_identity::destination::DefaultAppData::Dynamic(alloc::boxed::Box<(dyn core::ops::function::Fn() -> core::option::Option<alloc::vec::Vec<u8>> + core::marker::Send + core::marker::Sync)>)
pub rns_identity::destination::DefaultAppData::Static(alloc::vec::Vec<u8>)
#[repr(u8)] pub enum rns_identity::destination::DestType
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
pub rns_identity::destination::DestinationError::DecryptionFailed
pub rns_identity::destination::DestinationError::EncryptionUnavailable
pub rns_identity::destination::DestinationError::Identity(rns_identity::identity::IdentityError)
pub rns_identity::destination::DestinationError::IdentityMismatch
pub rns_identity::destination::DestinationError::InvalidAnnounceTime(f64)
pub rns_identity::destination::DestinationError::InvalidGroupKeyLength(usize)
pub rns_identity::destination::DestinationError::InvalidNameComponent(alloc::string::String)
pub rns_identity::destination::DestinationError::MissingIdentity
pub rns_identity::destination::DestinationError::NotGroup
pub rns_identity::destination::DestinationError::NotInbound
pub rns_identity::destination::DestinationError::NotSingle
pub rns_identity::destination::DestinationError::OutboundMissingIdentity
pub rns_identity::destination::DestinationError::PlainWithIdentity
pub rns_identity::destination::DestinationError::ProveNotSingle
pub rns_identity::destination::DestinationError::SigningUnavailable
pub enum rns_identity::destination::DestinationPacketError
pub rns_identity::destination::DestinationPacketError::Destination(rns_identity::destination::DestinationError)
pub rns_identity::destination::DestinationPacketError::LinkRuntimeRequired
pub rns_identity::destination::DestinationPacketError::LrproofRequiresLink
pub rns_identity::destination::DestinationPacketError::MissingIdentity
pub rns_identity::destination::DestinationPacketError::MissingTransportId
pub rns_identity::destination::DestinationPacketError::Packet(rns_wire::packet::PacketError)
pub enum rns_identity::destination::Direction
pub rns_identity::destination::Direction::In
pub rns_identity::destination::Direction::Out
#[repr(u8)] pub enum rns_identity::destination::ProofStrategy
pub rns_identity::destination::ProofStrategy::ProveAll = 35
pub rns_identity::destination::ProofStrategy::ProveApp = 34
pub rns_identity::destination::ProofStrategy::ProveNone = 33
pub struct rns_identity::destination::AnnounceTime
pub rns_identity::destination::AnnounceTime::cache: f64
pub rns_identity::destination::AnnounceTime::wire: u64
impl rns_identity::destination::AnnounceTime
pub fn rns_identity::destination::AnnounceTime::new(u64, f64) -> core::result::Result<Self, rns_identity::destination::DestinationError>
pub struct rns_identity::destination::Destination
pub rns_identity::destination::Destination::accept_link_requests: bool
pub rns_identity::destination::Destination::app_name: alloc::string::String
pub rns_identity::destination::Destination::dest_type: rns_identity::destination::DestType
pub rns_identity::destination::Destination::direction: rns_identity::destination::Direction
pub rns_identity::destination::Destination::hash: [u8; 16]
pub rns_identity::destination::Destination::identity_hash: core::option::Option<[u8; 16]>
pub rns_identity::destination::Destination::links: alloc::vec::Vec<[u8; 16]>
pub rns_identity::destination::Destination::local_ratchet_pub: core::option::Option<[u8; 32]>
pub rns_identity::destination::Destination::name: alloc::string::String
pub rns_identity::destination::Destination::name_hash: [u8; 10]
pub rns_identity::destination::Destination::only_validate_signature: bool
pub rns_identity::destination::Destination::proof_strategy: rns_identity::destination::ProofStrategy
pub rns_identity::destination::Destination::ratchets_enabled: bool
pub rns_identity::destination::Destination::ratchets_enforced: bool
pub rns_identity::destination::Destination::remote_ratchet_pub: core::option::Option<[u8; 32]>
impl rns_identity::destination::Destination
pub const rns_identity::destination::Destination::PR_TAG_WINDOW: f64
pub const rns_identity::destination::Destination::RATCHET_COUNT: usize
pub const rns_identity::destination::Destination::RATCHET_INTERVAL: u64
pub fn rns_identity::destination::Destination::accepts_links(&self) -> bool
pub fn rns_identity::destination::Destination::announce_packet(&mut self, &rns_identity::identity::Identity, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>, bool, core::option::Option<&[u8]>, f64) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::announce_packet_at(&mut self, &rns_identity::identity::Identity, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>, bool, core::option::Option<&[u8]>, rns_identity::destination::AnnounceTime) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::app_and_aspects_from_name(&str) -> (&str, alloc::vec::Vec<&str>)
pub fn rns_identity::destination::Destination::auto_identity(&self) -> core::option::Option<&rns_identity::identity::Identity>
pub fn rns_identity::destination::Destination::cached_path_response_packet(&mut self, &[u8], f64) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::check_request_allowed(&self, &[u8; 16], core::option::Option<&[u8; 16]>) -> bool
pub fn rns_identity::destination::Destination::clear_default_app_data(&mut self)
pub fn rns_identity::destination::Destination::compute_hash(&[u8; 10], core::option::Option<&[u8; 16]>) -> [u8; 16]
pub fn rns_identity::destination::Destination::create_announce(&mut self, &rns_identity::identity::Identity, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>, core::option::Option<&[u8]>, f64) -> core::result::Result<(alloc::vec::Vec<u8>, bool), rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::create_announce_at(&mut self, &rns_identity::identity::Identity, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>, core::option::Option<&[u8]>, rns_identity::destination::AnnounceTime) -> core::result::Result<(alloc::vec::Vec<u8>, bool), rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::decrypt(&self, &[u8], &rns_identity::identity::Identity) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::decrypt_with_ratchet_id(&self, &[u8], &rns_identity::identity::Identity, core::option::Option<&[[u8; 32]]>) -> core::result::Result<rns_identity::identity::DecryptionResult, rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::decrypt_with_ratchets(&self, &[u8], &rns_identity::identity::Identity, core::option::Option<&[[u8; 32]]>) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::deregister_request_handler(&mut self, &str) -> bool
pub fn rns_identity::destination::Destination::disable_ratchets(&mut self)
pub fn rns_identity::destination::Destination::enable_ratchets(&mut self, bool)
pub fn rns_identity::destination::Destination::encrypt(&self, &[u8], &rns_identity::identity::Identity, core::option::Option<&[u8; 32]>) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::expand_name(core::option::Option<&rns_identity::identity::Identity>, &str, &[&str]) -> core::result::Result<alloc::string::String, rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::generate_group_key(&mut self) -> core::result::Result<(), rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::get_ratchet_for_announce(&self) -> core::option::Option<[u8; 32]>
pub fn rns_identity::destination::Destination::get_request_handler(&self, &[u8; 16]) -> core::option::Option<&rns_identity::destination::RequestHandler>
pub fn rns_identity::destination::Destination::group_key(&self) -> core::result::Result<&[u8], rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::hash_from_name_and_identity(&str, core::option::Option<&[u8; 16]>) -> [u8; 16]
pub fn rns_identity::destination::Destination::hex_hash(&self) -> alloc::string::String
pub fn rns_identity::destination::Destination::hexhash(&self) -> alloc::string::String
pub fn rns_identity::destination::Destination::incoming_link_request(&mut self, [u8; 16]) -> bool
pub fn rns_identity::destination::Destination::link_count(&self) -> usize
pub fn rns_identity::destination::Destination::load_group_key(&mut self, &[u8]) -> core::result::Result<(), rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::new(core::option::Option<&rns_identity::identity::Identity>, rns_identity::destination::Direction, rns_identity::destination::DestType, &str) -> core::result::Result<Self, rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::new_with_aspects(core::option::Option<&rns_identity::identity::Identity>, rns_identity::destination::Direction, rns_identity::destination::DestType, &str, &[&str]) -> core::result::Result<Self, rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::on_link_established(&self, [u8; 16])
pub fn rns_identity::destination::Destination::pack_packet(&self, &[u8], core::option::Option<&rns_identity::identity::Identity>, core::option::Option<&[u8; 32]>, rns_identity::destination::DestinationPacketOptions) -> core::result::Result<rns_identity::destination::PackedDestinationPacket, rns_identity::destination::DestinationPacketError>
pub fn rns_identity::destination::Destination::prove(&self, &[u8], &rns_identity::identity::Identity, bool) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::ratchets_active(&self) -> bool
pub fn rns_identity::destination::Destination::receive(&self, u8, &[u8], &rns_identity::identity::Identity) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::receive_packet(&self, u8, &[u8], &[u8], &rns_identity::identity::Identity) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::receive_packet_with_ratchets(&self, u8, &[u8], &[u8], &rns_identity::identity::Identity, core::option::Option<&[[u8; 32]]>) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::register_request_handler(&mut self, &str, rns_identity::destination::AllowPolicy, core::option::Option<alloc::vec::Vec<[u8; 16]>>, bool) -> bool
pub fn rns_identity::destination::Destination::remove_link(&mut self, &[u8; 16])
pub fn rns_identity::destination::Destination::resolve_app_data(&self) -> core::option::Option<alloc::vec::Vec<u8>>
pub fn rns_identity::destination::Destination::set_accepts_links(&mut self, bool)
pub fn rns_identity::destination::Destination::set_default_app_data(&mut self, rns_identity::destination::DefaultAppData)
pub fn rns_identity::destination::Destination::set_group_key(&mut self, alloc::vec::Vec<u8>)
pub fn rns_identity::destination::Destination::set_link_established_callback(&mut self, rns_identity::destination::LinkEstablishedCallback)
pub fn rns_identity::destination::Destination::set_local_ratchet(&mut self, [u8; 32])
pub fn rns_identity::destination::Destination::set_only_validate_signature(&mut self, bool)
pub fn rns_identity::destination::Destination::set_packet_callback(&mut self, rns_identity::destination::PacketCallback)
pub fn rns_identity::destination::Destination::set_proof_requested_callback(&mut self, rns_identity::destination::ProofRequestedCallback)
pub fn rns_identity::destination::Destination::set_proof_strategy(&mut self, rns_identity::destination::ProofStrategy)
pub fn rns_identity::destination::Destination::set_remote_ratchet(&mut self, [u8; 32])
pub fn rns_identity::destination::Destination::should_prove(&self, &[u8]) -> bool
pub fn rns_identity::destination::Destination::sign(&self, &[u8], &rns_identity::identity::Identity) -> core::result::Result<[u8; 64], rns_identity::destination::DestinationError>
pub fn rns_identity::destination::Destination::take_auto_identity(&mut self) -> core::option::Option<rns_identity::identity::Identity>
impl core::fmt::Display for rns_identity::destination::Destination
pub fn rns_identity::destination::Destination::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct rns_identity::destination::DestinationPacketOptions
pub rns_identity::destination::DestinationPacketOptions::context: rns_wire::context::PacketContext
pub rns_identity::destination::DestinationPacketOptions::context_flag: bool
pub rns_identity::destination::DestinationPacketOptions::header_type: rns_wire::flags::HeaderType
pub rns_identity::destination::DestinationPacketOptions::packet_type: rns_wire::flags::PacketType
pub rns_identity::destination::DestinationPacketOptions::transport_id: core::option::Option<[u8; 16]>
pub rns_identity::destination::DestinationPacketOptions::transport_type: rns_wire::flags::TransportType
impl core::default::Default for rns_identity::destination::DestinationPacketOptions
pub fn rns_identity::destination::DestinationPacketOptions::default() -> Self
pub struct rns_identity::destination::PackedDestinationPacket
pub rns_identity::destination::PackedDestinationPacket::packet: rns_wire::packet::Packet
pub rns_identity::destination::PackedDestinationPacket::ratchet_id: core::option::Option<[u8; 10]>
pub struct rns_identity::destination::RequestHandler
pub rns_identity::destination::RequestHandler::allow: rns_identity::destination::AllowPolicy
pub rns_identity::destination::RequestHandler::allowed_list: alloc::vec::Vec<[u8; 16]>
pub rns_identity::destination::RequestHandler::auto_compress: bool
pub rns_identity::destination::RequestHandler::path: alloc::string::String
pub const rns_identity::destination::GROUP_KEY_LENGTH: usize
pub const rns_identity::destination::PR_TAG_WINDOW: f64
pub type rns_identity::destination::LinkEstablishedCallback = alloc::boxed::Box<(dyn core::ops::function::Fn([u8; 16]) + core::marker::Send + core::marker::Sync)>
pub type rns_identity::destination::PacketCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&[u8], &[u8]) + core::marker::Send + core::marker::Sync)>
pub type rns_identity::destination::ProofRequestedCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&[u8]) -> bool + core::marker::Send + core::marker::Sync)>
pub mod rns_identity::identity
pub enum rns_identity::identity::IdentityError
pub rns_identity::identity::IdentityError::DecryptionFailed
pub rns_identity::identity::IdentityError::Ed25519(rns_crypto::ed25519::Ed25519Error)
pub rns_identity::identity::IdentityError::InvalidPrivateKeyLength(usize)
pub rns_identity::identity::IdentityError::InvalidPublicKeyLength(usize)
pub rns_identity::identity::IdentityError::Io(core::io::error::Error)
pub rns_identity::identity::IdentityError::VerificationFailed
pub struct rns_identity::identity::DecryptionResult
pub rns_identity::identity::DecryptionResult::plaintext: alloc::vec::Vec<u8>
pub rns_identity::identity::DecryptionResult::ratchet_id: core::option::Option<[u8; 10]>
pub struct rns_identity::identity::Identity
pub rns_identity::identity::Identity::hash: [u8; 16]
impl rns_identity::identity::Identity
pub const rns_identity::identity::Identity::CURVE: &'static str
pub const rns_identity::identity::Identity::HASH_LENGTH_BITS: usize
pub const rns_identity::identity::Identity::KEY_SIZE_BITS: usize
pub const rns_identity::identity::Identity::RATCHETSIZE: usize
pub const rns_identity::identity::Identity::RATCHET_SIZE_BITS: usize
pub fn rns_identity::identity::Identity::decrypt(&self, &[u8], core::option::Option<&[&[u8; 32]]>, bool) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::identity::IdentityError>
pub fn rns_identity::identity::Identity::decrypt_with_ratchet_id(&self, &[u8], core::option::Option<&[&[u8; 32]]>, bool) -> core::result::Result<rns_identity::identity::DecryptionResult, rns_identity::identity::IdentityError>
pub fn rns_identity::identity::Identity::encrypt(&self, &[u8], core::option::Option<&[u8; 32]>) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::identity::IdentityError>
pub fn rns_identity::identity::Identity::from_backend(&[u8], alloc::sync::Arc<dyn rns_identity::identity::LocalKeyBackend>) -> core::result::Result<Self, rns_identity::identity::IdentityError>
pub fn rns_identity::identity::Identity::from_file(&std::path::Path) -> core::result::Result<Self, rns_identity::identity::IdentityError>
pub fn rns_identity::identity::Identity::from_private_key(&[u8]) -> core::result::Result<Self, rns_identity::identity::IdentityError>
pub fn rns_identity::identity::Identity::from_public_key(&[u8]) -> core::result::Result<Self, rns_identity::identity::IdentityError>
pub fn rns_identity::identity::Identity::get_private_key(&self) -> core::option::Option<zeroize::Zeroizing<[u8; 64]>>
pub fn rns_identity::identity::Identity::get_public_key(&self) -> [u8; 64]
pub fn rns_identity::identity::Identity::get_signing_key(&self) -> core::option::Option<rns_crypto::ed25519::Ed25519PrivateKey>
pub fn rns_identity::identity::Identity::has_backend(&self) -> bool
pub fn rns_identity::identity::Identity::has_private_key(&self) -> bool
pub fn rns_identity::identity::Identity::hexhash(&self) -> alloc::string::String
pub fn rns_identity::identity::Identity::lock(&self)
pub fn rns_identity::identity::Identity::new() -> Self
pub fn rns_identity::identity::Identity::prove(&self, &[u8], bool) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::identity::IdentityError>
pub fn rns_identity::identity::Identity::pub_to_file(&self, &std::path::Path) -> core::result::Result<(), rns_identity::identity::IdentityError>
pub fn rns_identity::identity::Identity::ratchet_id(&[u8; 32]) -> [u8; 10]
pub fn rns_identity::identity::Identity::sign(&self, &[u8]) -> core::option::Option<[u8; 64]>
pub fn rns_identity::identity::Identity::to_file(&self, &std::path::Path) -> core::result::Result<(), rns_identity::identity::IdentityError>
pub fn rns_identity::identity::Identity::verify(&self, &[u8], &[u8; 64]) -> bool
impl core::clone::Clone for rns_identity::identity::Identity
pub fn rns_identity::identity::Identity::clone(&self) -> Self
impl core::default::Default for rns_identity::identity::Identity
pub fn rns_identity::identity::Identity::default() -> Self
impl core::fmt::Display for rns_identity::identity::Identity
pub fn rns_identity::identity::Identity::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub const rns_identity::identity::CURVE: &str
pub const rns_identity::identity::DERIVED_KEY_LENGTH: usize
pub const rns_identity::identity::HASH_LENGTH_BITS: usize
pub const rns_identity::identity::IDENTITY_OVERHEAD: usize
pub const rns_identity::identity::KEY_SIZE_BITS: usize
pub const rns_identity::identity::RATCHETSIZE: usize
pub const rns_identity::identity::RATCHET_ID_LENGTH: usize
pub const rns_identity::identity::RATCHET_SIZE_BITS: usize
pub trait rns_identity::identity::LocalKeyBackend: core::marker::Send + core::marker::Sync
pub fn rns_identity::identity::LocalKeyBackend::ecdh(&self, &[u8; 32]) -> core::option::Option<[u8; 32]>
pub fn rns_identity::identity::LocalKeyBackend::lock(&self)
pub fn rns_identity::identity::LocalKeyBackend::sign_ed25519(&self, &[u8]) -> core::option::Option<[u8; 64]>
pub mod rns_identity::ifac
pub enum rns_identity::ifac::IfacError
pub rns_identity::ifac::IfacError::HkdfFailed(rns_crypto::hkdf::HkdfError)
pub rns_identity::ifac::IfacError::InvalidSalt
pub struct rns_identity::ifac::IfacKey(_)
impl rns_identity::ifac::IfacKey
pub fn rns_identity::ifac::IfacKey::derive(core::option::Option<&str>, core::option::Option<&str>) -> core::result::Result<Self, rns_identity::ifac::IfacError>
impl core::cmp::Eq for rns_identity::ifac::IfacKey
impl core::cmp::PartialEq for rns_identity::ifac::IfacKey
pub fn rns_identity::ifac::IfacKey::eq(&self, &Self) -> bool
impl core::convert::From<[u8; 64]> for rns_identity::ifac::IfacKey
pub fn rns_identity::ifac::IfacKey::from([u8; 64]) -> Self
impl core::fmt::Debug for rns_identity::ifac::IfacKey
pub fn rns_identity::ifac::IfacKey::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl core::ops::deref::Deref for rns_identity::ifac::IfacKey
pub type rns_identity::ifac::IfacKey::Target = [u8; 64]
pub fn rns_identity::ifac::IfacKey::deref(&self) -> &[u8; 64]
pub const rns_identity::ifac::IFAC_SALT: &str
pub fn rns_identity::ifac::derive_ifac_identity(core::option::Option<&str>, core::option::Option<&str>) -> core::result::Result<(rns_identity::identity::Identity, [u8; 64], [u8; 64]), rns_identity::ifac::IfacError>
pub fn rns_identity::ifac::derive_ifac_key(core::option::Option<&str>, core::option::Option<&str>) -> core::result::Result<[u8; 64], rns_identity::ifac::IfacError>
pub fn rns_identity::ifac::ifac_signature(&[u8; 64]) -> core::option::Option<[u8; 64]>
pub fn rns_identity::ifac::split_ifac_key(&[u8; 64]) -> (&[u8], &[u8])
pub mod rns_identity::known_destinations
pub struct rns_identity::known_destinations::KnownDestination
pub rns_identity::known_destinations::KnownDestination::app_data: core::option::Option<alloc::vec::Vec<u8>>
pub rns_identity::known_destinations::KnownDestination::packet_hash: [u8; 32]
pub rns_identity::known_destinations::KnownDestination::public_key: [u8; 64]
pub rns_identity::known_destinations::KnownDestination::retained: bool
pub rns_identity::known_destinations::KnownDestination::timestamp: f64
pub struct rns_identity::known_destinations::KnownDestinations
impl rns_identity::known_destinations::KnownDestinations
pub fn rns_identity::known_destinations::KnownDestinations::cleanup(&mut self, f64, f64, impl core::ops::function::Fn(&[u8; 16]) -> bool) -> alloc::vec::Vec<[u8; 16]>
pub fn rns_identity::known_destinations::KnownDestinations::contains(&self, &[u8; 16]) -> bool
pub fn rns_identity::known_destinations::KnownDestinations::get(&self, &[u8; 16]) -> core::option::Option<&rns_identity::known_destinations::KnownDestination>
pub fn rns_identity::known_destinations::KnownDestinations::is_empty(&self) -> bool
pub fn rns_identity::known_destinations::KnownDestinations::is_known_or_registered(&self, &[u8; 16], &std::collections::hash::set::HashSet<[u8; 16]>) -> bool
pub fn rns_identity::known_destinations::KnownDestinations::iter(&self) -> impl core::iter::traits::iterator::Iterator<Item = (&[u8; 16], &rns_identity::known_destinations::KnownDestination)>
pub fn rns_identity::known_destinations::KnownDestinations::len(&self) -> usize
pub fn rns_identity::known_destinations::KnownDestinations::load(&std::path::Path) -> core::io::error::Result<Self>
pub fn rns_identity::known_destinations::KnownDestinations::merge(&mut self, &rns_identity::known_destinations::KnownDestinations)
pub fn rns_identity::known_destinations::KnownDestinations::new() -> Self
pub fn rns_identity::known_destinations::KnownDestinations::recall_app_data(&self, &[u8; 16]) -> core::option::Option<alloc::vec::Vec<u8>>
pub fn rns_identity::known_destinations::KnownDestinations::recall_by_identity(&self, &[u8; 16]) -> core::option::Option<(&[u8; 16], &rns_identity::known_destinations::KnownDestination)>
pub fn rns_identity::known_destinations::KnownDestinations::remember(&mut self, [u8; 16], f64, [u8; 32], [u8; 64], core::option::Option<alloc::vec::Vec<u8>>)
pub fn rns_identity::known_destinations::KnownDestinations::remove(&mut self, &[u8; 16]) -> core::option::Option<rns_identity::known_destinations::KnownDestination>
pub fn rns_identity::known_destinations::KnownDestinations::retain(&mut self, &[u8; 16])
pub fn rns_identity::known_destinations::KnownDestinations::retain_identity(&mut self, &[u8; 16]) -> usize
pub fn rns_identity::known_destinations::KnownDestinations::save(&self, &std::path::Path) -> core::io::error::Result<()>
pub fn rns_identity::known_destinations::KnownDestinations::unretain(&mut self, &[u8; 16])
impl core::default::Default for rns_identity::known_destinations::KnownDestinations
pub fn rns_identity::known_destinations::KnownDestinations::default() -> Self
pub mod rns_identity::name_hash
pub fn rns_identity::name_hash::name_hash(&str) -> [u8; 10]
pub mod rns_identity::persistence
pub enum rns_identity::persistence::DurableCleanupOutcome
pub rns_identity::persistence::DurableCleanupOutcome::AlreadyAbsent
pub rns_identity::persistence::DurableCleanupOutcome::Removed
pub enum rns_identity::persistence::DurableCommitPhase
pub rns_identity::persistence::DurableCommitPhase::CommitUncertain
pub rns_identity::persistence::DurableCommitPhase::NotCommitted
pub enum rns_identity::persistence::DurableErrorKind
pub rns_identity::persistence::DurableErrorKind::DurabilityUnsupported
pub rns_identity::persistence::DurableErrorKind::InvalidInput
pub rns_identity::persistence::DurableErrorKind::Io
pub rns_identity::persistence::DurableErrorKind::Verification
#[non_exhaustive] pub enum rns_identity::persistence::StorageRisk
pub rns_identity::persistence::StorageRisk::Remote
pub rns_identity::persistence::StorageRisk::Volatile
impl core::fmt::Display for rns_identity::persistence::StorageRisk
pub fn rns_identity::persistence::StorageRisk::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct rns_identity::persistence::DurableDirectoryReceipt
impl rns_identity::persistence::DurableDirectoryReceipt
pub fn rns_identity::persistence::DurableDirectoryReceipt::path(&self) -> &std::path::Path
pub struct rns_identity::persistence::DurableFileReceipt
impl rns_identity::persistence::DurableFileReceipt
pub fn rns_identity::persistence::DurableFileReceipt::content_hash(&self) -> [u8; 32]
pub fn rns_identity::persistence::DurableFileReceipt::is_empty(&self) -> bool
pub fn rns_identity::persistence::DurableFileReceipt::len(&self) -> usize
pub fn rns_identity::persistence::DurableFileReceipt::path(&self) -> &std::path::Path
pub struct rns_identity::persistence::DurableWriteError
pub rns_identity::persistence::DurableWriteError::kind: rns_identity::persistence::DurableErrorKind
pub rns_identity::persistence::DurableWriteError::phase: rns_identity::persistence::DurableCommitPhase
pub rns_identity::persistence::DurableWriteError::recovery_paths: alloc::vec::Vec<std::path::PathBuf>
pub fn rns_identity::persistence::atomic_write(&std::path::Path, &[u8]) -> core::io::error::Result<()>
pub fn rns_identity::persistence::durable_create_dir_all(&std::path::Path, &rns_identity::persistence::DurableFileReceipt) -> core::result::Result<rns_identity::persistence::DurableDirectoryReceipt, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::durable_reconcile(&std::path::Path, &[u8]) -> core::result::Result<rns_identity::persistence::DurableFileReceipt, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::durable_reconcile_directory(&std::path::Path, &rns_identity::persistence::DurableFileReceipt) -> core::result::Result<rns_identity::persistence::DurableDirectoryReceipt, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::durable_reconcile_hash(&std::path::Path, [u8; 32], usize) -> core::result::Result<rns_identity::persistence::DurableFileReceipt, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::durable_remove(&std::path::Path, &rns_identity::persistence::DurableFileReceipt) -> core::result::Result<rns_identity::persistence::DurableCleanupOutcome, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::durable_rename_directory(&std::path::Path, &std::path::Path, &rns_identity::persistence::DurableFileReceipt) -> core::result::Result<rns_identity::persistence::DurableDirectoryReceipt, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::durable_write(&std::path::Path, &[u8]) -> core::result::Result<rns_identity::persistence::DurableFileReceipt, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::read_file(&std::path::Path) -> core::io::error::Result<core::option::Option<alloc::vec::Vec<u8>>>
pub fn rns_identity::persistence::read_file_bounded(&std::path::Path, usize) -> core::io::error::Result<core::option::Option<alloc::vec::Vec<u8>>>
pub fn rns_identity::persistence::read_secret_file(&std::path::Path, usize) -> core::io::error::Result<zeroize::Zeroizing<alloc::vec::Vec<u8>>>
pub fn rns_identity::persistence::storage_risk(&std::path::Path) -> core::io::error::Result<core::option::Option<rns_identity::persistence::StorageRisk>>
pub fn rns_identity::persistence::try_lock_exclusive(&std::fs::File) -> core::io::error::Result<()>
pub fn rns_identity::persistence::validate_durable_storage_directory(&std::path::Path) -> core::result::Result<(), rns_identity::persistence::DurableWriteError>
pub mod rns_identity::ratchet
pub enum rns_identity::ratchet::RatchetRingFormat
pub rns_identity::ratchet::RatchetRingFormat::Canonical
pub rns_identity::ratchet::RatchetRingFormat::LegacyRust
pub struct rns_identity::ratchet::LoadedRatchetRing
impl rns_identity::ratchet::LoadedRatchetRing
pub fn rns_identity::ratchet::LoadedRatchetRing::format(&self) -> rns_identity::ratchet::RatchetRingFormat
pub fn rns_identity::ratchet::LoadedRatchetRing::into_ring(self) -> rns_identity::ratchet::RatchetRing
pub fn rns_identity::ratchet::LoadedRatchetRing::ring(&self) -> &rns_identity::ratchet::RatchetRing
pub struct rns_identity::ratchet::PersistentRatchetRing
impl rns_identity::ratchet::PersistentRatchetRing
pub fn rns_identity::ratchet::PersistentRatchetRing::current_public_key(&self) -> core::option::Option<[u8; 32]>
pub fn rns_identity::ratchet::PersistentRatchetRing::ensure_current(&mut self, &rns_identity::identity::Identity) -> core::io::error::Result<[u8; 32]>
pub fn rns_identity::ratchet::PersistentRatchetRing::ensure_current_at(&mut self, &rns_identity::identity::Identity, f64) -> core::io::error::Result<[u8; 32]>
pub fn rns_identity::ratchet::PersistentRatchetRing::is_empty(&self) -> bool
pub fn rns_identity::ratchet::PersistentRatchetRing::len(&self) -> usize
pub fn rns_identity::ratchet::PersistentRatchetRing::open(impl core::convert::AsRef<std::path::Path>, &rns_identity::identity::Identity) -> core::io::error::Result<Self>
pub fn rns_identity::ratchet::PersistentRatchetRing::path(&self) -> &std::path::Path
pub fn rns_identity::ratchet::PersistentRatchetRing::private_keys(&self) -> &[[u8; 32]]
pub fn rns_identity::ratchet::PersistentRatchetRing::ring(&self) -> &rns_identity::ratchet::RatchetRing
pub fn rns_identity::ratchet::PersistentRatchetRing::rotate(&mut self, &rns_identity::identity::Identity) -> core::io::error::Result<[u8; 32]>
pub fn rns_identity::ratchet::PersistentRatchetRing::rotate_at(&mut self, &rns_identity::identity::Identity, f64) -> core::io::error::Result<[u8; 32]>
impl core::fmt::Debug for rns_identity::ratchet::PersistentRatchetRing
pub fn rns_identity::ratchet::PersistentRatchetRing::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct rns_identity::ratchet::PreparedRatchetRotation
impl rns_identity::ratchet::PreparedRatchetRotation
pub fn rns_identity::ratchet::PreparedRatchetRotation::public_key(&self) -> [u8; 32]
pub fn rns_identity::ratchet::PreparedRatchetRotation::ring(&self) -> &rns_identity::ratchet::RatchetRing
pub struct rns_identity::ratchet::RatchetRing
impl rns_identity::ratchet::RatchetRing
pub fn rns_identity::ratchet::RatchetRing::anchor_rotation_at(&mut self, f64) -> bool
pub fn rns_identity::ratchet::RatchetRing::commit_prepared_rotation(&mut self, rns_identity::ratchet::PreparedRatchetRotation) -> [u8; 32]
pub fn rns_identity::ratchet::RatchetRing::current_public_key(&self) -> core::option::Option<[u8; 32]>
pub fn rns_identity::ratchet::RatchetRing::is_empty(&self) -> bool
pub fn rns_identity::ratchet::RatchetRing::last_rotation(&self) -> f64
pub fn rns_identity::ratchet::RatchetRing::len(&self) -> usize
pub fn rns_identity::ratchet::RatchetRing::load(&std::path::Path) -> core::io::error::Result<(Self, [u8; 64])>
pub fn rns_identity::ratchet::RatchetRing::load_verified(&std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<rns_identity::ratchet::LoadedRatchetRing>
pub fn rns_identity::ratchet::RatchetRing::needs_rotation(&self) -> bool
pub fn rns_identity::ratchet::RatchetRing::needs_rotation_at(&self, f64) -> bool
pub fn rns_identity::ratchet::RatchetRing::new() -> Self
pub fn rns_identity::ratchet::RatchetRing::prepare_rotation_at(&self, f64) -> rns_identity::ratchet::PreparedRatchetRotation
pub fn rns_identity::ratchet::RatchetRing::private_keys(&self) -> &[[u8; 32]]
pub fn rns_identity::ratchet::RatchetRing::ratchet_interval(&self) -> u64
pub fn rns_identity::ratchet::RatchetRing::retained_ratchets(&self) -> usize
pub fn rns_identity::ratchet::RatchetRing::rotate(&mut self) -> [u8; 32]
pub fn rns_identity::ratchet::RatchetRing::rotate_at(&mut self, f64) -> [u8; 32]
pub fn rns_identity::ratchet::RatchetRing::save(&self, &std::path::Path, &[u8; 64]) -> core::io::error::Result<()>
pub fn rns_identity::ratchet::RatchetRing::save_verified(&self, &std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<()>
pub fn rns_identity::ratchet::RatchetRing::save_verified_durable(&self, &std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<()>
pub fn rns_identity::ratchet::RatchetRing::set_ratchet_interval(&mut self, u64) -> bool
pub fn rns_identity::ratchet::RatchetRing::set_retained_ratchets(&mut self, usize) -> bool
impl core::default::Default for rns_identity::ratchet::RatchetRing
pub fn rns_identity::ratchet::RatchetRing::default() -> Self
impl core::ops::drop::Drop for rns_identity::ratchet::RatchetRing
pub fn rns_identity::ratchet::RatchetRing::drop(&mut self)
impl zeroize::Zeroize for rns_identity::ratchet::RatchetRing
pub fn rns_identity::ratchet::RatchetRing::zeroize(&mut self)
pub struct rns_identity::ratchet::ReceivedRatchet
pub rns_identity::ratchet::ReceivedRatchet::ratchet_pub: [u8; 32]
pub rns_identity::ratchet::ReceivedRatchet::received_at: f64
impl rns_identity::ratchet::ReceivedRatchet
pub fn rns_identity::ratchet::ReceivedRatchet::is_expired(&self) -> bool
pub fn rns_identity::ratchet::ReceivedRatchet::is_expired_at(&self, f64) -> bool
pub fn rns_identity::ratchet::ReceivedRatchet::load(&std::path::Path) -> core::io::error::Result<Self>
pub fn rns_identity::ratchet::ReceivedRatchet::new([u8; 32]) -> Self
pub fn rns_identity::ratchet::ReceivedRatchet::new_at([u8; 32], f64) -> Self
pub fn rns_identity::ratchet::ReceivedRatchet::ratchet_id(&self) -> alloc::vec::Vec<u8>
pub fn rns_identity::ratchet::ReceivedRatchet::save(&self, &std::path::Path) -> core::io::error::Result<()>
pub fn rns_identity::ratchet::ReceivedRatchet::save_durable(&self, &std::path::Path) -> core::io::error::Result<()>
pub struct rns_identity::ratchet::ReceivedRatchetStore
impl rns_identity::ratchet::ReceivedRatchetStore
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::get(&mut self, &[u8; 16]) -> core::option::Option<[u8; 32]>
pub fn rns_identity::ratchet::ReceivedRatchetStore::get_at(&mut self, &[u8; 16], f64) -> core::option::Option<[u8; 32]>
pub fn rns_identity::ratchet::ReceivedRatchetStore::is_empty(&self) -> bool
pub fn rns_identity::ratchet::ReceivedRatchetStore::len(&self) -> usize
pub fn rns_identity::ratchet::ReceivedRatchetStore::new() -> Self
pub fn rns_identity::ratchet::ReceivedRatchetStore::remember(&mut self, [u8; 16], [u8; 32])
pub fn rns_identity::ratchet::ReceivedRatchetStore::remember_at(&mut self, [u8; 16], [u8; 32], f64)
pub fn rns_identity::ratchet::ReceivedRatchetStore::with_storage(std::path::PathBuf) -> Self
impl core::default::Default for rns_identity::ratchet::ReceivedRatchetStore
pub fn rns_identity::ratchet::ReceivedRatchetStore::default() -> Self
pub fn rns_identity::ratchet::clean_received_ratchets_dir(&std::path::Path) -> usize
pub fn rns_identity::ratchet::get_ratchet_id(&[u8; 32]) -> alloc::vec::Vec<u8>
pub fn rns_identity::ratchet::purge_expired_ratchets_in_memory<K: core::cmp::Eq + core::hash::Hash>(&mut std::collections::hash::map::HashMap<K, rns_identity::ratchet::ReceivedRatchet>) -> usize
pub fn rns_identity::ratchet::ratchet_public_bytes(&[u8; 32]) -> [u8; 32]
File diff suppressed because it is too large. Load diff
+384
View File
@@ -0,0 +1,384 @@
pub mod rns_link
pub mod rns_link::clock
pub struct rns_link::clock::ContinuousInstant(_)
impl rns_link::clock::ContinuousInstant
pub fn rns_link::clock::ContinuousInstant::checked_add(self, core::time::Duration) -> core::option::Option<Self>
pub fn rns_link::clock::ContinuousInstant::checked_duration_since(self, Self) -> core::option::Option<core::time::Duration>
pub fn rns_link::clock::ContinuousInstant::checked_sub(self, core::time::Duration) -> core::option::Option<Self>
pub fn rns_link::clock::ContinuousInstant::duration_since(self, Self) -> core::time::Duration
pub fn rns_link::clock::ContinuousInstant::elapsed(self) -> core::time::Duration
pub fn rns_link::clock::ContinuousInstant::now() -> Self
pub fn rns_link::clock::ContinuousInstant::saturating_duration_since(self, Self) -> core::time::Duration
impl core::ops::arith::Add<core::time::Duration> for rns_link::clock::ContinuousInstant
pub type rns_link::clock::ContinuousInstant::Output = rns_link::clock::ContinuousInstant
pub fn rns_link::clock::ContinuousInstant::add(self, core::time::Duration) -> Self
impl core::ops::arith::AddAssign<core::time::Duration> for rns_link::clock::ContinuousInstant
pub fn rns_link::clock::ContinuousInstant::add_assign(&mut self, core::time::Duration)
impl core::ops::arith::Sub for rns_link::clock::ContinuousInstant
pub type rns_link::clock::ContinuousInstant::Output = core::time::Duration
pub fn rns_link::clock::ContinuousInstant::sub(self, Self) -> core::time::Duration
impl core::ops::arith::Sub<core::time::Duration> for rns_link::clock::ContinuousInstant
pub type rns_link::clock::ContinuousInstant::Output = rns_link::clock::ContinuousInstant
pub fn rns_link::clock::ContinuousInstant::sub(self, core::time::Duration) -> Self
impl core::ops::arith::SubAssign<core::time::Duration> for rns_link::clock::ContinuousInstant
pub fn rns_link::clock::ContinuousInstant::sub_assign(&mut self, core::time::Duration)
pub mod rns_link::constants
pub const rns_link::constants::ACCEPT_ALL: u8
pub const rns_link::constants::ACCEPT_APP: u8
pub const rns_link::constants::ACCEPT_NONE: u8
pub const rns_link::constants::AES128_DERIVED_KEY_LENGTH: usize
pub const rns_link::constants::AES256_DERIVED_KEY_LENGTH: usize
pub const rns_link::constants::DEFAULT_MODE: u8
pub const rns_link::constants::DESTINATION_CLOSED: u8
pub const rns_link::constants::ECPUBSIZE: usize
pub const rns_link::constants::ENABLED_MODES: &[u8]
pub const rns_link::constants::ESTABLISHMENT_TIMEOUT_PER_HOP: f64
pub const rns_link::constants::INITIATOR_CLOSED: u8
pub const rns_link::constants::KEEPALIVE_DEFAULT: f64
pub const rns_link::constants::KEEPALIVE_MAX: f64
pub const rns_link::constants::KEEPALIVE_MAX_RTT: f64
pub const rns_link::constants::KEEPALIVE_MIN: f64
pub const rns_link::constants::KEEPALIVE_REQUEST: u8
pub const rns_link::constants::KEEPALIVE_RESPONSE: u8
pub const rns_link::constants::KEEPALIVE_TIMEOUT_FACTOR: f64
pub const rns_link::constants::KEYSIZE: usize
pub const rns_link::constants::LINK_MTU_SIZE: usize
pub const rns_link::constants::MODE_AES128_CBC: u8
pub const rns_link::constants::MODE_AES256_CBC: u8
pub const rns_link::constants::MODE_AES256_GCM: u8
pub const rns_link::constants::MODE_BYTEMASK: u32
pub const rns_link::constants::MODE_OTP_RESERVED: u8
pub const rns_link::constants::MODE_PQ_RESERVED_1: u8
pub const rns_link::constants::MODE_PQ_RESERVED_2: u8
pub const rns_link::constants::MODE_PQ_RESERVED_3: u8
pub const rns_link::constants::MODE_PQ_RESERVED_4: u8
pub const rns_link::constants::MTU_BYTEMASK: u32
pub const rns_link::constants::RESPONSE_MAX_GRACE_TIME: f64
pub const rns_link::constants::STALE_FACTOR: f64
pub const rns_link::constants::STALE_GRACE: f64
pub const rns_link::constants::STALE_TIME_DEFAULT: f64
pub const rns_link::constants::TIMEOUT: u8
pub const rns_link::constants::TRAFFIC_TIMEOUT_FACTOR: f64
pub const rns_link::constants::TRAFFIC_TIMEOUT_FLOOR_MS: u64
pub const rns_link::constants::WATCHDOG_MAX_SLEEP: f64
pub mod rns_link::encryption
pub enum rns_link::encryption::LinkCryptoError
pub rns_link::encryption::LinkCryptoError::DecryptionFailed
pub rns_link::encryption::LinkCryptoError::EncryptionFailed
pub fn rns_link::encryption::link_decrypt(&rns_link::key_derivation::LinkKeys, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
pub fn rns_link::encryption::link_encrypt(&rns_link::key_derivation::LinkKeys, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
pub mod rns_link::handshake
pub enum rns_link::handshake::HandshakeError
pub rns_link::handshake::HandshakeError::InvalidLength(usize)
pub rns_link::handshake::HandshakeError::InvalidSignature
pub rns_link::handshake::HandshakeError::KeyDerivation(rns_link::key_derivation::LinkKeyError)
pub rns_link::handshake::HandshakeError::Signalling(rns_wire::link_signalling::LinkSignallingError)
pub rns_link::handshake::HandshakeError::TooShort
pub rns_link::handshake::HandshakeError::UnsupportedMode(u8)
pub struct rns_link::handshake::EphemeralKeys
pub rns_link::handshake::EphemeralKeys::ed25519_prv: rns_crypto::ed25519::Ed25519PrivateKey
pub rns_link::handshake::EphemeralKeys::ed25519_pub: rns_crypto::ed25519::Ed25519PublicKey
pub rns_link::handshake::EphemeralKeys::x25519_prv: rns_crypto::x25519::X25519PrivateKey
pub rns_link::handshake::EphemeralKeys::x25519_pub: rns_crypto::x25519::X25519PublicKey
impl rns_link::handshake::EphemeralKeys
pub fn rns_link::handshake::EphemeralKeys::generate() -> Self
impl core::ops::drop::Drop for rns_link::handshake::EphemeralKeys
pub fn rns_link::handshake::EphemeralKeys::drop(&mut self)
impl zeroize::Zeroize for rns_link::handshake::EphemeralKeys
pub fn rns_link::handshake::EphemeralKeys::zeroize(&mut self)
pub struct rns_link::handshake::LinkProofData
pub rns_link::handshake::LinkProofData::responder_x25519_pub: [u8; 32]
pub rns_link::handshake::LinkProofData::signalling: rns_wire::link_signalling::SignallingData
pub rns_link::handshake::LinkProofData::signature: [u8; 64]
impl rns_link::handshake::LinkProofData
pub fn rns_link::handshake::LinkProofData::create(&rns_crypto::ed25519::Ed25519PrivateKey, &[u8; 32], &[u8; 32], &[u8; 16], rns_wire::link_signalling::SignallingData) -> Self
pub fn rns_link::handshake::LinkProofData::create_with<F>(F, &[u8; 32], &[u8; 32], &[u8; 16], rns_wire::link_signalling::SignallingData) -> Self where F: core::ops::function::FnOnce(&[u8]) -> [u8; 64]
pub fn rns_link::handshake::LinkProofData::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_link::handshake::LinkProofData::unpack(&[u8]) -> core::result::Result<Self, rns_link::handshake::HandshakeError>
pub fn rns_link::handshake::LinkProofData::validate(&self, &rns_crypto::ed25519::Ed25519PublicKey, &[u8; 16], &[u8; 32]) -> bool
pub struct rns_link::handshake::LinkRequestData
pub rns_link::handshake::LinkRequestData::peer_ed25519_pub: [u8; 32]
pub rns_link::handshake::LinkRequestData::peer_x25519_pub: [u8; 32]
pub rns_link::handshake::LinkRequestData::signalling: rns_wire::link_signalling::SignallingData
impl rns_link::handshake::LinkRequestData
pub fn rns_link::handshake::LinkRequestData::pack(&rns_link::handshake::EphemeralKeys, rns_wire::link_signalling::SignallingData) -> alloc::vec::Vec<u8>
pub fn rns_link::handshake::LinkRequestData::unpack(&[u8]) -> core::result::Result<Self, rns_link::handshake::HandshakeError>
pub fn rns_link::handshake::compute_link_id(&[u8; 16], &[u8]) -> [u8; 16]
pub fn rns_link::handshake::compute_link_id_from_raw(&[u8], rns_wire::flags::HeaderType) -> [u8; 16]
pub fn rns_link::handshake::perform_handshake(&rns_crypto::x25519::X25519PrivateKey, &[u8; 32], &[u8; 16], u8) -> core::result::Result<rns_link::key_derivation::LinkKeys, rns_link::key_derivation::LinkKeyError>
pub mod rns_link::keepalive
pub struct rns_link::keepalive::KeepaliveState
pub rns_link::keepalive::KeepaliveState::activated_at: core::option::Option<std::time::Instant>
pub rns_link::keepalive::KeepaliveState::is_initiator: bool
pub rns_link::keepalive::KeepaliveState::keepalive_interval: core::time::Duration
pub rns_link::keepalive::KeepaliveState::last_data: std::time::Instant
pub rns_link::keepalive::KeepaliveState::last_inbound: std::time::Instant
pub rns_link::keepalive::KeepaliveState::last_keepalive_sent: core::option::Option<std::time::Instant>
pub rns_link::keepalive::KeepaliveState::last_outbound: core::option::Option<std::time::Instant>
pub rns_link::keepalive::KeepaliveState::last_proof: core::option::Option<std::time::Instant>
pub rns_link::keepalive::KeepaliveState::stale_time: core::time::Duration
impl rns_link::keepalive::KeepaliveState
pub fn rns_link::keepalive::KeepaliveState::is_stale(&self) -> bool
pub fn rns_link::keepalive::KeepaliveState::mark_activated(&mut self)
pub fn rns_link::keepalive::KeepaliveState::mark_keepalive_sent(&mut self)
pub fn rns_link::keepalive::KeepaliveState::new(bool) -> Self
pub fn rns_link::keepalive::KeepaliveState::record_data(&mut self)
pub fn rns_link::keepalive::KeepaliveState::record_inbound(&mut self)
pub fn rns_link::keepalive::KeepaliveState::record_outbound(&mut self)
pub fn rns_link::keepalive::KeepaliveState::record_proof(&mut self)
pub fn rns_link::keepalive::KeepaliveState::should_send_keepalive(&self) -> bool
pub fn rns_link::keepalive::KeepaliveState::since_inbound(&self) -> core::time::Duration
pub fn rns_link::keepalive::KeepaliveState::stale_grace_timeout(&self, core::time::Duration) -> core::time::Duration
pub fn rns_link::keepalive::KeepaliveState::update_from_rtt(&mut self, core::time::Duration)
pub mod rns_link::key_derivation
pub enum rns_link::key_derivation::LinkKeyError
pub rns_link::key_derivation::LinkKeyError::HkdfFailed
pub rns_link::key_derivation::LinkKeyError::UnsupportedMode(u8)
pub struct rns_link::key_derivation::LinkKeys
pub rns_link::key_derivation::LinkKeys::encryption_key: alloc::vec::Vec<u8>
pub rns_link::key_derivation::LinkKeys::signing_key: alloc::vec::Vec<u8>
impl rns_link::key_derivation::LinkKeys
pub fn rns_link::key_derivation::LinkKeys::derive(&rns_crypto::x25519::X25519PrivateKey, &rns_crypto::x25519::X25519PublicKey, &[u8; 16], u8) -> core::result::Result<Self, rns_link::key_derivation::LinkKeyError>
impl core::ops::drop::Drop for rns_link::key_derivation::LinkKeys
pub fn rns_link::key_derivation::LinkKeys::drop(&mut self)
pub mod rns_link::link
pub enum rns_link::link::CloseReason
pub rns_link::link::CloseReason::DestinationClosed
pub rns_link::link::CloseReason::InitiatorClosed
pub rns_link::link::CloseReason::Timeout
pub enum rns_link::link::LinkAction
pub rns_link::link::LinkAction::Closed(rns_link::link::CloseReason)
pub rns_link::link::LinkAction::None
pub rns_link::link::LinkAction::SendKeepalive
pub rns_link::link::LinkAction::SendTeardownAndClose(alloc::vec::Vec<u8>)
pub rns_link::link::LinkAction::TransitionedToStale
pub enum rns_link::link::LinkRole
pub rns_link::link::LinkRole::Initiator
pub rns_link::link::LinkRole::Responder
pub enum rns_link::link::LinkState
pub rns_link::link::LinkState::Active = 2
pub rns_link::link::LinkState::Closed = 4
pub rns_link::link::LinkState::Handshake = 1
pub rns_link::link::LinkState::Pending = 0
pub rns_link::link::LinkState::Stale = 3
pub enum rns_link::link::OutboundResourceState
pub rns_link::link::OutboundResourceState::AwaitingProof
pub rns_link::link::OutboundResourceState::Complete
pub rns_link::link::OutboundResourceState::Failed
pub rns_link::link::OutboundResourceState::Transferring
pub enum rns_link::link::PacketProofError
pub rns_link::link::PacketProofError::HashMismatch
pub rns_link::link::PacketProofError::InvalidSignature
pub rns_link::link::PacketProofError::InvalidState(rns_link::link::LinkState)
pub rns_link::link::PacketProofError::MalformedProof
pub rns_link::link::PacketProofError::PeerKeyUnavailable
pub rns_link::link::PacketProofError::SignerUnavailable
pub rns_link::link::PacketProofError::WrongRole
pub enum rns_link::link::RequestSendMode
pub rns_link::link::RequestSendMode::Packet(alloc::vec::Vec<u8>)
pub rns_link::link::RequestSendMode::Resource(alloc::vec::Vec<u8>)
pub enum rns_link::link::ResourceAcceptance
pub rns_link::link::ResourceAcceptance::Accept
pub rns_link::link::ResourceAcceptance::AskApp
pub rns_link::link::ResourceAcceptance::Reject
pub enum rns_link::link::ResourceStrategy
pub rns_link::link::ResourceStrategy::AcceptAll
pub rns_link::link::ResourceStrategy::AcceptApp
pub rns_link::link::ResourceStrategy::AcceptNone
pub struct rns_link::link::Link
pub rns_link::link::Link::activated_at: core::option::Option<std::time::Instant>
pub rns_link::link::Link::destination_hash: [u8; 16]
pub rns_link::link::Link::establishment_cost: usize
pub rns_link::link::Link::establishment_rate: core::option::Option<f64>
pub rns_link::link::Link::establishment_timeout: core::time::Duration
pub rns_link::link::Link::expected_hops: core::option::Option<u8>
pub rns_link::link::Link::expected_rate: core::option::Option<f64>
pub rns_link::link::Link::has_channel: bool
pub rns_link::link::Link::identified: bool
pub rns_link::link::Link::incoming_resource_count: usize
pub rns_link::link::Link::incoming_resources: alloc::vec::Vec<[u8; 32]>
pub rns_link::link::Link::is_initiator: bool
pub rns_link::link::Link::keepalive: rns_link::keepalive::KeepaliveState
pub rns_link::link::Link::link_closed_callback: core::option::Option<rns_link::link::LinkCallback>
pub rns_link::link::Link::link_established_callback: core::option::Option<rns_link::link::LinkCallback>
pub rns_link::link::Link::link_id: [u8; 16]
pub rns_link::link::Link::mdu: usize
pub rns_link::link::Link::mode: u8
pub rns_link::link::Link::mtu: u32
pub rns_link::link::Link::outgoing_resource_states: alloc::vec::Vec<rns_link::link::OutboundResourceState>
pub rns_link::link::Link::outgoing_resources: alloc::vec::Vec<[u8; 32]>
pub rns_link::link::Link::packet_callback: core::option::Option<rns_link::link::PacketCallback>
pub rns_link::link::Link::pending_requests: alloc::vec::Vec<rns_link::request::RequestReceipt>
pub rns_link::link::Link::q: core::option::Option<f64>
pub rns_link::link::Link::remote_identified_callback: core::option::Option<rns_link::link::RemoteIdentifiedCallback>
pub rns_link::link::Link::request_time: std::time::Instant
pub rns_link::link::Link::resource_callback: core::option::Option<rns_link::link::ResourceCallback>
pub rns_link::link::Link::resource_strategy: rns_link::link::ResourceStrategy
pub rns_link::link::Link::rssi: core::option::Option<f64>
pub rns_link::link::Link::rtt: core::option::Option<core::time::Duration>
pub rns_link::link::Link::rx_bytes: u64
pub rns_link::link::Link::rx_count: u64
pub rns_link::link::Link::snr: core::option::Option<f64>
pub rns_link::link::Link::stale_since: core::option::Option<std::time::Instant>
pub rns_link::link::Link::state: rns_link::link::LinkState
pub rns_link::link::Link::teardown_reason: core::option::Option<rns_link::link::CloseReason>
pub rns_link::link::Link::tx_bytes: u64
pub rns_link::link::Link::tx_count: u64
impl rns_link::link::Link
pub fn rns_link::link::Link::add_establishment_cost(&mut self, usize)
pub fn rns_link::link::Link::age(&self) -> core::option::Option<core::time::Duration>
pub fn rns_link::link::Link::classify_request(&self, alloc::vec::Vec<u8>) -> rns_link::link::RequestSendMode
pub fn rns_link::link::Link::create_response(&self, &[u8; 16], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
pub fn rns_link::link::Link::create_rtt_packet(&self) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
pub fn rns_link::link::Link::decrypt(&self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
pub fn rns_link::link::Link::default_request_timeout(&self) -> core::time::Duration
pub fn rns_link::link::Link::deliver_response_data(&mut self, &[u8; 16], alloc::vec::Vec<u8>) -> bool
pub fn rns_link::link::Link::encrypt(&self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
pub fn rns_link::link::Link::extend_establishment_timeout(&mut self, f64)
pub fn rns_link::link::Link::fail_pending_request(&mut self, &[u8; 16]) -> bool
pub fn rns_link::link::Link::get_age(&self) -> core::option::Option<f64>
pub fn rns_link::link::Link::get_establishment_rate(&self) -> core::option::Option<f64>
pub fn rns_link::link::Link::get_expected_rate(&self) -> core::option::Option<f64>
pub fn rns_link::link::Link::get_mdu(&self) -> core::option::Option<usize>
pub const fn rns_link::link::Link::get_mode(&self) -> u8
pub fn rns_link::link::Link::get_mtu(&self) -> core::option::Option<u32>
pub fn rns_link::link::Link::get_q(&self) -> core::option::Option<f64>
pub fn rns_link::link::Link::get_rssi(&self) -> core::option::Option<f64>
pub fn rns_link::link::Link::get_snr(&self) -> core::option::Option<f64>
pub fn rns_link::link::Link::handle_identification(&mut self, &[u8]) -> core::result::Result<[u8; 64], rns_link::encryption::LinkCryptoError>
pub fn rns_link::link::Link::handle_request(&self, &[u8]) -> core::result::Result<rns_link::link::ParsedRequestData, rns_link::encryption::LinkCryptoError>
pub fn rns_link::link::Link::handle_response(&mut self, &[u8]) -> core::result::Result<([u8; 16], alloc::vec::Vec<u8>), rns_link::encryption::LinkCryptoError>
pub fn rns_link::link::Link::handle_response_plaintext(&mut self, &[u8]) -> core::result::Result<([u8; 16], alloc::vec::Vec<u8>), rns_link::encryption::LinkCryptoError>
pub fn rns_link::link::Link::has_keys(&self) -> bool
pub fn rns_link::link::Link::identify(&self, &[u8; 64], &rns_crypto::ed25519::Ed25519PrivateKey) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
pub fn rns_link::link::Link::identify_with<F>(&self, &[u8; 64], F) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError> where F: core::ops::function::FnOnce(&[u8]) -> [u8; 64]
pub fn rns_link::link::Link::identify_with_fallible<F>(&self, &[u8; 64], F) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError> where F: core::ops::function::FnOnce(&[u8]) -> core::option::Option<[u8; 64]>
pub fn rns_link::link::Link::inactive_for(&self) -> core::time::Duration
pub fn rns_link::link::Link::is_active(&self) -> bool
pub fn rns_link::link::Link::mark_channel_created(&mut self)
pub fn rns_link::link::Link::mark_closed(&mut self, rns_link::link::CloseReason)
pub fn rns_link::link::Link::mark_request_resource_sending(&mut self, &[u8; 16]) -> bool
pub fn rns_link::link::Link::mark_request_resource_sent(&mut self, &[u8; 16]) -> bool
pub fn rns_link::link::Link::new_initiator([u8; 16], u8) -> (Self, alloc::vec::Vec<u8>)
pub fn rns_link::link::Link::new_responder(&[u8], &rns_crypto::ed25519::Ed25519PrivateKey, [u8; 16], u8) -> core::result::Result<(Self, alloc::vec::Vec<u8>), rns_link::handshake::HandshakeError>
pub fn rns_link::link::Link::new_responder_with<F>(&[u8], &[u8; 32], [u8; 16], u8, F) -> core::result::Result<(Self, alloc::vec::Vec<u8>), rns_link::handshake::HandshakeError> where F: core::ops::function::FnOnce(&[u8]) -> core::option::Option<[u8; 64]>
pub fn rns_link::link::Link::no_data_for(&self) -> core::time::Duration
pub fn rns_link::link::Link::no_inbound_for(&self) -> core::time::Duration
pub fn rns_link::link::Link::no_outbound_for(&self) -> core::time::Duration
pub fn rns_link::link::Link::pack_response(&[u8; 16], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
pub fn rns_link::link::Link::packet_proof_timeout(&self) -> core::time::Duration
pub fn rns_link::link::Link::parse_request(&[u8]) -> core::result::Result<rns_link::link::ParsedRequestData, rns_link::encryption::LinkCryptoError>
pub fn rns_link::link::Link::parse_response_plaintext(&[u8]) -> core::result::Result<([u8; 16], alloc::vec::Vec<u8>), rns_link::encryption::LinkCryptoError>
pub fn rns_link::link::Link::phy_stats(&self) -> (core::option::Option<f64>, core::option::Option<f64>, core::option::Option<f64>)
pub fn rns_link::link::Link::phy_stats_snapshot(&self) -> rns_link::link::LinkPhyStats
pub fn rns_link::link::Link::phy_stats_tracking_enabled(&self) -> bool
pub fn rns_link::link::Link::prepare_request(&mut self, &str, core::option::Option<&[u8]>, core::time::Duration) -> core::result::Result<(alloc::vec::Vec<u8>, [u8; 16]), rns_link::encryption::LinkCryptoError>
pub fn rns_link::link::Link::prove_packet(&self, &[u8; 32], &rns_crypto::ed25519::Ed25519PrivateKey) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
pub fn rns_link::link::Link::prove_packet_with<F>(&self, &[u8; 32], F) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError> where F: core::ops::function::FnOnce(&[u8]) -> [u8; 64]
pub fn rns_link::link::Link::prove_packet_with_fallible<F>(&self, &[u8; 32], F) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError> where F: core::ops::function::FnOnce(&[u8]) -> core::option::Option<[u8; 64]>
pub fn rns_link::link::Link::prove_packet_with_link_key(&self, &[u8; 32]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
pub fn rns_link::link::Link::prove_packet_with_local_signer(&self, &[u8; 32]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::link::PacketProofError>
pub fn rns_link::link::Link::prove_responder_packet_with<F>(&self, &[u8; 32], F) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::link::PacketProofError> where F: core::ops::function::FnOnce(&[u8]) -> core::option::Option<[u8; 64]>
pub fn rns_link::link::Link::ready_for_new_resource(&self) -> bool
pub fn rns_link::link::Link::receive_rtt_packet(&mut self, &[u8]) -> core::result::Result<(), rns_link::handshake::HandshakeError>
pub fn rns_link::link::Link::receive_teardown(&mut self, &[u8]) -> bool
pub fn rns_link::link::Link::record_inbound(&mut self)
pub fn rns_link::link::Link::record_rx(&mut self, usize)
pub fn rns_link::link::Link::record_tx(&mut self, usize)
pub fn rns_link::link::Link::record_tx_keepalive(&mut self, usize)
pub fn rns_link::link::Link::register_incoming_resource(&mut self)
pub fn rns_link::link::Link::register_outgoing_resource(&mut self)
pub fn rns_link::link::Link::remote_identity(&self) -> core::option::Option<&[u8; 64]>
pub fn rns_link::link::Link::request(&mut self, &str, core::option::Option<&[u8]>, core::time::Duration) -> core::result::Result<(alloc::vec::Vec<u8>, [u8; 16]), rns_link::encryption::LinkCryptoError>
pub fn rns_link::link::Link::request_str(&mut self, &str, &str, core::time::Duration) -> core::result::Result<(alloc::vec::Vec<u8>, [u8; 16]), rns_link::encryption::LinkCryptoError>
pub fn rns_link::link::Link::resource_concluded(&mut self, usize, f64, bool)
pub fn rns_link::link::Link::role(&self) -> rns_link::link::LinkRole
pub fn rns_link::link::Link::rtt_secs(&self) -> f64
pub fn rns_link::link::Link::session_keys(&self) -> core::option::Option<rns_link::key_derivation::LinkKeys>
pub fn rns_link::link::Link::set_link_closed_callback(&mut self, impl core::ops::function::Fn(&rns_link::link::Link) + core::marker::Send + core::marker::Sync + 'static)
pub fn rns_link::link::Link::set_link_established_callback(&mut self, impl core::ops::function::Fn(&rns_link::link::Link) + core::marker::Send + core::marker::Sync + 'static)
pub fn rns_link::link::Link::set_packet_callback(&mut self, impl core::ops::function::Fn(&[u8]) + core::marker::Send + core::marker::Sync + 'static)
pub fn rns_link::link::Link::set_remote_identified_callback(&mut self, impl core::ops::function::Fn(&rns_link::link::Link, &[u8; 64]) + core::marker::Send + core::marker::Sync + 'static)
pub fn rns_link::link::Link::set_resource_callback(&mut self, impl core::ops::function::Fn(bool) -> bool + core::marker::Send + core::marker::Sync + 'static)
pub fn rns_link::link::Link::set_resource_strategy(&mut self, rns_link::link::ResourceStrategy)
pub fn rns_link::link::Link::set_signing_key(&mut self, &rns_crypto::ed25519::Ed25519PrivateKey)
pub fn rns_link::link::Link::should_accept_resource(&self) -> rns_link::link::ResourceAcceptance
pub fn rns_link::link::Link::should_respond_to_keepalive(&self) -> bool
pub fn rns_link::link::Link::sign(&self, &[u8]) -> core::option::Option<[u8; 64]>
pub fn rns_link::link::Link::teardown(&mut self, rns_link::link::CloseReason) -> core::option::Option<alloc::vec::Vec<u8>>
pub fn rns_link::link::Link::tick(&mut self) -> rns_link::link::LinkAction
pub fn rns_link::link::Link::track_incoming_resource(&mut self, [u8; 32])
pub fn rns_link::link::Link::track_outgoing_resource(&mut self, [u8; 32])
pub fn rns_link::link::Link::track_phy_stats(&mut self, bool)
pub fn rns_link::link::Link::traffic_stats(&self) -> (u64, u64, u64, u64)
pub fn rns_link::link::Link::try_extend_establishment_timeout(&mut self, f64) -> core::result::Result<(), rns_link::link::TimeoutError>
pub fn rns_link::link::Link::untrack_resource(&mut self, &[u8; 32])
pub fn rns_link::link::Link::update_outgoing_resource_state(&mut self, usize, rns_link::link::OutboundResourceState)
pub fn rns_link::link::Link::update_pending_request_id(&mut self, &[u8; 16], [u8; 16]) -> bool
pub fn rns_link::link::Link::update_phy_stats(&mut self, core::option::Option<f64>, core::option::Option<f64>, core::option::Option<f64>)
pub fn rns_link::link::Link::update_phy_stats_force(&mut self, core::option::Option<f64>, core::option::Option<f64>, core::option::Option<f64>)
pub fn rns_link::link::Link::update_rtt_from_packet(&mut self, &[u8]) -> core::result::Result<core::time::Duration, rns_link::encryption::LinkCryptoError>
pub fn rns_link::link::Link::validate(&self, &[u8], &[u8]) -> bool
pub fn rns_link::link::Link::validate_packet_proof(&self, &[u8; 32], &[u8]) -> bool
pub fn rns_link::link::Link::validate_peer_packet_proof(&self, &[u8; 32], &[u8]) -> core::result::Result<(), rns_link::link::PacketProofError>
pub fn rns_link::link::Link::validate_proof(&mut self, &[u8], &rns_crypto::ed25519::Ed25519PublicKey, &[u8; 32]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::handshake::HandshakeError>
pub struct rns_link::link::LinkPhyStats
pub rns_link::link::LinkPhyStats::q: core::option::Option<f64>
pub rns_link::link::LinkPhyStats::rssi: core::option::Option<f64>
pub rns_link::link::LinkPhyStats::snr: core::option::Option<f64>
pub struct rns_link::link::TimeoutError
pub type rns_link::link::LinkCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&rns_link::link::Link) + core::marker::Send + core::marker::Sync)>
pub type rns_link::link::PacketCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&[u8]) + core::marker::Send + core::marker::Sync)>
pub type rns_link::link::ParsedRequestData = ([u8; 16], [u8; 16], f64, alloc::vec::Vec<u8>)
pub type rns_link::link::RemoteIdentifiedCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&rns_link::link::Link, &[u8; 64]) + core::marker::Send + core::marker::Sync)>
pub type rns_link::link::ResourceCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(bool) -> bool + core::marker::Send + core::marker::Sync)>
pub mod rns_link::mtu_discovery
pub use rns_link::mtu_discovery::LinkMtu
pub use rns_link::mtu_discovery::LinkSignalling
pub use rns_link::mtu_discovery::LinkSignallingError
pub use rns_link::mtu_discovery::SignallingData
pub use rns_link::mtu_discovery::parse_proof_signalling
pub use rns_link::mtu_discovery::parse_request_signalling
pub mod rns_link::request
pub enum rns_link::request::RequestState
pub rns_link::request::RequestState::Delivered
pub rns_link::request::RequestState::Failed
pub rns_link::request::RequestState::Receiving
pub rns_link::request::RequestState::ResponseReceived
pub rns_link::request::RequestState::SendingResource
pub rns_link::request::RequestState::Sent
pub struct rns_link::request::RequestCallbacks
pub rns_link::request::RequestCallbacks::failed: core::option::Option<rns_link::request::RequestCallback>
pub rns_link::request::RequestCallbacks::progress: core::option::Option<rns_link::request::ProgressCallback>
pub rns_link::request::RequestCallbacks::response: core::option::Option<rns_link::request::RequestCallback>
pub struct rns_link::request::RequestReceipt
pub rns_link::request::RequestReceipt::callbacks: rns_link::request::RequestCallbacks
pub rns_link::request::RequestReceipt::link_id: [u8; 16]
pub rns_link::request::RequestReceipt::progress: f32
pub rns_link::request::RequestReceipt::request_id: [u8; 32]
pub rns_link::request::RequestReceipt::response: core::option::Option<alloc::vec::Vec<u8>>
pub rns_link::request::RequestReceipt::rtt: core::option::Option<core::time::Duration>
pub rns_link::request::RequestReceipt::sent_at: std::time::Instant
pub rns_link::request::RequestReceipt::state: rns_link::request::RequestState
pub rns_link::request::RequestReceipt::timeout: core::time::Duration
impl rns_link::request::RequestReceipt
pub fn rns_link::request::RequestReceipt::check_timeout(&mut self) -> bool
pub fn rns_link::request::RequestReceipt::concluded(&self) -> bool
pub fn rns_link::request::RequestReceipt::deliver(&mut self, alloc::vec::Vec<u8>)
pub fn rns_link::request::RequestReceipt::fail(&mut self)
pub fn rns_link::request::RequestReceipt::get_progress(&self) -> f32
pub fn rns_link::request::RequestReceipt::get_response_time(&self) -> core::option::Option<core::time::Duration>
pub fn rns_link::request::RequestReceipt::is_pending(&self) -> bool
pub fn rns_link::request::RequestReceipt::is_timed_out(&self) -> bool
pub fn rns_link::request::RequestReceipt::mark_delivered(&mut self)
pub fn rns_link::request::RequestReceipt::mark_failed(&mut self)
pub fn rns_link::request::RequestReceipt::mark_resource_sending(&mut self)
pub fn rns_link::request::RequestReceipt::mark_resource_sent(&mut self)
pub fn rns_link::request::RequestReceipt::new([u8; 32], [u8; 16], core::time::Duration) -> Self
pub fn rns_link::request::RequestReceipt::receive_response(&mut self, alloc::vec::Vec<u8>)
pub fn rns_link::request::RequestReceipt::set_failed_callback(&mut self, impl core::ops::function::FnOnce(&rns_link::request::RequestReceipt) + core::marker::Send + 'static)
pub fn rns_link::request::RequestReceipt::set_progress_callback(&mut self, impl core::ops::function::Fn(f32) + core::marker::Send + core::marker::Sync + 'static)
pub fn rns_link::request::RequestReceipt::set_response_callback(&mut self, impl core::ops::function::FnOnce(&rns_link::request::RequestReceipt) + core::marker::Send + 'static)
pub fn rns_link::request::RequestReceipt::update_progress(&mut self, f32)
pub type rns_link::request::ProgressCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(f32) + core::marker::Send + core::marker::Sync)>
pub type rns_link::request::RequestCallback = alloc::boxed::Box<(dyn core::ops::function::FnOnce(&rns_link::request::RequestReceipt) + core::marker::Send)>
+638
View File
@@ -0,0 +1,638 @@
pub mod rns_protocol
pub mod rns_protocol::buffer
pub enum rns_protocol::buffer::BufferError
pub rns_protocol::buffer::BufferError::WriterClosed
pub struct rns_protocol::buffer::ChannelBuffer
impl rns_protocol::buffer::ChannelBuffer
pub fn rns_protocol::buffer::ChannelBuffer::available(&self) -> usize
pub fn rns_protocol::buffer::ChannelBuffer::close_writer(&mut self) -> rns_protocol::stream_data::StreamDataMessage
pub fn rns_protocol::buffer::ChannelBuffer::drain_and_close_writer(&mut self) -> rns_protocol::buffer::DrainClose
pub fn rns_protocol::buffer::ChannelBuffer::feed_reader(&mut self, &rns_protocol::stream_data::StreamDataMessage) -> bool
pub fn rns_protocol::buffer::ChannelBuffer::is_done(&self) -> bool
pub fn rns_protocol::buffer::ChannelBuffer::is_writer_closed(&self) -> bool
pub fn rns_protocol::buffer::ChannelBuffer::new(u16, usize) -> Self
pub fn rns_protocol::buffer::ChannelBuffer::read(&mut self, usize) -> core::option::Option<alloc::vec::Vec<u8>>
pub fn rns_protocol::buffer::ChannelBuffer::read_all(&mut self) -> core::option::Option<alloc::vec::Vec<u8>>
pub fn rns_protocol::buffer::ChannelBuffer::stream_id(&self) -> u16
pub fn rns_protocol::buffer::ChannelBuffer::write(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<rns_protocol::stream_data::StreamDataMessage>, rns_protocol::buffer::BufferError>
pub struct rns_protocol::buffer::DrainClose
pub rns_protocol::buffer::DrainClose::eof_message: rns_protocol::stream_data::StreamDataMessage
pub struct rns_protocol::buffer::StreamReader
impl rns_protocol::buffer::StreamReader
pub fn rns_protocol::buffer::StreamReader::available(&self) -> usize
pub fn rns_protocol::buffer::StreamReader::feed(&mut self, &rns_protocol::stream_data::StreamDataMessage) -> bool
pub fn rns_protocol::buffer::StreamReader::is_done(&self) -> bool
pub fn rns_protocol::buffer::StreamReader::is_eof(&self) -> bool
pub fn rns_protocol::buffer::StreamReader::new(u16) -> Self
pub fn rns_protocol::buffer::StreamReader::read(&mut self, usize) -> core::option::Option<alloc::vec::Vec<u8>>
pub fn rns_protocol::buffer::StreamReader::read_all(&mut self) -> core::option::Option<alloc::vec::Vec<u8>>
pub struct rns_protocol::buffer::StreamWriter
impl rns_protocol::buffer::StreamWriter
pub fn rns_protocol::buffer::StreamWriter::close(&mut self) -> rns_protocol::buffer::DrainClose
pub fn rns_protocol::buffer::StreamWriter::close_simple(&mut self) -> rns_protocol::stream_data::StreamDataMessage
pub fn rns_protocol::buffer::StreamWriter::is_closed(&self) -> bool
pub fn rns_protocol::buffer::StreamWriter::new(u16, usize) -> Self
pub fn rns_protocol::buffer::StreamWriter::write(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<rns_protocol::stream_data::StreamDataMessage>, rns_protocol::buffer::BufferError>
pub const rns_protocol::buffer::COMPRESSION_TRIES: usize
pub const rns_protocol::buffer::MAX_CHUNK_LEN: usize
pub mod rns_protocol::channel
pub enum rns_protocol::channel::ChannelError
pub rns_protocol::channel::ChannelError::ChannelClosed
pub rns_protocol::channel::ChannelError::InvalidEnvelope
pub rns_protocol::channel::ChannelError::InvalidMessageType(u16)
pub rns_protocol::channel::ChannelError::MaxRetriesExceeded
pub rns_protocol::channel::ChannelError::MessageTooLarge
pub rns_protocol::channel::ChannelError::MessageTooLarge::actual: usize
pub rns_protocol::channel::ChannelError::MessageTooLarge::max: usize
pub rns_protocol::channel::ChannelError::NotReady
pub rns_protocol::channel::ChannelError::UnknownMessageType(u16)
pub struct rns_protocol::channel::Channel
pub rns_protocol::channel::Channel::active: bool
pub rns_protocol::channel::Channel::window: rns_protocol::channel::ChannelWindow
impl rns_protocol::channel::Channel
pub fn rns_protocol::channel::Channel::add_message_handler(&mut self, rns_protocol::channel::MessageCallback) -> rns_protocol::channel::HandlerId
pub fn rns_protocol::channel::Channel::channel_mdu(usize) -> usize
pub fn rns_protocol::channel::Channel::clear_message_handlers(&mut self)
pub fn rns_protocol::channel::Channel::compute_timeout(&self, usize) -> f64
pub fn rns_protocol::channel::Channel::delivered(&mut self, u16, f64)
pub fn rns_protocol::channel::Channel::is_drained(&self) -> bool
pub fn rns_protocol::channel::Channel::is_ready_to_send(&self) -> bool
pub fn rns_protocol::channel::Channel::new(f64) -> Self
pub fn rns_protocol::channel::Channel::next_timeout_duration(&self) -> core::option::Option<core::time::Duration>
pub fn rns_protocol::channel::Channel::outstanding_count(&self) -> usize
pub fn rns_protocol::channel::Channel::receive(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<(u16, alloc::vec::Vec<u8>)>, rns_protocol::channel::ChannelError>
pub fn rns_protocol::channel::Channel::register_message_type(&mut self, u16) -> core::result::Result<(), rns_protocol::channel::ChannelError>
pub fn rns_protocol::channel::Channel::register_system_type(&mut self, u16)
pub fn rns_protocol::channel::Channel::remove_message_handler(&mut self, rns_protocol::channel::HandlerId) -> bool
pub fn rns_protocol::channel::Channel::send(&mut self, &dyn rns_protocol::channel_message::MessageBase) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::channel::ChannelError>
pub fn rns_protocol::channel::Channel::send_tracked(&mut self, &dyn rns_protocol::channel_message::MessageBase) -> core::result::Result<(u16, alloc::vec::Vec<u8>), rns_protocol::channel::ChannelError>
pub fn rns_protocol::channel::Channel::shutdown(&mut self)
pub fn rns_protocol::channel::Channel::timed_out_sequences(&self) -> alloc::vec::Vec<u16>
pub fn rns_protocol::channel::Channel::timeout(&mut self, u16) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_protocol::channel::ChannelError>
pub fn rns_protocol::channel::Channel::update_rtt(&mut self, f64)
pub struct rns_protocol::channel::ChannelWindow
pub rns_protocol::channel::ChannelWindow::fast_rate_rounds: usize
pub rns_protocol::channel::ChannelWindow::medium_rate_rounds: usize
pub rns_protocol::channel::ChannelWindow::window: usize
pub rns_protocol::channel::ChannelWindow::window_flexibility: usize
pub rns_protocol::channel::ChannelWindow::window_max: usize
pub rns_protocol::channel::ChannelWindow::window_min: usize
impl rns_protocol::channel::ChannelWindow
pub fn rns_protocol::channel::ChannelWindow::grow(&mut self, f64)
pub fn rns_protocol::channel::ChannelWindow::new(f64) -> Self
pub fn rns_protocol::channel::ChannelWindow::shrink(&mut self)
pub struct rns_protocol::channel::Envelope
pub rns_protocol::channel::Envelope::msg_type: u16
pub rns_protocol::channel::Envelope::packed: bool
pub rns_protocol::channel::Envelope::raw: alloc::vec::Vec<u8>
pub rns_protocol::channel::Envelope::sequence: u16
pub rns_protocol::channel::Envelope::state: rns_protocol::channel_message::MessageState
pub rns_protocol::channel::Envelope::tries: usize
impl rns_protocol::channel::Envelope
pub fn rns_protocol::channel::Envelope::pack(&dyn rns_protocol::channel_message::MessageBase, u16) -> Self
pub fn rns_protocol::channel::Envelope::payload(&self) -> &[u8]
pub fn rns_protocol::channel::Envelope::unpack(&[u8]) -> core::result::Result<Self, rns_protocol::channel_message::ChannelMessageError>
pub struct rns_protocol::channel::HandlerId(_)
pub struct rns_protocol::channel::LinkChannel
impl rns_protocol::channel::LinkChannel
pub fn rns_protocol::channel::LinkChannel::add_message_handler(&mut self, rns_protocol::channel::MessageCallback) -> rns_protocol::channel::HandlerId
pub fn rns_protocol::channel::LinkChannel::clear_message_handlers(&mut self)
pub fn rns_protocol::channel::LinkChannel::delivered(&mut self, u16, f64)
pub fn rns_protocol::channel::LinkChannel::delivered_by_packet_hash(&mut self, &[u8; 32], f64) -> core::option::Option<u16>
pub fn rns_protocol::channel::LinkChannel::is_active(&self) -> bool
pub fn rns_protocol::channel::LinkChannel::is_drained(&self) -> bool
pub fn rns_protocol::channel::LinkChannel::is_ready_to_send(&self) -> bool
pub fn rns_protocol::channel::LinkChannel::link_id(&self) -> &[u8; 16]
pub fn rns_protocol::channel::LinkChannel::mdu(&self) -> usize
pub fn rns_protocol::channel::LinkChannel::new([u8; 16], f64) -> Self
pub fn rns_protocol::channel::LinkChannel::new_encrypted([u8; 16], f64, rns_link::key_derivation::LinkKeys) -> Self
pub fn rns_protocol::channel::LinkChannel::new_encrypted_with_mdu([u8; 16], f64, usize, rns_link::key_derivation::LinkKeys) -> Self
pub fn rns_protocol::channel::LinkChannel::new_with_mdu([u8; 16], f64, usize) -> Self
pub fn rns_protocol::channel::LinkChannel::next_timeout_duration(&self) -> core::option::Option<core::time::Duration>
pub fn rns_protocol::channel::LinkChannel::outstanding_count(&self) -> usize
pub fn rns_protocol::channel::LinkChannel::prepare_send(&mut self, &dyn rns_protocol::channel_message::MessageBase) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::channel::ChannelError>
pub fn rns_protocol::channel::LinkChannel::prepare_send_tracked(&mut self, &dyn rns_protocol::channel_message::MessageBase) -> core::result::Result<rns_protocol::channel::PreparedChannelData, rns_protocol::channel::ChannelError>
pub fn rns_protocol::channel::LinkChannel::receive_data(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<(u16, alloc::vec::Vec<u8>)>, rns_protocol::channel::ChannelError>
pub fn rns_protocol::channel::LinkChannel::register_message_type(&mut self, u16) -> core::result::Result<(), rns_protocol::channel::ChannelError>
pub fn rns_protocol::channel::LinkChannel::register_system_type(&mut self, u16)
pub fn rns_protocol::channel::LinkChannel::remove_message_handler(&mut self, rns_protocol::channel::HandlerId) -> bool
pub fn rns_protocol::channel::LinkChannel::shutdown(&mut self)
pub fn rns_protocol::channel::LinkChannel::timed_out_sequences(&self) -> alloc::vec::Vec<u16>
pub fn rns_protocol::channel::LinkChannel::timeout(&mut self, u16) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_protocol::channel::ChannelError>
pub fn rns_protocol::channel::LinkChannel::track_outbound_packet_hash(&mut self, [u8; 32], u16)
pub fn rns_protocol::channel::LinkChannel::update_rtt(&mut self, f64)
pub struct rns_protocol::channel::PreparedChannelData
pub rns_protocol::channel::PreparedChannelData::data: alloc::vec::Vec<u8>
pub rns_protocol::channel::PreparedChannelData::sequence: u16
pub const rns_protocol::channel::ENVELOPE_HEADER_SIZE: usize
pub const rns_protocol::channel::FAST_RATE_THRESHOLD: usize
pub const rns_protocol::channel::MAX_TRIES: usize
pub const rns_protocol::channel::MIN_TIMEOUT_BASE: f64
pub const rns_protocol::channel::RTT_FAST: f64
pub const rns_protocol::channel::RTT_MAX: f64
pub const rns_protocol::channel::RTT_MEDIUM: f64
pub const rns_protocol::channel::RTT_SLOW: f64
pub const rns_protocol::channel::SEQ_MAX: u16
pub const rns_protocol::channel::SEQ_MODULUS: u32
pub const rns_protocol::channel::WINDOW_FLEXIBILITY: usize
pub const rns_protocol::channel::WINDOW_INITIAL: usize
pub const rns_protocol::channel::WINDOW_MAX: usize
pub const rns_protocol::channel::WINDOW_MAX_FAST: usize
pub const rns_protocol::channel::WINDOW_MAX_MEDIUM: usize
pub const rns_protocol::channel::WINDOW_MAX_SLOW: usize
pub const rns_protocol::channel::WINDOW_MIN: usize
pub const rns_protocol::channel::WINDOW_MIN_LIMIT_FAST: usize
pub const rns_protocol::channel::WINDOW_MIN_LIMIT_MEDIUM: usize
pub const rns_protocol::channel::WINDOW_MIN_LIMIT_SLOW: usize
pub type rns_protocol::channel::MessageCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(u16, &[u8]) -> bool + core::marker::Send)>
pub mod rns_protocol::channel_message
pub enum rns_protocol::channel_message::ChannelMessageError
pub rns_protocol::channel_message::ChannelMessageError::InvalidType
pub rns_protocol::channel_message::ChannelMessageError::TooShort
pub rns_protocol::channel_message::ChannelMessageError::UnpackFailed
pub enum rns_protocol::channel_message::MessageState
pub rns_protocol::channel_message::MessageState::Delivered
pub rns_protocol::channel_message::MessageState::Failed
pub rns_protocol::channel_message::MessageState::New
pub rns_protocol::channel_message::MessageState::Sent
pub const rns_protocol::channel_message::SMT_STREAM_DATA: u16
pub const rns_protocol::channel_message::SYSTEM_MESSAGE_TYPE_MIN: u16
pub trait rns_protocol::channel_message::MessageBase: core::marker::Send
pub fn rns_protocol::channel_message::MessageBase::msg_type(&self) -> u16
pub fn rns_protocol::channel_message::MessageBase::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::channel_message::MessageBase::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::CommandExitedMessage
pub fn rns_protocol::rnsh::CommandExitedMessage::msg_type(&self) -> u16
pub fn rns_protocol::rnsh::CommandExitedMessage::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::rnsh::CommandExitedMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::ErrorMessage
pub fn rns_protocol::rnsh::ErrorMessage::msg_type(&self) -> u16
pub fn rns_protocol::rnsh::ErrorMessage::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::rnsh::ErrorMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::ExecuteCommandMessage
pub fn rns_protocol::rnsh::ExecuteCommandMessage::msg_type(&self) -> u16
pub fn rns_protocol::rnsh::ExecuteCommandMessage::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::rnsh::ExecuteCommandMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::NoopMessage
pub fn rns_protocol::rnsh::NoopMessage::msg_type(&self) -> u16
pub fn rns_protocol::rnsh::NoopMessage::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::rnsh::NoopMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::RnshStreamDataMessage
pub fn rns_protocol::rnsh::RnshStreamDataMessage::msg_type(&self) -> u16
pub fn rns_protocol::rnsh::RnshStreamDataMessage::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::rnsh::RnshStreamDataMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::VersionInfoMessage
pub fn rns_protocol::rnsh::VersionInfoMessage::msg_type(&self) -> u16
pub fn rns_protocol::rnsh::VersionInfoMessage::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::rnsh::VersionInfoMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::WindowSizeMessage
pub fn rns_protocol::rnsh::WindowSizeMessage::msg_type(&self) -> u16
pub fn rns_protocol::rnsh::WindowSizeMessage::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::rnsh::WindowSizeMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
impl rns_protocol::channel_message::MessageBase for rns_protocol::stream_data::StreamDataMessage
pub fn rns_protocol::stream_data::StreamDataMessage::msg_type(&self) -> u16
pub fn rns_protocol::stream_data::StreamDataMessage::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::stream_data::StreamDataMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
pub mod rns_protocol::compression
pub enum rns_protocol::compression::CompressionError
pub rns_protocol::compression::CompressionError::CompressFailed
pub rns_protocol::compression::CompressionError::DecompressFailed
pub rns_protocol::compression::CompressionError::DecompressedTooLarge
pub const rns_protocol::compression::AUTO_COMPRESS_MAX_SIZE: usize
pub fn rns_protocol::compression::bz2_compress(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::compression::CompressionError>
pub fn rns_protocol::compression::bz2_decompress(&[u8], usize) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::compression::CompressionError>
pub fn rns_protocol::compression::try_compress(&[u8]) -> (alloc::vec::Vec<u8>, bool)
pub mod rns_protocol::resource
pub enum rns_protocol::resource::CancelType
pub rns_protocol::resource::CancelType::Icl
pub rns_protocol::resource::CancelType::Rcl
pub enum rns_protocol::resource::ResourceError
pub rns_protocol::resource::ResourceError::ControlFrameTooLarge
pub rns_protocol::resource::ResourceError::ControlFrameTooLarge::context: rns_wire::context::PacketContext
pub rns_protocol::resource::ResourceError::ControlFrameTooLarge::encoded_len: usize
pub rns_protocol::resource::ResourceError::ControlFrameTooLarge::mtu: usize
pub rns_protocol::resource::ResourceError::Corrupt
pub rns_protocol::resource::ResourceError::DecompressionFailed
pub rns_protocol::resource::ResourceError::DecryptFailed
pub rns_protocol::resource::ResourceError::DuplicateSegment
pub rns_protocol::resource::ResourceError::HashMismatch
pub rns_protocol::resource::ResourceError::Incomplete
pub rns_protocol::resource::ResourceError::InvalidAdvertisement
pub rns_protocol::resource::ResourceError::InvalidMetadata
pub rns_protocol::resource::ResourceError::InvalidMetadata::available: usize
pub rns_protocol::resource::ResourceError::InvalidMetadata::declared: usize
pub rns_protocol::resource::ResourceError::MapHashCollision
pub rns_protocol::resource::ResourceError::MetadataTooLarge
pub rns_protocol::resource::ResourceError::TooLarge
#[repr(u8)] pub enum rns_protocol::resource::ResourceState
pub rns_protocol::resource::ResourceState::Advertised = 2
pub rns_protocol::resource::ResourceState::Assembling = 5
pub rns_protocol::resource::ResourceState::AwaitingProof = 4
pub rns_protocol::resource::ResourceState::Complete = 6
pub rns_protocol::resource::ResourceState::Corrupt = 8
pub rns_protocol::resource::ResourceState::Failed = 7
pub rns_protocol::resource::ResourceState::None = 0
pub rns_protocol::resource::ResourceState::Queued = 1
pub rns_protocol::resource::ResourceState::Rejected = 9
pub rns_protocol::resource::ResourceState::Transferring = 3
pub enum rns_protocol::resource::TransferAction
pub rns_protocol::resource::TransferAction::Complete
pub rns_protocol::resource::TransferAction::Failed(alloc::string::String)
pub rns_protocol::resource::TransferAction::None
pub rns_protocol::resource::TransferAction::SendAdvertisement(alloc::vec::Vec<u8>)
pub rns_protocol::resource::TransferAction::SendCancel(rns_protocol::resource::CancelType, [u8; 32])
pub rns_protocol::resource::TransferAction::SendHmu(alloc::vec::Vec<u8>)
pub rns_protocol::resource::TransferAction::SendPart(usize, alloc::vec::Vec<u8>)
pub rns_protocol::resource::TransferAction::SendProof(alloc::vec::Vec<u8>)
pub rns_protocol::resource::TransferAction::SendRequest(alloc::vec::Vec<u8>)
pub struct rns_protocol::resource::InboundResource
pub rns_protocol::resource::InboundResource::consecutive_completed: usize
pub rns_protocol::resource::InboundResource::data_size: usize
pub rns_protocol::resource::InboundResource::flags: rns_protocol::resource::ResourceFlags
pub rns_protocol::resource::InboundResource::map_hashes: alloc::vec::Vec<[u8; 4]>
pub rns_protocol::resource::InboundResource::metadata: core::option::Option<alloc::vec::Vec<u8>>
pub rns_protocol::resource::InboundResource::parts: alloc::vec::Vec<core::option::Option<alloc::vec::Vec<u8>>>
pub rns_protocol::resource::InboundResource::random_hash: [u8; 4]
pub rns_protocol::resource::InboundResource::resource_hash: [u8; 32]
pub rns_protocol::resource::InboundResource::sdu: usize
pub rns_protocol::resource::InboundResource::state: rns_protocol::resource::ResourceState
pub rns_protocol::resource::InboundResource::total_parts: usize
pub rns_protocol::resource::InboundResource::total_size: usize
pub rns_protocol::resource::InboundResource::window: rns_protocol::resource::WindowState
impl rns_protocol::resource::InboundResource
pub fn rns_protocol::resource::InboundResource::assemble(&mut self, core::option::Option<&rns_protocol::resource::ResourceDecryptor<'_>>) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource::InboundResource::generate_proof(&self, &[u8]) -> alloc::vec::Vec<u8>
pub fn rns_protocol::resource::InboundResource::handle_cancel(&mut self)
pub fn rns_protocol::resource::InboundResource::is_complete(&self) -> bool
pub fn rns_protocol::resource::InboundResource::new(usize, usize, usize, [u8; 4], [u8; 32], rns_protocol::resource::ResourceFlags, alloc::vec::Vec<[u8; 4]>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource::InboundResource::progress(&self) -> f64
pub fn rns_protocol::resource::InboundResource::receive_part(&mut self, alloc::vec::Vec<u8>) -> bool
pub fn rns_protocol::resource::InboundResource::received_count(&self) -> usize
pub fn rns_protocol::resource::InboundResource::with_sdu(usize, usize, usize, [u8; 4], [u8; 32], rns_protocol::resource::ResourceFlags, alloc::vec::Vec<[u8; 4]>, core::option::Option<usize>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
pub struct rns_protocol::resource::InboundTransfer
pub rns_protocol::resource::InboundTransfer::accepted: bool
pub rns_protocol::resource::InboundTransfer::eifr: core::option::Option<f64>
pub rns_protocol::resource::InboundTransfer::hashmap_height: usize
pub rns_protocol::resource::InboundTransfer::last_activity: std::time::Instant
pub rns_protocol::resource::InboundTransfer::outstanding_parts: usize
pub rns_protocol::resource::InboundTransfer::part_timeout_factor: f64
pub rns_protocol::resource::InboundTransfer::parts_since_hmu: usize
pub rns_protocol::resource::InboundTransfer::previous_eifr: core::option::Option<f64>
pub rns_protocol::resource::InboundTransfer::req_data_rtt_rate: f64
pub rns_protocol::resource::InboundTransfer::req_resp: core::option::Option<std::time::Instant>
pub rns_protocol::resource::InboundTransfer::req_sent: core::option::Option<std::time::Instant>
pub rns_protocol::resource::InboundTransfer::resource: rns_protocol::resource::InboundResource
pub rns_protocol::resource::InboundTransfer::retries_left: usize
pub rns_protocol::resource::InboundTransfer::rtt: core::time::Duration
pub rns_protocol::resource::InboundTransfer::rtt_rxd_bytes: usize
pub rns_protocol::resource::InboundTransfer::rtt_rxd_bytes_at_part_req: usize
pub rns_protocol::resource::InboundTransfer::started_at: std::time::Instant
pub rns_protocol::resource::InboundTransfer::waiting_for_hmu: bool
impl rns_protocol::resource::InboundTransfer
pub fn rns_protocol::resource::InboundTransfer::cancel(&mut self) -> rns_protocol::resource::TransferAction
pub fn rns_protocol::resource::InboundTransfer::check_timeout(&mut self) -> rns_protocol::resource::TransferAction
pub fn rns_protocol::resource::InboundTransfer::complete(&mut self, core::option::Option<&rns_protocol::resource::ResourceDecryptor<'_>>) -> core::result::Result<(alloc::vec::Vec<u8>, alloc::vec::Vec<u8>), rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource::InboundTransfer::create_hmu(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::resource::InboundTransfer::from_advertisement(usize, usize, usize, [u8; 4], [u8; 32], rns_protocol::resource::ResourceFlags, alloc::vec::Vec<[u8; 4]>, core::time::Duration) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource::InboundTransfer::handle_cancel(&mut self)
pub fn rns_protocol::resource::InboundTransfer::hashmap_update(&mut self, usize, &[u8]) -> rns_protocol::resource::TransferAction
pub fn rns_protocol::resource::InboundTransfer::progress(&self) -> f64
pub fn rns_protocol::resource::InboundTransfer::receive_part(&mut self, alloc::vec::Vec<u8>) -> rns_protocol::resource::TransferAction
pub fn rns_protocol::resource::InboundTransfer::request_next(&mut self) -> rns_protocol::resource::TransferAction
pub fn rns_protocol::resource::InboundTransfer::seed_previous_eifr(&mut self, f64)
pub fn rns_protocol::resource::InboundTransfer::update_eifr(&mut self)
pub struct rns_protocol::resource::LazyMultiSegmentOutbound
pub rns_protocol::resource::LazyMultiSegmentOutbound::data_size: usize
pub rns_protocol::resource::LazyMultiSegmentOutbound::original_hash: [u8; 32]
pub rns_protocol::resource::LazyMultiSegmentOutbound::total_segments: usize
impl rns_protocol::resource::LazyMultiSegmentOutbound
pub fn rns_protocol::resource::LazyMultiSegmentOutbound::new(alloc::vec::Vec<u8>, bool) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource::LazyMultiSegmentOutbound::next_segment(&mut self, core::option::Option<&rns_protocol::resource::ResourceEncryptor<'_>>) -> core::result::Result<core::option::Option<rns_protocol::resource::OutboundResource>, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource::LazyMultiSegmentOutbound::remaining_segments(&self) -> usize
pub fn rns_protocol::resource::LazyMultiSegmentOutbound::with_options(alloc::vec::Vec<u8>, bool, core::option::Option<alloc::vec::Vec<u8>>, core::option::Option<alloc::vec::Vec<u8>>, bool) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
pub struct rns_protocol::resource::LinkResource
pub rns_protocol::resource::LinkResource::inbound: core::option::Option<rns_protocol::resource::InboundResource>
pub rns_protocol::resource::LinkResource::link_id: [u8; 16]
pub rns_protocol::resource::LinkResource::outbound: core::option::Option<rns_protocol::resource::OutboundResource>
pub rns_protocol::resource::LinkResource::session_keys: core::option::Option<rns_link::key_derivation::LinkKeys>
impl rns_protocol::resource::LinkResource
pub fn rns_protocol::resource::LinkResource::assemble(&mut self) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource::LinkResource::is_complete(&self) -> bool
pub fn rns_protocol::resource::LinkResource::new_inbound([u8; 16], usize, usize, usize, [u8; 4], [u8; 32], rns_protocol::resource::ResourceFlags, alloc::vec::Vec<[u8; 4]>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource::LinkResource::new_outbound([u8; 16], alloc::vec::Vec<u8>, bool) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource::LinkResource::new_outbound_encrypted([u8; 16], alloc::vec::Vec<u8>, bool, rns_link::key_derivation::LinkKeys) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource::LinkResource::next_part(&self, usize) -> core::option::Option<alloc::vec::Vec<u8>>
pub fn rns_protocol::resource::LinkResource::num_parts(&self) -> usize
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_segments: alloc::vec::Vec<core::option::Option<alloc::vec::Vec<u8>>>
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]
pub rns_protocol::resource::MultiSegmentInbound::segments: alloc::vec::Vec<core::option::Option<rns_protocol::resource::InboundResource>>
pub rns_protocol::resource::MultiSegmentInbound::total_segments: usize
impl rns_protocol::resource::MultiSegmentInbound
pub fn rns_protocol::resource::MultiSegmentInbound::assemble_segment(&mut self, usize, core::option::Option<&rns_protocol::resource::ResourceDecryptor<'_>>) -> core::result::Result<(), rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource::MultiSegmentInbound::assembled_count(&self) -> usize
pub fn rns_protocol::resource::MultiSegmentInbound::is_complete(&self) -> bool
pub fn rns_protocol::resource::MultiSegmentInbound::new(usize, [u8; 32]) -> Self
pub fn rns_protocol::resource::MultiSegmentInbound::progress(&self) -> f64
pub fn rns_protocol::resource::MultiSegmentInbound::reassemble(&self) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::resource::ResourceError>
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 struct rns_protocol::resource::MultiSegmentOutbound
pub rns_protocol::resource::MultiSegmentOutbound::data_size: usize
pub rns_protocol::resource::MultiSegmentOutbound::original_hash: [u8; 32]
pub rns_protocol::resource::MultiSegmentOutbound::segments: alloc::vec::Vec<rns_protocol::resource::OutboundResource>
pub rns_protocol::resource::MultiSegmentOutbound::total_segments: usize
impl rns_protocol::resource::MultiSegmentOutbound
pub fn rns_protocol::resource::MultiSegmentOutbound::cancel_all(&mut self) -> usize
pub fn rns_protocol::resource::MultiSegmentOutbound::get_segment(&self, usize) -> core::option::Option<&rns_protocol::resource::OutboundResource>
pub fn rns_protocol::resource::MultiSegmentOutbound::get_segment_mut(&mut self, usize) -> core::option::Option<&mut rns_protocol::resource::OutboundResource>
pub fn rns_protocol::resource::MultiSegmentOutbound::is_complete(&self) -> bool
pub fn rns_protocol::resource::MultiSegmentOutbound::new(alloc::vec::Vec<u8>, bool) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource::MultiSegmentOutbound::num_segments(&self) -> usize
pub fn rns_protocol::resource::MultiSegmentOutbound::with_encrypt(alloc::vec::Vec<u8>, bool, core::option::Option<&rns_protocol::resource::ResourceEncryptor<'_>>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource::MultiSegmentOutbound::with_options(alloc::vec::Vec<u8>, bool, core::option::Option<alloc::vec::Vec<u8>>, core::option::Option<alloc::vec::Vec<u8>>, bool, core::option::Option<&rns_protocol::resource::ResourceEncryptor<'_>>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
pub struct rns_protocol::resource::OutboundResource
pub rns_protocol::resource::OutboundResource::advertisement_data_size: usize
pub rns_protocol::resource::OutboundResource::data: alloc::vec::Vec<u8>
pub rns_protocol::resource::OutboundResource::expected_proof: [u8; 32]
pub rns_protocol::resource::OutboundResource::flags: rns_protocol::resource::ResourceFlags
pub rns_protocol::resource::OutboundResource::map_hashes: alloc::vec::Vec<[u8; 4]>
pub rns_protocol::resource::OutboundResource::metadata: core::option::Option<alloc::vec::Vec<u8>>
pub rns_protocol::resource::OutboundResource::metadata_size: usize
pub rns_protocol::resource::OutboundResource::original_hash: core::option::Option<[u8; 32]>
pub rns_protocol::resource::OutboundResource::parts: alloc::vec::Vec<alloc::vec::Vec<u8>>
pub rns_protocol::resource::OutboundResource::random_hash: [u8; 4]
pub rns_protocol::resource::OutboundResource::request_id: core::option::Option<alloc::vec::Vec<u8>>
pub rns_protocol::resource::OutboundResource::resource_hash: [u8; 32]
pub rns_protocol::resource::OutboundResource::retries: usize
pub rns_protocol::resource::OutboundResource::sdu: usize
pub rns_protocol::resource::OutboundResource::segment_index: usize
pub rns_protocol::resource::OutboundResource::state: rns_protocol::resource::ResourceState
pub rns_protocol::resource::OutboundResource::total_segments: usize
pub rns_protocol::resource::OutboundResource::total_size: usize
pub rns_protocol::resource::OutboundResource::window: rns_protocol::resource::WindowState
impl rns_protocol::resource::OutboundResource
pub fn rns_protocol::resource::OutboundResource::get_part(&self, usize) -> core::option::Option<&[u8]>
pub fn rns_protocol::resource::OutboundResource::handle_cancel(&mut self)
pub fn rns_protocol::resource::OutboundResource::handle_hmu(&mut self, &[u8]) -> alloc::vec::Vec<usize>
pub fn rns_protocol::resource::OutboundResource::new(alloc::vec::Vec<u8>, bool, core::option::Option<&rns_protocol::resource::ResourceEncryptor<'_>>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource::OutboundResource::num_parts(&self) -> usize
pub fn rns_protocol::resource::OutboundResource::validate_proof(&mut self, &[u8]) -> bool
pub fn rns_protocol::resource::OutboundResource::with_options(alloc::vec::Vec<u8>, bool, core::option::Option<alloc::vec::Vec<u8>>, core::option::Option<usize>, core::option::Option<&rns_protocol::resource::ResourceEncryptor<'_>>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
pub struct rns_protocol::resource::OutboundTransfer
pub rns_protocol::resource::OutboundTransfer::advertised: bool
pub rns_protocol::resource::OutboundTransfer::awaiting_hmu: bool
pub rns_protocol::resource::OutboundTransfer::confirmed_parts: alloc::vec::Vec<bool>
pub rns_protocol::resource::OutboundTransfer::cursor: usize
pub rns_protocol::resource::OutboundTransfer::last_part_sent: core::option::Option<std::time::Instant>
pub rns_protocol::resource::OutboundTransfer::receiver_min_consecutive_height: usize
pub rns_protocol::resource::OutboundTransfer::resource: rns_protocol::resource::OutboundResource
pub rns_protocol::resource::OutboundTransfer::retries: usize
pub rns_protocol::resource::OutboundTransfer::rtt: core::time::Duration
pub rns_protocol::resource::OutboundTransfer::sent_parts: usize
pub rns_protocol::resource::OutboundTransfer::started_at: std::time::Instant
pub rns_protocol::resource::OutboundTransfer::window_cursor: usize
pub rns_protocol::resource::OutboundTransfer::window_max_sent: usize
impl rns_protocol::resource::OutboundTransfer
pub fn rns_protocol::resource::OutboundTransfer::all_confirmed(&self) -> bool
pub fn rns_protocol::resource::OutboundTransfer::check_timeout(&mut self) -> rns_protocol::resource::TransferAction
pub fn rns_protocol::resource::OutboundTransfer::from_prebuilt(rns_protocol::resource::OutboundResource, core::time::Duration) -> Self
pub fn rns_protocol::resource::OutboundTransfer::handle_cancel(&mut self)
pub fn rns_protocol::resource::OutboundTransfer::handle_hmu(&mut self, &[u8])
pub fn rns_protocol::resource::OutboundTransfer::handle_proof(&mut self, &[u8]) -> bool
pub fn rns_protocol::resource::OutboundTransfer::handle_request(&mut self, &[u8]) -> alloc::vec::Vec<rns_protocol::resource::TransferAction>
pub fn rns_protocol::resource::OutboundTransfer::handle_request_packet(&mut self, [u8; 32], &[u8]) -> alloc::vec::Vec<rns_protocol::resource::TransferAction>
pub fn rns_protocol::resource::OutboundTransfer::new(alloc::vec::Vec<u8>, bool, core::time::Duration) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource::OutboundTransfer::new_encrypted(alloc::vec::Vec<u8>, bool, core::time::Duration, rns_link::key_derivation::LinkKeys) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource::OutboundTransfer::progress(&self) -> f64
pub fn rns_protocol::resource::OutboundTransfer::tick(&mut self) -> rns_protocol::resource::TransferAction
pub fn rns_protocol::resource::OutboundTransfer::timeout_window(&self) -> core::option::Option<(std::time::Instant, core::time::Duration)>
pub struct rns_protocol::resource::ResourceFlags
pub rns_protocol::resource::ResourceFlags::compressed: bool
pub rns_protocol::resource::ResourceFlags::encrypted: bool
pub rns_protocol::resource::ResourceFlags::has_metadata: bool
pub rns_protocol::resource::ResourceFlags::is_request: bool
pub rns_protocol::resource::ResourceFlags::is_response: bool
pub rns_protocol::resource::ResourceFlags::split: bool
impl rns_protocol::resource::ResourceFlags
pub fn rns_protocol::resource::ResourceFlags::from_byte(u8) -> Self
pub fn rns_protocol::resource::ResourceFlags::to_byte(&self) -> u8
pub struct rns_protocol::resource::WindowState
pub rns_protocol::resource::WindowState::fast_rate_rounds: usize
pub rns_protocol::resource::WindowState::very_slow_rate_rounds: usize
pub rns_protocol::resource::WindowState::window: usize
pub rns_protocol::resource::WindowState::window_max: usize
pub rns_protocol::resource::WindowState::window_min: usize
impl rns_protocol::resource::WindowState
pub fn rns_protocol::resource::WindowState::grow(&mut self, usize)
pub fn rns_protocol::resource::WindowState::new() -> Self
pub fn rns_protocol::resource::WindowState::shrink(&mut self)
impl core::default::Default for rns_protocol::resource::WindowState
pub fn rns_protocol::resource::WindowState::default() -> Self
pub const rns_protocol::resource::EIFR_COLD_START_BYTES: usize
pub const rns_protocol::resource::FAST_RATE_THRESHOLD: usize
pub const rns_protocol::resource::HASHMAP_IS_EXHAUSTED: u8
pub const rns_protocol::resource::HASHMAP_IS_NOT_EXHAUSTED: u8
pub const rns_protocol::resource::HMU_WAIT_FACTOR: f64
pub const rns_protocol::resource::MAPHASH_LEN: usize
pub const rns_protocol::resource::MAX_ADV_RETRIES: usize
pub const rns_protocol::resource::MAX_EFFICIENT_SIZE: usize
pub const rns_protocol::resource::MAX_RESOURCE_SIZE: usize
pub const rns_protocol::resource::MAX_RETRIES: usize
pub const rns_protocol::resource::MAX_SEGMENTS: usize
pub const rns_protocol::resource::METADATA_MAX_SIZE: usize
pub const rns_protocol::resource::PART_TIMEOUT_FACTOR: f64
pub const rns_protocol::resource::PART_TIMEOUT_FACTOR_AFTER_RTT: f64
pub const rns_protocol::resource::PER_RETRY_DELAY: f64
pub const rns_protocol::resource::PROCESSING_GRACE: f64
pub const rns_protocol::resource::PROOF_TIMEOUT_FACTOR: f64
pub const rns_protocol::resource::RANDOM_HASH_SIZE: usize
pub const rns_protocol::resource::RATE_FAST: usize
pub const rns_protocol::resource::RATE_VERY_SLOW: usize
pub const rns_protocol::resource::RETRY_GRACE_TIME: f64
pub const rns_protocol::resource::SDU: usize
pub const rns_protocol::resource::SENDER_GRACE_TIME: f64
pub const rns_protocol::resource::VERY_SLOW_RATE_THRESHOLD: usize
pub const rns_protocol::resource::WATCHDOG_MAX_SLEEP: f64
pub const rns_protocol::resource::WINDOW_FLEXIBILITY: usize
pub const rns_protocol::resource::WINDOW_INITIAL: usize
pub const rns_protocol::resource::WINDOW_MAX: usize
pub const rns_protocol::resource::WINDOW_MAX_FAST: usize
pub const rns_protocol::resource::WINDOW_MAX_SLOW: usize
pub const rns_protocol::resource::WINDOW_MAX_VERY_SLOW: usize
pub const rns_protocol::resource::WINDOW_MIN: usize
pub fn rns_protocol::resource::compute_expected_proof(&[u8], &[u8; 32]) -> [u8; 32]
pub fn rns_protocol::resource::compute_resource_hash(&[u8], &[u8]) -> [u8; 32]
pub fn rns_protocol::resource::get_map_hash(&[u8], &[u8]) -> [u8; 4]
pub fn rns_protocol::resource::parse_hashmap_update(&[u8]) -> core::result::Result<([u8; 32], usize, alloc::vec::Vec<u8>), rns_protocol::resource::ResourceError>
pub type rns_protocol::resource::ResourceDecryptor<'a> = (dyn core::ops::function::Fn(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::resource::ResourceError> + 'a)
pub type rns_protocol::resource::ResourceEncryptor<'a> = (dyn core::ops::function::Fn(&[u8]) -> alloc::vec::Vec<u8> + 'a)
pub mod rns_protocol::resource_adv
pub struct rns_protocol::resource_adv::ResourceAdvertisement
pub rns_protocol::resource_adv::ResourceAdvertisement::data_size: usize
pub rns_protocol::resource_adv::ResourceAdvertisement::flags: rns_protocol::resource::ResourceFlags
pub rns_protocol::resource_adv::ResourceAdvertisement::hashmap: alloc::vec::Vec<u8>
pub rns_protocol::resource_adv::ResourceAdvertisement::metadata_size: usize
pub rns_protocol::resource_adv::ResourceAdvertisement::num_parts: usize
pub rns_protocol::resource_adv::ResourceAdvertisement::original_hash: [u8; 32]
pub rns_protocol::resource_adv::ResourceAdvertisement::random_hash: alloc::vec::Vec<u8>
pub rns_protocol::resource_adv::ResourceAdvertisement::request_id: core::option::Option<alloc::vec::Vec<u8>>
pub rns_protocol::resource_adv::ResourceAdvertisement::resource_hash: [u8; 32]
pub rns_protocol::resource_adv::ResourceAdvertisement::segment_index: usize
pub rns_protocol::resource_adv::ResourceAdvertisement::total_segments: usize
pub rns_protocol::resource_adv::ResourceAdvertisement::transfer_size: usize
impl rns_protocol::resource_adv::ResourceAdvertisement
pub fn rns_protocol::resource_adv::ResourceAdvertisement::encoded_len(&self) -> core::result::Result<usize, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource_adv::ResourceAdvertisement::get_map_hashes(&self) -> alloc::vec::Vec<[u8; 4]>
pub fn rns_protocol::resource_adv::ResourceAdvertisement::new(usize, usize, usize, [u8; 32], alloc::vec::Vec<u8>, rns_protocol::resource::ResourceFlags, &[[u8; 4]], usize) -> Self
pub fn rns_protocol::resource_adv::ResourceAdvertisement::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::resource_adv::ResourceAdvertisement::pack_into<W: core::io::write::Write>(&self, W) -> core::result::Result<(), rmp_serde::encode::Error>
pub fn rns_protocol::resource_adv::ResourceAdvertisement::unpack(&[u8]) -> core::result::Result<Self, alloc::string::String>
pub fn rns_protocol::resource_adv::ResourceAdvertisement::with_metadata_size(usize, usize, usize, [u8; 32], alloc::vec::Vec<u8>, rns_protocol::resource::ResourceFlags, &[[u8; 4]], usize, usize) -> Self
pub const rns_protocol::resource_adv::OVERHEAD: usize
pub fn rns_protocol::resource_adv::collision_guard_size(usize) -> usize
pub fn rns_protocol::resource_adv::hashmap_max_len(usize) -> usize
pub mod rns_protocol::resource_control
pub const rns_protocol::resource_control::HASHMAP_STRIDE: usize
pub fn rns_protocol::resource_control::check_advertisement(&rns_protocol::resource_adv::ResourceAdvertisement, usize) -> core::result::Result<(), rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource_control::check_control_frame(rns_wire::context::PacketContext, usize, bool, usize, usize) -> core::result::Result<(), rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource_control::encode_hashmap_update(&[u8; 32], usize, &[u8]) -> alloc::vec::Vec<u8>
pub fn rns_protocol::resource_control::encrypted_len(usize) -> core::result::Result<usize, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource_control::preflight_outbound(usize, core::option::Option<usize>, core::option::Option<&[u8]>, bool, bool, usize) -> core::result::Result<(), rns_protocol::resource::ResourceError>
pub mod rns_protocol::rnsh
pub enum rns_protocol::rnsh::RnshCodecError
pub rns_protocol::rnsh::RnshCodecError::Decode(alloc::string::String)
pub rns_protocol::rnsh::RnshCodecError::Encode(alloc::string::String)
pub rns_protocol::rnsh::RnshCodecError::InvalidShape(&'static str)
pub rns_protocol::rnsh::RnshCodecError::InvalidUtf8
pub rns_protocol::rnsh::RnshCodecError::StreamData
pub rns_protocol::rnsh::RnshCodecError::UnknownMessageType(u16)
pub enum rns_protocol::rnsh::RnshMessage
pub rns_protocol::rnsh::RnshMessage::CommandExited(rns_protocol::rnsh::CommandExitedMessage)
pub rns_protocol::rnsh::RnshMessage::Error(rns_protocol::rnsh::ErrorMessage)
pub rns_protocol::rnsh::RnshMessage::ExecuteCommand(rns_protocol::rnsh::ExecuteCommandMessage)
pub rns_protocol::rnsh::RnshMessage::Noop(rns_protocol::rnsh::NoopMessage)
pub rns_protocol::rnsh::RnshMessage::StreamData(rns_protocol::rnsh::RnshStreamDataMessage)
pub rns_protocol::rnsh::RnshMessage::VersionInfo(rns_protocol::rnsh::VersionInfoMessage)
pub rns_protocol::rnsh::RnshMessage::WindowSize(rns_protocol::rnsh::WindowSizeMessage)
impl rns_protocol::rnsh::RnshMessage
pub fn rns_protocol::rnsh::RnshMessage::decode(u16, &[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
pub fn rns_protocol::rnsh::RnshMessage::msg_type(&self) -> u16
pub fn rns_protocol::rnsh::RnshMessage::pack(&self) -> alloc::vec::Vec<u8>
pub struct rns_protocol::rnsh::CommandExitedMessage
pub rns_protocol::rnsh::CommandExitedMessage::return_code: i64
impl rns_protocol::rnsh::CommandExitedMessage
pub fn rns_protocol::rnsh::CommandExitedMessage::new(i64) -> Self
pub fn rns_protocol::rnsh::CommandExitedMessage::unpack_payload(&[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::CommandExitedMessage
pub fn rns_protocol::rnsh::CommandExitedMessage::msg_type(&self) -> u16
pub fn rns_protocol::rnsh::CommandExitedMessage::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::rnsh::CommandExitedMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
pub struct rns_protocol::rnsh::ErrorMessage
pub rns_protocol::rnsh::ErrorMessage::data: core::option::Option<rmpv::Value>
pub rns_protocol::rnsh::ErrorMessage::fatal: bool
pub rns_protocol::rnsh::ErrorMessage::msg: core::option::Option<alloc::string::String>
impl rns_protocol::rnsh::ErrorMessage
pub fn rns_protocol::rnsh::ErrorMessage::new(core::option::Option<alloc::string::String>, bool, core::option::Option<rmpv::Value>) -> Self
pub fn rns_protocol::rnsh::ErrorMessage::unpack_payload(&[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::ErrorMessage
pub fn rns_protocol::rnsh::ErrorMessage::msg_type(&self) -> u16
pub fn rns_protocol::rnsh::ErrorMessage::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::rnsh::ErrorMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
pub struct rns_protocol::rnsh::ExecuteCommandMessage
pub rns_protocol::rnsh::ExecuteCommandMessage::cmdline: core::option::Option<alloc::vec::Vec<alloc::string::String>>
pub rns_protocol::rnsh::ExecuteCommandMessage::cols: core::option::Option<u32>
pub rns_protocol::rnsh::ExecuteCommandMessage::hpix: core::option::Option<u32>
pub rns_protocol::rnsh::ExecuteCommandMessage::pipe_stderr: bool
pub rns_protocol::rnsh::ExecuteCommandMessage::pipe_stdin: bool
pub rns_protocol::rnsh::ExecuteCommandMessage::pipe_stdout: bool
pub rns_protocol::rnsh::ExecuteCommandMessage::rows: core::option::Option<u32>
pub rns_protocol::rnsh::ExecuteCommandMessage::tcflags: core::option::Option<rmpv::Value>
pub rns_protocol::rnsh::ExecuteCommandMessage::term: core::option::Option<alloc::string::String>
pub rns_protocol::rnsh::ExecuteCommandMessage::vpix: core::option::Option<u32>
impl rns_protocol::rnsh::ExecuteCommandMessage
pub fn rns_protocol::rnsh::ExecuteCommandMessage::new(core::option::Option<alloc::vec::Vec<alloc::string::String>>, bool, bool, bool, core::option::Option<rmpv::Value>, core::option::Option<alloc::string::String>, core::option::Option<u32>, core::option::Option<u32>, core::option::Option<u32>, core::option::Option<u32>) -> Self
pub fn rns_protocol::rnsh::ExecuteCommandMessage::unpack_payload(&[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::ExecuteCommandMessage
pub fn rns_protocol::rnsh::ExecuteCommandMessage::msg_type(&self) -> u16
pub fn rns_protocol::rnsh::ExecuteCommandMessage::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::rnsh::ExecuteCommandMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
pub struct rns_protocol::rnsh::NoopMessage
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::NoopMessage
pub fn rns_protocol::rnsh::NoopMessage::msg_type(&self) -> u16
pub fn rns_protocol::rnsh::NoopMessage::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::rnsh::NoopMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
pub struct rns_protocol::rnsh::RnshStreamDataMessage
pub rns_protocol::rnsh::RnshStreamDataMessage::compressed: bool
pub rns_protocol::rnsh::RnshStreamDataMessage::data: alloc::vec::Vec<u8>
pub rns_protocol::rnsh::RnshStreamDataMessage::eof: bool
pub rns_protocol::rnsh::RnshStreamDataMessage::stream_id: u16
impl rns_protocol::rnsh::RnshStreamDataMessage
pub fn rns_protocol::rnsh::RnshStreamDataMessage::new(u16, alloc::vec::Vec<u8>, bool) -> Self
pub fn rns_protocol::rnsh::RnshStreamDataMessage::unpack_payload(&[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
impl core::default::Default for rns_protocol::rnsh::RnshStreamDataMessage
pub fn rns_protocol::rnsh::RnshStreamDataMessage::default() -> Self
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::RnshStreamDataMessage
pub fn rns_protocol::rnsh::RnshStreamDataMessage::msg_type(&self) -> u16
pub fn rns_protocol::rnsh::RnshStreamDataMessage::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::rnsh::RnshStreamDataMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
pub struct rns_protocol::rnsh::VersionInfoMessage
pub rns_protocol::rnsh::VersionInfoMessage::protocol_version: u64
pub rns_protocol::rnsh::VersionInfoMessage::sw_version: alloc::string::String
impl rns_protocol::rnsh::VersionInfoMessage
pub fn rns_protocol::rnsh::VersionInfoMessage::new(impl core::convert::Into<alloc::string::String>) -> Self
pub fn rns_protocol::rnsh::VersionInfoMessage::unpack_payload(&[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
impl core::default::Default for rns_protocol::rnsh::VersionInfoMessage
pub fn rns_protocol::rnsh::VersionInfoMessage::default() -> Self
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::VersionInfoMessage
pub fn rns_protocol::rnsh::VersionInfoMessage::msg_type(&self) -> u16
pub fn rns_protocol::rnsh::VersionInfoMessage::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::rnsh::VersionInfoMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
pub struct rns_protocol::rnsh::WindowSizeMessage
pub rns_protocol::rnsh::WindowSizeMessage::cols: core::option::Option<u32>
pub rns_protocol::rnsh::WindowSizeMessage::hpix: core::option::Option<u32>
pub rns_protocol::rnsh::WindowSizeMessage::rows: core::option::Option<u32>
pub rns_protocol::rnsh::WindowSizeMessage::vpix: core::option::Option<u32>
impl rns_protocol::rnsh::WindowSizeMessage
pub fn rns_protocol::rnsh::WindowSizeMessage::new(core::option::Option<u32>, core::option::Option<u32>, core::option::Option<u32>, core::option::Option<u32>) -> Self
pub fn rns_protocol::rnsh::WindowSizeMessage::unpack_payload(&[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::WindowSizeMessage
pub fn rns_protocol::rnsh::WindowSizeMessage::msg_type(&self) -> u16
pub fn rns_protocol::rnsh::WindowSizeMessage::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::rnsh::WindowSizeMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
pub const rns_protocol::rnsh::MESSAGE_TYPES: [u16; 7]
pub const rns_protocol::rnsh::MSG_MAGIC: u8
pub const rns_protocol::rnsh::MSG_TYPE_COMMAND_EXITED: u16
pub const rns_protocol::rnsh::MSG_TYPE_ERROR: u16
pub const rns_protocol::rnsh::MSG_TYPE_EXECUTE_COMMAND: u16
pub const rns_protocol::rnsh::MSG_TYPE_NOOP: u16
pub const rns_protocol::rnsh::MSG_TYPE_STREAM_DATA: u16
pub const rns_protocol::rnsh::MSG_TYPE_VERSION_INFO: u16
pub const rns_protocol::rnsh::MSG_TYPE_WINDOW_SIZE: u16
pub const rns_protocol::rnsh::PROTOCOL_VERSION: u64
pub const rns_protocol::rnsh::STREAM_DATA_OVERHEAD: usize
pub const rns_protocol::rnsh::STREAM_ID_MAX: u16
pub const rns_protocol::rnsh::STREAM_ID_STDERR: u16
pub const rns_protocol::rnsh::STREAM_ID_STDIN: u16
pub const rns_protocol::rnsh::STREAM_ID_STDOUT: u16
pub const fn rns_protocol::rnsh::make_msg_type(u8) -> u16
pub mod rns_protocol::stream_data
pub struct rns_protocol::stream_data::StreamDataMessage
pub rns_protocol::stream_data::StreamDataMessage::compressed: bool
pub rns_protocol::stream_data::StreamDataMessage::data: alloc::vec::Vec<u8>
pub rns_protocol::stream_data::StreamDataMessage::eof: bool
pub rns_protocol::stream_data::StreamDataMessage::stream_id: u16
impl rns_protocol::stream_data::StreamDataMessage
pub fn rns_protocol::stream_data::StreamDataMessage::new(u16, alloc::vec::Vec<u8>, bool) -> Self
impl rns_protocol::channel_message::MessageBase for rns_protocol::stream_data::StreamDataMessage
pub fn rns_protocol::stream_data::StreamDataMessage::msg_type(&self) -> u16
pub fn rns_protocol::stream_data::StreamDataMessage::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::stream_data::StreamDataMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
pub const rns_protocol::stream_data::OVERHEAD: usize
pub const rns_protocol::stream_data::STREAM_ID_MAX: u16
+618
View File
@@ -0,0 +1,618 @@
pub mod rns_ratkey
pub mod rns_ratkey::apdu
pub const rns_ratkey::apdu::ALG_ECCP256: u8
pub const rns_ratkey::apdu::ALG_ECCP384: u8
pub const rns_ratkey::apdu::ALG_ED25519: u8
pub const rns_ratkey::apdu::ALG_X25519: u8
pub const rns_ratkey::apdu::INS_ATTEST: u8
pub const rns_ratkey::apdu::INS_CHANGE_REFERENCE: u8
pub const rns_ratkey::apdu::INS_GENERAL_AUTHENTICATE: u8
pub const rns_ratkey::apdu::INS_GENERATE_ASYMMETRIC: u8
pub const rns_ratkey::apdu::INS_GET_DATA: u8
pub const rns_ratkey::apdu::INS_GET_METADATA: u8
pub const rns_ratkey::apdu::INS_GET_SERIAL: u8
pub const rns_ratkey::apdu::INS_GET_VERSION: u8
pub const rns_ratkey::apdu::INS_IMPORT_KEY: u8
pub const rns_ratkey::apdu::INS_RESET_PIV: u8
pub const rns_ratkey::apdu::INS_RESET_RETRY: u8
pub const rns_ratkey::apdu::INS_SELECT: u8
pub const rns_ratkey::apdu::INS_VERIFY: u8
pub const rns_ratkey::apdu::MGMT_ALG_AES128: u8
pub const rns_ratkey::apdu::MGMT_ALG_AES192: u8
pub const rns_ratkey::apdu::MGMT_ALG_AES256: u8
pub const rns_ratkey::apdu::MGMT_ALG_TDES: u8
pub const rns_ratkey::apdu::OBJ_ID_9A: &[u8]
pub const rns_ratkey::apdu::OBJ_ID_9D: &[u8]
pub const rns_ratkey::apdu::OBJ_ID_F9: &[u8]
pub const rns_ratkey::apdu::PIN_POLICY_ALWAYS: u8
pub const rns_ratkey::apdu::PIN_POLICY_NEVER: u8
pub const rns_ratkey::apdu::PIN_POLICY_ONCE: u8
pub const rns_ratkey::apdu::PIV_AID: &[u8]
pub const rns_ratkey::apdu::SLOT_ATTESTATION: u8
pub const rns_ratkey::apdu::SLOT_AUTHENTICATION: u8
pub const rns_ratkey::apdu::SLOT_CARD_AUTH: u8
pub const rns_ratkey::apdu::SLOT_CARD_MANAGEMENT: u8
pub const rns_ratkey::apdu::SLOT_KEY_MANAGEMENT: u8
pub const rns_ratkey::apdu::SLOT_SIGNATURE: u8
pub const rns_ratkey::apdu::TOUCH_POLICY_ALWAYS: u8
pub const rns_ratkey::apdu::TOUCH_POLICY_CACHED: u8
pub const rns_ratkey::apdu::TOUCH_POLICY_NEVER: u8
pub fn rns_ratkey::apdu::attest_key(u8) -> alloc::vec::Vec<u8>
pub fn rns_ratkey::apdu::auth_witness_request(u8) -> alloc::vec::Vec<u8>
pub fn rns_ratkey::apdu::auth_witness_response(u8, &[u8], &[u8]) -> alloc::vec::Vec<u8>
pub fn rns_ratkey::apdu::change_pin(&str, &str) -> alloc::vec::Vec<u8>
pub fn rns_ratkey::apdu::check_response(&[u8]) -> core::result::Result<&[u8], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::apdu::ecdh_x25519(u8, &[u8; 32]) -> alloc::vec::Vec<u8>
pub fn rns_ratkey::apdu::generate_key(u8, u8, core::option::Option<u8>, core::option::Option<u8>) -> alloc::vec::Vec<u8>
pub fn rns_ratkey::apdu::get_data(u8) -> core::option::Option<alloc::vec::Vec<u8>>
pub fn rns_ratkey::apdu::get_metadata(u8) -> alloc::vec::Vec<u8>
pub fn rns_ratkey::apdu::get_serial() -> alloc::vec::Vec<u8>
pub fn rns_ratkey::apdu::get_version() -> alloc::vec::Vec<u8>
pub fn rns_ratkey::apdu::import_ed25519(u8, &[u8; 32], core::option::Option<u8>, core::option::Option<u8>) -> alloc::vec::Vec<u8>
pub fn rns_ratkey::apdu::import_x25519(u8, &[u8; 32], core::option::Option<u8>, core::option::Option<u8>) -> alloc::vec::Vec<u8>
pub fn rns_ratkey::apdu::parse_auth_response(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::apdu::parse_auth_witness(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::apdu::parse_certificate_object(&[u8]) -> core::option::Option<alloc::vec::Vec<u8>>
pub fn rns_ratkey::apdu::parse_ecdh_response(&[u8]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::apdu::parse_generate_response(&[u8]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::apdu::parse_metadata_algorithm(&[u8]) -> core::result::Result<u8, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::apdu::parse_metadata_public_key(&[u8]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::apdu::parse_serial_response(&[u8]) -> core::result::Result<u32, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::apdu::parse_sign_response(&[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::apdu::parse_version_response(&[u8]) -> core::result::Result<(u8, u8, u8), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::apdu::reset_piv() -> alloc::vec::Vec<u8>
pub fn rns_ratkey::apdu::reset_retry(&str, &str) -> alloc::vec::Vec<u8>
pub fn rns_ratkey::apdu::select_piv() -> alloc::vec::Vec<u8>
pub fn rns_ratkey::apdu::sign_ed25519(u8, &[u8]) -> alloc::vec::Vec<u8>
pub fn rns_ratkey::apdu::slot_to_object_id(u8) -> core::option::Option<&'static [u8]>
pub fn rns_ratkey::apdu::verify_pin(&str) -> alloc::vec::Vec<u8>
pub mod rns_ratkey::attestation
pub struct rns_ratkey::attestation::AttestationInfo
pub rns_ratkey::attestation::AttestationInfo::attestation_cert_der: alloc::vec::Vec<u8>
pub rns_ratkey::attestation::AttestationInfo::device_cert_der: alloc::vec::Vec<u8>
pub rns_ratkey::attestation::AttestationInfo::firmware_version: core::option::Option<(u8, u8, u8)>
pub rns_ratkey::attestation::AttestationInfo::form_factor: core::option::Option<u8>
pub rns_ratkey::attestation::AttestationInfo::pin_policy: core::option::Option<u8>
pub rns_ratkey::attestation::AttestationInfo::serial_number: core::option::Option<u32>
pub rns_ratkey::attestation::AttestationInfo::touch_policy: core::option::Option<u8>
pub struct rns_ratkey::attestation::AttestationVerification
pub rns_ratkey::attestation::AttestationVerification::chain_verified: bool
pub rns_ratkey::attestation::AttestationVerification::description: alloc::string::String
pub rns_ratkey::attestation::AttestationVerification::info: rns_ratkey::attestation::AttestationInfo
pub rns_ratkey::attestation::AttestationVerification::metadata_extracted: bool
pub rns_ratkey::attestation::AttestationVerification::root_ca: alloc::string::String
pub rns_ratkey::attestation::AttestationVerification::verified: bool
pub const rns_ratkey::attestation::OID_FIRMWARE_VERSION: &[u8]
pub const rns_ratkey::attestation::OID_FORM_FACTOR: &[u8]
pub const rns_ratkey::attestation::OID_SERIAL_NUMBER: &[u8]
pub const rns_ratkey::attestation::OID_USAGE_POLICY: &[u8]
pub const rns_ratkey::attestation::YUBICO_ATTESTATION_ROOT_1_PEM: &str
pub const rns_ratkey::attestation::YUBICO_LEGACY_ROOT_SHA256: &str
pub const rns_ratkey::attestation::YUBICO_NEW_ROOT_SHA256: &str
pub const rns_ratkey::attestation::YUBICO_PIV_ROOT_CA_LEGACY_PEM: &str
pub fn rns_ratkey::attestation::pem_to_der(&str) -> core::option::Option<alloc::vec::Vec<u8>>
pub fn rns_ratkey::attestation::supports_attestation(&str) -> bool
pub fn rns_ratkey::attestation::verify_attestation(&[u8], &[u8]) -> core::result::Result<rns_ratkey::attestation::AttestationVerification, rns_ratkey::error::RatkeyError>
pub mod rns_ratkey::backend
pub struct rns_ratkey::backend::HardwareBackend
impl rns_identity::identity::LocalKeyBackend for rns_ratkey::backend::HardwareBackend
pub fn rns_ratkey::backend::HardwareBackend::ecdh(&self, &[u8; 32]) -> core::option::Option<[u8; 32]>
pub fn rns_ratkey::backend::HardwareBackend::lock(&self)
pub fn rns_ratkey::backend::HardwareBackend::sign_ed25519(&self, &[u8]) -> core::option::Option<[u8; 64]>
pub fn rns_ratkey::backend::load_hardware_identity(&rns_ratkey::hwid::HwidConfig, &str) -> core::result::Result<rns_identity::identity::Identity, rns_ratkey::error::RatkeyError>
pub mod rns_ratkey::detect
pub enum rns_ratkey::detect::DeviceType
pub rns_ratkey::detect::DeviceType::Nitrokey3
pub rns_ratkey::detect::DeviceType::Unknown
pub rns_ratkey::detect::DeviceType::YubiKey5
impl rns_ratkey::detect::DeviceType
pub fn rns_ratkey::detect::DeviceType::as_str(&self) -> &'static str
pub struct rns_ratkey::detect::DeviceInfo
pub rns_ratkey::detect::DeviceInfo::device_type: alloc::string::String
pub rns_ratkey::detect::DeviceInfo::firmware: core::option::Option<alloc::string::String>
pub rns_ratkey::detect::DeviceInfo::has_encryption_key: bool
pub rns_ratkey::detect::DeviceInfo::has_signing_key: bool
pub rns_ratkey::detect::DeviceInfo::reader_name: alloc::string::String
pub rns_ratkey::detect::DeviceInfo::serial: core::option::Option<u32>
pub fn rns_ratkey::detect::detect_device_type(&str) -> rns_ratkey::detect::DeviceType
pub fn rns_ratkey::detect::detect_devices() -> core::result::Result<alloc::vec::Vec<rns_ratkey::detect::DeviceInfo>, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::detect::list_readers() -> core::result::Result<alloc::vec::Vec<alloc::string::String>, rns_ratkey::error::RatkeyError>
pub mod rns_ratkey::error
pub enum rns_ratkey::error::RatkeyError
pub rns_ratkey::error::RatkeyError::Apdu
pub rns_ratkey::error::RatkeyError::Apdu::sw1: u8
pub rns_ratkey::error::RatkeyError::Apdu::sw2: u8
pub rns_ratkey::error::RatkeyError::Disconnected
pub rns_ratkey::error::RatkeyError::EcdhFailed(alloc::string::String)
pub rns_ratkey::error::RatkeyError::EmptySlot
pub rns_ratkey::error::RatkeyError::EmptySlot::slot: u8
pub rns_ratkey::error::RatkeyError::FirmwareVersion
pub rns_ratkey::error::RatkeyError::FirmwareVersion::found: alloc::string::String
pub rns_ratkey::error::RatkeyError::FirmwareVersion::required: alloc::string::String
pub rns_ratkey::error::RatkeyError::InvalidHwid(alloc::string::String)
pub rns_ratkey::error::RatkeyError::Io(core::io::error::Error)
pub rns_ratkey::error::RatkeyError::KeyMismatch
pub rns_ratkey::error::RatkeyError::ManagementAuthFailed
pub rns_ratkey::error::RatkeyError::NoDevice
pub rns_ratkey::error::RatkeyError::Pcsc(pcsc::Error)
pub rns_ratkey::error::RatkeyError::PinFailed
pub rns_ratkey::error::RatkeyError::PinFailed::remaining: u8
pub rns_ratkey::error::RatkeyError::PinLocked
pub rns_ratkey::error::RatkeyError::PinRequired
pub rns_ratkey::error::RatkeyError::PukFailed
pub rns_ratkey::error::RatkeyError::PukFailed::remaining: u8
pub rns_ratkey::error::RatkeyError::PukLocked
pub rns_ratkey::error::RatkeyError::ResetRequiresBlockedPinAndPuk
pub rns_ratkey::error::RatkeyError::SigningFailed(alloc::string::String)
pub rns_ratkey::error::RatkeyError::SlotOccupied
pub rns_ratkey::error::RatkeyError::SlotOccupied::slot: u8
pub rns_ratkey::error::RatkeyError::TouchRequired
pub rns_ratkey::error::RatkeyError::UnsupportedDevice(alloc::string::String)
pub mod rns_ratkey::hardware
pub struct rns_ratkey::hardware::HardwareIdentity
pub rns_ratkey::hardware::HardwareIdentity::config: rns_ratkey::hwid::HwidConfig
pub rns_ratkey::hardware::HardwareIdentity::identity: rns_identity::identity::Identity
impl rns_ratkey::hardware::HardwareIdentity
pub fn rns_ratkey::hardware::HardwareIdentity::as_identity(&self) -> &rns_identity::identity::Identity
pub fn rns_ratkey::hardware::HardwareIdentity::decrypt(&mut self, &[u8], core::option::Option<&[&[u8; 32]]>, bool) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hardware::HardwareIdentity::ecdh(&mut self, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hardware::HardwareIdentity::ed25519_public(&self) -> &[u8; 32]
pub fn rns_ratkey::hardware::HardwareIdentity::from_file(&std::path::Path, alloc::boxed::Box<dyn rns_ratkey::hardware::IdentityBackend>) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hardware::HardwareIdentity::from_hwid(rns_ratkey::hwid::HwidConfig, alloc::boxed::Box<dyn rns_ratkey::hardware::IdentityBackend>) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hardware::HardwareIdentity::from_keys([u8; 32], [u8; 32], alloc::boxed::Box<dyn rns_ratkey::hardware::IdentityBackend>) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hardware::HardwareIdentity::get_public_key(&self) -> [u8; 64]
pub fn rns_ratkey::hardware::HardwareIdentity::hash(&self) -> &[u8; 16]
pub fn rns_ratkey::hardware::HardwareIdentity::hash_hex(&self) -> alloc::string::String
pub fn rns_ratkey::hardware::HardwareIdentity::is_connected(&self) -> bool
pub fn rns_ratkey::hardware::HardwareIdentity::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hardware::HardwareIdentity::sign(&mut self, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hardware::HardwareIdentity::verify(&self, &[u8], &[u8; 64]) -> bool
pub fn rns_ratkey::hardware::HardwareIdentity::x25519_public(&self) -> &[u8; 32]
pub trait rns_ratkey::hardware::IdentityBackend
pub fn rns_ratkey::hardware::IdentityBackend::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hardware::IdentityBackend::is_connected(&self) -> bool
pub fn rns_ratkey::hardware::IdentityBackend::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hardware::IdentityBackend::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hardware::IdentityBackend::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hardware::IdentityBackend::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
impl rns_ratkey::hardware::IdentityBackend for rns_ratkey::mock::MockPivSession
pub fn rns_ratkey::mock::MockPivSession::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::is_connected(&self) -> bool
pub fn rns_ratkey::mock::MockPivSession::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
impl<T: rns_ratkey::transport::PivTransport> rns_ratkey::hardware::IdentityBackend for rns_ratkey::session::PivSession<T>
pub fn rns_ratkey::session::PivSession<T>::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::is_connected(&self) -> bool
pub fn rns_ratkey::session::PivSession<T>::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
pub mod rns_ratkey::hwid
pub struct rns_ratkey::hwid::HwidApp
pub rns_ratkey::hwid::HwidApp::app_hash: alloc::string::String
pub struct rns_ratkey::hwid::HwidAttestation
pub rns_ratkey::hwid::HwidAttestation::ed25519_cert: alloc::string::String
pub rns_ratkey::hwid::HwidAttestation::verified: bool
pub rns_ratkey::hwid::HwidAttestation::x25519_cert: alloc::string::String
pub struct rns_ratkey::hwid::HwidBackup
pub rns_ratkey::hwid::HwidBackup::backup_serial: core::option::Option<u32>
pub rns_ratkey::hwid::HwidBackup::encrypted_backup_hash: core::option::Option<alloc::string::String>
pub rns_ratkey::hwid::HwidBackup::tier: u8
pub struct rns_ratkey::hwid::HwidConfig
pub rns_ratkey::hwid::HwidConfig::app: rns_ratkey::hwid::HwidApp
pub rns_ratkey::hwid::HwidConfig::attestation: rns_ratkey::hwid::HwidAttestation
pub rns_ratkey::hwid::HwidConfig::backup: rns_ratkey::hwid::HwidBackup
pub rns_ratkey::hwid::HwidConfig::device: rns_ratkey::hwid::HwidDevice
pub rns_ratkey::hwid::HwidConfig::identity: rns_ratkey::hwid::HwidIdentity
pub rns_ratkey::hwid::HwidConfig::keys: rns_ratkey::hwid::HwidKeys
pub rns_ratkey::hwid::HwidConfig::policy: rns_ratkey::hwid::HwidPolicy
pub rns_ratkey::hwid::HwidConfig::slots: rns_ratkey::hwid::HwidSlots
impl rns_ratkey::hwid::HwidConfig
pub fn rns_ratkey::hwid::HwidConfig::ed25519_pub_bytes(&self) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hwid::HwidConfig::encryption_slot(&self) -> core::result::Result<u8, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hwid::HwidConfig::from_file(&std::path::Path) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hwid::HwidConfig::signing_slot(&self) -> core::result::Result<u8, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hwid::HwidConfig::to_file(&self, &std::path::Path) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hwid::HwidConfig::to_string(&self) -> core::result::Result<alloc::string::String, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hwid::HwidConfig::x25519_pub_bytes(&self) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
impl core::str::traits::FromStr for rns_ratkey::hwid::HwidConfig
pub type rns_ratkey::hwid::HwidConfig::Err = rns_ratkey::error::RatkeyError
pub fn rns_ratkey::hwid::HwidConfig::from_str(&str) -> core::result::Result<Self, Self::Err>
pub struct rns_ratkey::hwid::HwidDevice
pub rns_ratkey::hwid::HwidDevice::device_type: alloc::string::String
pub rns_ratkey::hwid::HwidDevice::firmware: alloc::string::String
pub rns_ratkey::hwid::HwidDevice::serial: u32
pub struct rns_ratkey::hwid::HwidIdentity
pub rns_ratkey::hwid::HwidIdentity::created_at: u64
pub rns_ratkey::hwid::HwidIdentity::hash: alloc::string::String
pub rns_ratkey::hwid::HwidIdentity::nickname: alloc::string::String
pub struct rns_ratkey::hwid::HwidKeys
pub rns_ratkey::hwid::HwidKeys::ed25519_pub: alloc::string::String
pub rns_ratkey::hwid::HwidKeys::x25519_pub: alloc::string::String
pub struct rns_ratkey::hwid::HwidPolicy
pub rns_ratkey::hwid::HwidPolicy::pin_cache_timeout: u64
pub rns_ratkey::hwid::HwidPolicy::touch_encryption: alloc::string::String
pub rns_ratkey::hwid::HwidPolicy::touch_signing: alloc::string::String
pub struct rns_ratkey::hwid::HwidSlots
pub rns_ratkey::hwid::HwidSlots::encryption: alloc::string::String
pub rns_ratkey::hwid::HwidSlots::signing: alloc::string::String
pub mod rns_ratkey::mgmt
pub fn rns_ratkey::mgmt::block_len(u8) -> core::option::Option<usize>
pub fn rns_ratkey::mgmt::ecb_decrypt(u8, &[u8], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mgmt::ecb_encrypt(u8, &[u8], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mgmt::key_len(u8) -> core::option::Option<usize>
pub mod rns_ratkey::mock
pub enum rns_ratkey::mock::MockOperation
pub rns_ratkey::mock::MockOperation::EcdhX25519
pub rns_ratkey::mock::MockOperation::EcdhX25519::slot: u8
pub rns_ratkey::mock::MockOperation::GenerateEd25519
pub rns_ratkey::mock::MockOperation::GenerateEd25519::slot: u8
pub rns_ratkey::mock::MockOperation::GenerateX25519
pub rns_ratkey::mock::MockOperation::GenerateX25519::slot: u8
pub rns_ratkey::mock::MockOperation::PinUnblock
pub rns_ratkey::mock::MockOperation::PinUnblock::success: bool
pub rns_ratkey::mock::MockOperation::PinVerify
pub rns_ratkey::mock::MockOperation::PinVerify::success: bool
pub rns_ratkey::mock::MockOperation::ReadPublicKey
pub rns_ratkey::mock::MockOperation::ReadPublicKey::slot: u8
pub rns_ratkey::mock::MockOperation::ResetPiv
pub rns_ratkey::mock::MockOperation::ResetPiv::success: bool
pub rns_ratkey::mock::MockOperation::SignEd25519
pub rns_ratkey::mock::MockOperation::SignEd25519::data_len: usize
pub rns_ratkey::mock::MockOperation::SignEd25519::slot: u8
pub enum rns_ratkey::mock::TouchPolicy
pub rns_ratkey::mock::TouchPolicy::Always
pub rns_ratkey::mock::TouchPolicy::Cached
pub rns_ratkey::mock::TouchPolicy::Never
pub struct rns_ratkey::mock::MockPivSession
pub rns_ratkey::mock::MockPivSession::device_type: alloc::string::String
pub rns_ratkey::mock::MockPivSession::firmware: alloc::string::String
pub rns_ratkey::mock::MockPivSession::operations: alloc::vec::Vec<rns_ratkey::mock::MockOperation>
pub rns_ratkey::mock::MockPivSession::serial: u32
impl rns_ratkey::mock::MockPivSession
pub fn rns_ratkey::mock::MockPivSession::disconnect(&mut self)
pub fn rns_ratkey::mock::MockPivSession::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::generate_ed25519(&mut self, u8, rns_ratkey::mock::TouchPolicy) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::generate_x25519(&mut self, u8, rns_ratkey::mock::TouchPolicy) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::is_connected(&self) -> bool
pub fn rns_ratkey::mock::MockPivSession::lock(&mut self)
pub fn rns_ratkey::mock::MockPivSession::new() -> Self
pub fn rns_ratkey::mock::MockPivSession::read_ed25519_public(&self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::read_x25519_public(&self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::reconnect(&mut self)
pub fn rns_ratkey::mock::MockPivSession::require_touch(&mut self)
pub fn rns_ratkey::mock::MockPivSession::reset_piv(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::set_pin(&mut self, &str)
pub fn rns_ratkey::mock::MockPivSession::set_puk(&mut self, &str)
pub fn rns_ratkey::mock::MockPivSession::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::simulate_touch(&mut self)
pub fn rns_ratkey::mock::MockPivSession::unblock_pin(&mut self, &str, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::verify_pin(&mut self, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::with_key_bytes(&[u8; 32], &[u8; 32]) -> Self
pub fn rns_ratkey::mock::MockPivSession::with_keys() -> Self
impl core::default::Default for rns_ratkey::mock::MockPivSession
pub fn rns_ratkey::mock::MockPivSession::default() -> Self
impl core::ops::drop::Drop for rns_ratkey::mock::MockPivSession
pub fn rns_ratkey::mock::MockPivSession::drop(&mut self)
impl rns_ratkey::hardware::IdentityBackend for rns_ratkey::mock::MockPivSession
pub fn rns_ratkey::mock::MockPivSession::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::is_connected(&self) -> bool
pub fn rns_ratkey::mock::MockPivSession::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
pub const rns_ratkey::mock::SLOT_9A: u8
pub const rns_ratkey::mock::SLOT_9D: u8
pub mod rns_ratkey::pin
pub struct rns_ratkey::pin::PinCache
impl rns_ratkey::pin::PinCache
pub fn rns_ratkey::pin::PinCache::cache(&mut self, &str)
pub fn rns_ratkey::pin::PinCache::clear(&mut self)
pub fn rns_ratkey::pin::PinCache::default_timeout() -> Self
pub fn rns_ratkey::pin::PinCache::get(&self) -> core::option::Option<&str>
pub fn rns_ratkey::pin::PinCache::is_cached(&self) -> bool
pub fn rns_ratkey::pin::PinCache::new(core::time::Duration) -> Self
pub fn rns_ratkey::pin::PinCache::remaining(&self) -> core::option::Option<core::time::Duration>
impl core::ops::drop::Drop for rns_ratkey::pin::PinCache
pub fn rns_ratkey::pin::PinCache::drop(&mut self)
pub mod rns_ratkey::provision
pub struct rns_ratkey::provision::ProvisionConfig
pub rns_ratkey::provision::ProvisionConfig::identities_dir: core::option::Option<std::path::PathBuf>
pub rns_ratkey::provision::ProvisionConfig::nickname: alloc::string::String
pub rns_ratkey::provision::ProvisionConfig::pin: alloc::string::String
pub rns_ratkey::provision::ProvisionConfig::touch_encryption: rns_ratkey::mock::TouchPolicy
pub rns_ratkey::provision::ProvisionConfig::touch_signing: rns_ratkey::mock::TouchPolicy
impl core::default::Default for rns_ratkey::provision::ProvisionConfig
pub fn rns_ratkey::provision::ProvisionConfig::default() -> Self
pub struct rns_ratkey::provision::ProvisionResult
pub rns_ratkey::provision::ProvisionResult::config: rns_ratkey::hwid::HwidConfig
pub rns_ratkey::provision::ProvisionResult::ed25519_pub: [u8; 32]
pub rns_ratkey::provision::ProvisionResult::hwid_path: core::option::Option<std::path::PathBuf>
pub rns_ratkey::provision::ProvisionResult::identity_hash: [u8; 16]
pub rns_ratkey::provision::ProvisionResult::identity_hash_hex: alloc::string::String
pub rns_ratkey::provision::ProvisionResult::x25519_pub: [u8; 32]
pub fn rns_ratkey::provision::compute_identity_hash(&[u8; 32], &[u8; 32]) -> [u8; 16]
pub fn rns_ratkey::provision::import_recoverable_identity<T: rns_ratkey::transport::PivTransport>(&mut rns_ratkey::session::PivSession<T>, &[u8], &rns_ratkey::provision::ProvisionConfig, &str) -> core::result::Result<rns_ratkey::provision::ProvisionResult, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::provision::provision_hardware_only<T: rns_ratkey::transport::PivTransport>(&mut rns_ratkey::session::PivSession<T>, &[u8], &rns_ratkey::provision::ProvisionConfig) -> core::result::Result<rns_ratkey::provision::ProvisionResult, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::provision::provision_mock(&mut rns_ratkey::mock::MockPivSession, &rns_ratkey::provision::ProvisionConfig) -> core::result::Result<rns_ratkey::provision::ProvisionResult, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::provision::provision_recoverable<T: rns_ratkey::transport::PivTransport>(&mut rns_ratkey::session::PivSession<T>, &[u8], &rns_ratkey::provision::ProvisionConfig) -> core::result::Result<(rns_ratkey::provision::ProvisionResult, alloc::string::String), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::provision::read_existing<T: rns_ratkey::transport::PivTransport>(&mut rns_ratkey::session::PivSession<T>, &rns_ratkey::provision::ProvisionConfig) -> core::result::Result<rns_ratkey::provision::ProvisionResult, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::provision::restore<T: rns_ratkey::transport::PivTransport>(&mut rns_ratkey::session::PivSession<T>, &[u8], &rns_ratkey::provision::ProvisionConfig, &str) -> core::result::Result<rns_ratkey::provision::ProvisionResult, rns_ratkey::error::RatkeyError>
pub mod rns_ratkey::seed
pub struct rns_ratkey::seed::DerivedIdentity
pub rns_ratkey::seed::DerivedIdentity::ed25519_pub: [u8; 32]
pub rns_ratkey::seed::DerivedIdentity::ed25519_seed: [u8; 32]
pub rns_ratkey::seed::DerivedIdentity::x25519_pub: [u8; 32]
pub rns_ratkey::seed::DerivedIdentity::x25519_secret: [u8; 32]
impl core::ops::drop::Drop for rns_ratkey::seed::DerivedIdentity
pub fn rns_ratkey::seed::DerivedIdentity::drop(&mut self)
pub fn rns_ratkey::seed::derive_identity(&str) -> core::result::Result<rns_ratkey::seed::DerivedIdentity, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::seed::generate_mnemonic() -> core::result::Result<alloc::string::String, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::seed::validate_mnemonic(&str) -> bool
pub mod rns_ratkey::session
pub struct rns_ratkey::session::DeviceMeta
pub rns_ratkey::session::DeviceMeta::device_type: rns_ratkey::detect::DeviceType
pub rns_ratkey::session::DeviceMeta::firmware: core::option::Option<alloc::string::String>
pub rns_ratkey::session::DeviceMeta::serial: core::option::Option<u32>
pub struct rns_ratkey::session::PivSession<T: rns_ratkey::transport::PivTransport>
impl rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>
pub fn rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>::connect() -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>::connect_reader(&str) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
impl<T: rns_ratkey::transport::PivTransport> rns_ratkey::session::PivSession<T>
pub fn rns_ratkey::session::PivSession<T>::attest_key(&mut self, u8) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::authenticate_management_key(&mut self, &[u8]) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::change_pin(&mut self, &str, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::device_type(&self) -> rns_ratkey::detect::DeviceType
pub fn rns_ratkey::session::PivSession<T>::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::firmware(&self) -> core::option::Option<&str>
pub fn rns_ratkey::session::PivSession<T>::generate_ed25519(&mut self, u8, core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::generate_x25519(&mut self, u8, core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::import_ed25519(&mut self, u8, &[u8; 32], core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::import_x25519(&mut self, u8, &[u8; 32], core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::is_connected(&self) -> bool
pub fn rns_ratkey::session::PivSession<T>::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::new(T, rns_ratkey::session::DeviceMeta) -> Self
pub fn rns_ratkey::session::PivSession<T>::read_attestation_cert(&mut self) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::read_certificate(&mut self, u8) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::read_metadata(&mut self, u8) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::read_public_key(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::reset_piv(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::serial(&self) -> core::option::Option<u32>
pub fn rns_ratkey::session::PivSession<T>::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::unblock_pin(&mut self, &str, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::verify_pin(&mut self, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
impl<T: rns_ratkey::transport::PivTransport> rns_ratkey::hardware::IdentityBackend for rns_ratkey::session::PivSession<T>
pub fn rns_ratkey::session::PivSession<T>::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::is_connected(&self) -> bool
pub fn rns_ratkey::session::PivSession<T>::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
pub type rns_ratkey::session::PcscPivSession = rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>
pub mod rns_ratkey::transport
pub struct rns_ratkey::transport::PcscTransport
impl rns_ratkey::PcscTransport
pub fn rns_ratkey::PcscTransport::connect() -> core::result::Result<(Self, rns_ratkey::session::DeviceMeta), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::PcscTransport::connect_reader(&str) -> core::result::Result<(Self, rns_ratkey::session::DeviceMeta), rns_ratkey::error::RatkeyError>
impl rns_ratkey::transport::PivTransport for rns_ratkey::PcscTransport
pub fn rns_ratkey::PcscTransport::is_connected(&self) -> bool
pub fn rns_ratkey::PcscTransport::transmit(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
pub trait rns_ratkey::transport::PivTransport
pub fn rns_ratkey::transport::PivTransport::is_connected(&self) -> bool
pub fn rns_ratkey::transport::PivTransport::transmit(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
impl rns_ratkey::transport::PivTransport for rns_ratkey::PcscTransport
pub fn rns_ratkey::PcscTransport::is_connected(&self) -> bool
pub fn rns_ratkey::PcscTransport::transmit(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
pub enum rns_ratkey::RatkeyError
pub rns_ratkey::RatkeyError::Apdu
pub rns_ratkey::RatkeyError::Apdu::sw1: u8
pub rns_ratkey::RatkeyError::Apdu::sw2: u8
pub rns_ratkey::RatkeyError::Disconnected
pub rns_ratkey::RatkeyError::EcdhFailed(alloc::string::String)
pub rns_ratkey::RatkeyError::EmptySlot
pub rns_ratkey::RatkeyError::EmptySlot::slot: u8
pub rns_ratkey::RatkeyError::FirmwareVersion
pub rns_ratkey::RatkeyError::FirmwareVersion::found: alloc::string::String
pub rns_ratkey::RatkeyError::FirmwareVersion::required: alloc::string::String
pub rns_ratkey::RatkeyError::InvalidHwid(alloc::string::String)
pub rns_ratkey::RatkeyError::Io(core::io::error::Error)
pub rns_ratkey::RatkeyError::KeyMismatch
pub rns_ratkey::RatkeyError::ManagementAuthFailed
pub rns_ratkey::RatkeyError::NoDevice
pub rns_ratkey::RatkeyError::Pcsc(pcsc::Error)
pub rns_ratkey::RatkeyError::PinFailed
pub rns_ratkey::RatkeyError::PinFailed::remaining: u8
pub rns_ratkey::RatkeyError::PinLocked
pub rns_ratkey::RatkeyError::PinRequired
pub rns_ratkey::RatkeyError::PukFailed
pub rns_ratkey::RatkeyError::PukFailed::remaining: u8
pub rns_ratkey::RatkeyError::PukLocked
pub rns_ratkey::RatkeyError::ResetRequiresBlockedPinAndPuk
pub rns_ratkey::RatkeyError::SigningFailed(alloc::string::String)
pub rns_ratkey::RatkeyError::SlotOccupied
pub rns_ratkey::RatkeyError::SlotOccupied::slot: u8
pub rns_ratkey::RatkeyError::TouchRequired
pub rns_ratkey::RatkeyError::UnsupportedDevice(alloc::string::String)
pub struct rns_ratkey::DeviceMeta
pub rns_ratkey::DeviceMeta::device_type: rns_ratkey::detect::DeviceType
pub rns_ratkey::DeviceMeta::firmware: core::option::Option<alloc::string::String>
pub rns_ratkey::DeviceMeta::serial: core::option::Option<u32>
pub struct rns_ratkey::HardwareBackend
impl rns_identity::identity::LocalKeyBackend for rns_ratkey::backend::HardwareBackend
pub fn rns_ratkey::backend::HardwareBackend::ecdh(&self, &[u8; 32]) -> core::option::Option<[u8; 32]>
pub fn rns_ratkey::backend::HardwareBackend::lock(&self)
pub fn rns_ratkey::backend::HardwareBackend::sign_ed25519(&self, &[u8]) -> core::option::Option<[u8; 64]>
pub struct rns_ratkey::HardwareIdentity
pub rns_ratkey::HardwareIdentity::config: rns_ratkey::hwid::HwidConfig
pub rns_ratkey::HardwareIdentity::identity: rns_identity::identity::Identity
impl rns_ratkey::hardware::HardwareIdentity
pub fn rns_ratkey::hardware::HardwareIdentity::as_identity(&self) -> &rns_identity::identity::Identity
pub fn rns_ratkey::hardware::HardwareIdentity::decrypt(&mut self, &[u8], core::option::Option<&[&[u8; 32]]>, bool) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hardware::HardwareIdentity::ecdh(&mut self, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hardware::HardwareIdentity::ed25519_public(&self) -> &[u8; 32]
pub fn rns_ratkey::hardware::HardwareIdentity::from_file(&std::path::Path, alloc::boxed::Box<dyn rns_ratkey::hardware::IdentityBackend>) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hardware::HardwareIdentity::from_hwid(rns_ratkey::hwid::HwidConfig, alloc::boxed::Box<dyn rns_ratkey::hardware::IdentityBackend>) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hardware::HardwareIdentity::from_keys([u8; 32], [u8; 32], alloc::boxed::Box<dyn rns_ratkey::hardware::IdentityBackend>) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hardware::HardwareIdentity::get_public_key(&self) -> [u8; 64]
pub fn rns_ratkey::hardware::HardwareIdentity::hash(&self) -> &[u8; 16]
pub fn rns_ratkey::hardware::HardwareIdentity::hash_hex(&self) -> alloc::string::String
pub fn rns_ratkey::hardware::HardwareIdentity::is_connected(&self) -> bool
pub fn rns_ratkey::hardware::HardwareIdentity::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hardware::HardwareIdentity::sign(&mut self, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hardware::HardwareIdentity::verify(&self, &[u8], &[u8; 64]) -> bool
pub fn rns_ratkey::hardware::HardwareIdentity::x25519_public(&self) -> &[u8; 32]
pub struct rns_ratkey::HwidConfig
pub rns_ratkey::HwidConfig::app: rns_ratkey::hwid::HwidApp
pub rns_ratkey::HwidConfig::attestation: rns_ratkey::hwid::HwidAttestation
pub rns_ratkey::HwidConfig::backup: rns_ratkey::hwid::HwidBackup
pub rns_ratkey::HwidConfig::device: rns_ratkey::hwid::HwidDevice
pub rns_ratkey::HwidConfig::identity: rns_ratkey::hwid::HwidIdentity
pub rns_ratkey::HwidConfig::keys: rns_ratkey::hwid::HwidKeys
pub rns_ratkey::HwidConfig::policy: rns_ratkey::hwid::HwidPolicy
pub rns_ratkey::HwidConfig::slots: rns_ratkey::hwid::HwidSlots
impl rns_ratkey::hwid::HwidConfig
pub fn rns_ratkey::hwid::HwidConfig::ed25519_pub_bytes(&self) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hwid::HwidConfig::encryption_slot(&self) -> core::result::Result<u8, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hwid::HwidConfig::from_file(&std::path::Path) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hwid::HwidConfig::signing_slot(&self) -> core::result::Result<u8, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hwid::HwidConfig::to_file(&self, &std::path::Path) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hwid::HwidConfig::to_string(&self) -> core::result::Result<alloc::string::String, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::hwid::HwidConfig::x25519_pub_bytes(&self) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
impl core::str::traits::FromStr for rns_ratkey::hwid::HwidConfig
pub type rns_ratkey::hwid::HwidConfig::Err = rns_ratkey::error::RatkeyError
pub fn rns_ratkey::hwid::HwidConfig::from_str(&str) -> core::result::Result<Self, Self::Err>
pub struct rns_ratkey::MockPivSession
pub rns_ratkey::MockPivSession::device_type: alloc::string::String
pub rns_ratkey::MockPivSession::firmware: alloc::string::String
pub rns_ratkey::MockPivSession::operations: alloc::vec::Vec<rns_ratkey::mock::MockOperation>
pub rns_ratkey::MockPivSession::serial: u32
impl rns_ratkey::mock::MockPivSession
pub fn rns_ratkey::mock::MockPivSession::disconnect(&mut self)
pub fn rns_ratkey::mock::MockPivSession::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::generate_ed25519(&mut self, u8, rns_ratkey::mock::TouchPolicy) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::generate_x25519(&mut self, u8, rns_ratkey::mock::TouchPolicy) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::is_connected(&self) -> bool
pub fn rns_ratkey::mock::MockPivSession::lock(&mut self)
pub fn rns_ratkey::mock::MockPivSession::new() -> Self
pub fn rns_ratkey::mock::MockPivSession::read_ed25519_public(&self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::read_x25519_public(&self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::reconnect(&mut self)
pub fn rns_ratkey::mock::MockPivSession::require_touch(&mut self)
pub fn rns_ratkey::mock::MockPivSession::reset_piv(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::set_pin(&mut self, &str)
pub fn rns_ratkey::mock::MockPivSession::set_puk(&mut self, &str)
pub fn rns_ratkey::mock::MockPivSession::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::simulate_touch(&mut self)
pub fn rns_ratkey::mock::MockPivSession::unblock_pin(&mut self, &str, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::verify_pin(&mut self, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::with_key_bytes(&[u8; 32], &[u8; 32]) -> Self
pub fn rns_ratkey::mock::MockPivSession::with_keys() -> Self
impl core::default::Default for rns_ratkey::mock::MockPivSession
pub fn rns_ratkey::mock::MockPivSession::default() -> Self
impl core::ops::drop::Drop for rns_ratkey::mock::MockPivSession
pub fn rns_ratkey::mock::MockPivSession::drop(&mut self)
impl rns_ratkey::hardware::IdentityBackend for rns_ratkey::mock::MockPivSession
pub fn rns_ratkey::mock::MockPivSession::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::is_connected(&self) -> bool
pub fn rns_ratkey::mock::MockPivSession::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
pub struct rns_ratkey::PcscTransport
impl rns_ratkey::PcscTransport
pub fn rns_ratkey::PcscTransport::connect() -> core::result::Result<(Self, rns_ratkey::session::DeviceMeta), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::PcscTransport::connect_reader(&str) -> core::result::Result<(Self, rns_ratkey::session::DeviceMeta), rns_ratkey::error::RatkeyError>
impl rns_ratkey::transport::PivTransport for rns_ratkey::PcscTransport
pub fn rns_ratkey::PcscTransport::is_connected(&self) -> bool
pub fn rns_ratkey::PcscTransport::transmit(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
pub struct rns_ratkey::PinCache
impl rns_ratkey::pin::PinCache
pub fn rns_ratkey::pin::PinCache::cache(&mut self, &str)
pub fn rns_ratkey::pin::PinCache::clear(&mut self)
pub fn rns_ratkey::pin::PinCache::default_timeout() -> Self
pub fn rns_ratkey::pin::PinCache::get(&self) -> core::option::Option<&str>
pub fn rns_ratkey::pin::PinCache::is_cached(&self) -> bool
pub fn rns_ratkey::pin::PinCache::new(core::time::Duration) -> Self
pub fn rns_ratkey::pin::PinCache::remaining(&self) -> core::option::Option<core::time::Duration>
impl core::ops::drop::Drop for rns_ratkey::pin::PinCache
pub fn rns_ratkey::pin::PinCache::drop(&mut self)
pub struct rns_ratkey::PivSession<T: rns_ratkey::transport::PivTransport>
impl rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>
pub fn rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>::connect() -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>::connect_reader(&str) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
impl<T: rns_ratkey::transport::PivTransport> rns_ratkey::session::PivSession<T>
pub fn rns_ratkey::session::PivSession<T>::attest_key(&mut self, u8) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::authenticate_management_key(&mut self, &[u8]) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::change_pin(&mut self, &str, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::device_type(&self) -> rns_ratkey::detect::DeviceType
pub fn rns_ratkey::session::PivSession<T>::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::firmware(&self) -> core::option::Option<&str>
pub fn rns_ratkey::session::PivSession<T>::generate_ed25519(&mut self, u8, core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::generate_x25519(&mut self, u8, core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::import_ed25519(&mut self, u8, &[u8; 32], core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::import_x25519(&mut self, u8, &[u8; 32], core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::is_connected(&self) -> bool
pub fn rns_ratkey::session::PivSession<T>::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::new(T, rns_ratkey::session::DeviceMeta) -> Self
pub fn rns_ratkey::session::PivSession<T>::read_attestation_cert(&mut self) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::read_certificate(&mut self, u8) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::read_metadata(&mut self, u8) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::read_public_key(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::reset_piv(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::serial(&self) -> core::option::Option<u32>
pub fn rns_ratkey::session::PivSession<T>::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::unblock_pin(&mut self, &str, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::verify_pin(&mut self, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
impl<T: rns_ratkey::transport::PivTransport> rns_ratkey::hardware::IdentityBackend for rns_ratkey::session::PivSession<T>
pub fn rns_ratkey::session::PivSession<T>::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::is_connected(&self) -> bool
pub fn rns_ratkey::session::PivSession<T>::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
pub struct rns_ratkey::ProvisionConfig
pub rns_ratkey::ProvisionConfig::identities_dir: core::option::Option<std::path::PathBuf>
pub rns_ratkey::ProvisionConfig::nickname: alloc::string::String
pub rns_ratkey::ProvisionConfig::pin: alloc::string::String
pub rns_ratkey::ProvisionConfig::touch_encryption: rns_ratkey::mock::TouchPolicy
pub rns_ratkey::ProvisionConfig::touch_signing: rns_ratkey::mock::TouchPolicy
impl core::default::Default for rns_ratkey::provision::ProvisionConfig
pub fn rns_ratkey::provision::ProvisionConfig::default() -> Self
pub struct rns_ratkey::ProvisionResult
pub rns_ratkey::ProvisionResult::config: rns_ratkey::hwid::HwidConfig
pub rns_ratkey::ProvisionResult::ed25519_pub: [u8; 32]
pub rns_ratkey::ProvisionResult::hwid_path: core::option::Option<std::path::PathBuf>
pub rns_ratkey::ProvisionResult::identity_hash: [u8; 16]
pub rns_ratkey::ProvisionResult::identity_hash_hex: alloc::string::String
pub rns_ratkey::ProvisionResult::x25519_pub: [u8; 32]
pub trait rns_ratkey::IdentityBackend
pub fn rns_ratkey::IdentityBackend::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::IdentityBackend::is_connected(&self) -> bool
pub fn rns_ratkey::IdentityBackend::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::IdentityBackend::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::IdentityBackend::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::IdentityBackend::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
impl rns_ratkey::hardware::IdentityBackend for rns_ratkey::mock::MockPivSession
pub fn rns_ratkey::mock::MockPivSession::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::is_connected(&self) -> bool
pub fn rns_ratkey::mock::MockPivSession::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::mock::MockPivSession::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
impl<T: rns_ratkey::transport::PivTransport> rns_ratkey::hardware::IdentityBackend for rns_ratkey::session::PivSession<T>
pub fn rns_ratkey::session::PivSession<T>::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::is_connected(&self) -> bool
pub fn rns_ratkey::session::PivSession<T>::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::session::PivSession<T>::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
pub trait rns_ratkey::PivTransport
pub fn rns_ratkey::PivTransport::is_connected(&self) -> bool
pub fn rns_ratkey::PivTransport::transmit(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
impl rns_ratkey::transport::PivTransport for rns_ratkey::PcscTransport
pub fn rns_ratkey::PcscTransport::is_connected(&self) -> bool
pub fn rns_ratkey::PcscTransport::transmit(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
pub fn rns_ratkey::load_hardware_identity(&rns_ratkey::hwid::HwidConfig, &str) -> core::result::Result<rns_identity::identity::Identity, rns_ratkey::error::RatkeyError>
pub type rns_ratkey::PcscPivSession = rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>
File diff suppressed because it is too large. Load diff
+15
View File
@@ -0,0 +1,15 @@
pub mod rns_tools
pub mod rns_tools::format
pub fn rns_tools::format::hex_rep(&[u8]) -> alloc::string::String
pub fn rns_tools::format::pretty_frequency(f64) -> alloc::string::String
pub fn rns_tools::format::pretty_hex_rep(&[u8]) -> alloc::string::String
pub fn rns_tools::format::pretty_size(u64) -> alloc::string::String
pub fn rns_tools::format::pretty_speed(u64) -> alloc::string::String
pub fn rns_tools::format::pretty_time(f64) -> alloc::string::String
pub mod rns_tools::hash
pub fn rns_tools::hash::format_dest_hash(&[u8; 16]) -> alloc::string::String
pub fn rns_tools::hash::parse_dest_hash(&str) -> core::result::Result<[u8; 16], alloc::string::String>
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 fn rns_tools::init_tracing<W>(tracing_core::metadata::Level, bool, bool, W) where W: for<'a> tracing_subscriber::fmt::writer::MakeWriter<'a> + core::marker::Send + core::marker::Sync + 'static
File diff suppressed because it is too large. Load diff
+402
View File
@@ -0,0 +1,402 @@
pub mod rns_wire
pub mod rns_wire::constants
pub const rns_wire::constants::AES128_BLOCKSIZE: usize
pub const rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT: f64
pub const rns_wire::constants::ENCRYPTED_MDU: usize
pub const rns_wire::constants::EXPL_LENGTH: usize
pub const rns_wire::constants::HASHLENGTH: usize
pub const rns_wire::constants::HEADER_MAXSIZE: usize
pub const rns_wire::constants::HEADER_MINSIZE: usize
pub const rns_wire::constants::IMPL_LENGTH: usize
pub const rns_wire::constants::KEYSIZE: usize
pub const rns_wire::constants::LINK_MDU: usize
pub const rns_wire::constants::MDU: usize
pub const rns_wire::constants::MTU: usize
pub const rns_wire::constants::NAME_HASH_LENGTH: usize
pub const rns_wire::constants::PLAIN_MDU: usize
pub const rns_wire::constants::RATCHETSIZE: usize
pub const rns_wire::constants::RATCHET_COUNT: usize
pub const rns_wire::constants::RATCHET_EXPIRY: u64
pub const rns_wire::constants::RATCHET_INTERVAL: u64
pub const rns_wire::constants::SIGLENGTH: usize
pub const rns_wire::constants::SINGLE_PACKET_ENCRYPTED_MDU: usize
pub const rns_wire::constants::TOKEN_OVERHEAD: usize
pub const rns_wire::constants::TRUNCATED_HASHLENGTH: usize
pub mod rns_wire::context
pub enum rns_wire::context::PacketContext
pub rns_wire::context::PacketContext::CacheRequest
pub rns_wire::context::PacketContext::Channel
pub rns_wire::context::PacketContext::Command
pub rns_wire::context::PacketContext::CommandStatus
pub rns_wire::context::PacketContext::Keepalive
pub rns_wire::context::PacketContext::LinkClose
pub rns_wire::context::PacketContext::LinkIdentify
pub rns_wire::context::PacketContext::LinkProof
pub rns_wire::context::PacketContext::Lrproof
pub rns_wire::context::PacketContext::Lrrtt
pub rns_wire::context::PacketContext::None
pub rns_wire::context::PacketContext::PathResponse
pub rns_wire::context::PacketContext::Request
pub rns_wire::context::PacketContext::Resource
pub rns_wire::context::PacketContext::ResourceAdv
pub rns_wire::context::PacketContext::ResourceHmu
pub rns_wire::context::PacketContext::ResourceIcl
pub rns_wire::context::PacketContext::ResourcePrf
pub rns_wire::context::PacketContext::ResourceRcl
pub rns_wire::context::PacketContext::ResourceReq
pub rns_wire::context::PacketContext::Response
pub rns_wire::context::PacketContext::Unknown(u8)
impl rns_wire::context::PacketContext
pub fn rns_wire::context::PacketContext::from_byte(u8) -> Self
pub fn rns_wire::context::PacketContext::is_plaintext_context(self) -> bool
pub fn rns_wire::context::PacketContext::to_byte(self) -> u8
pub mod rns_wire::flags
#[repr(u8)] pub enum rns_wire::flags::DestinationType
pub rns_wire::flags::DestinationType::Group = 1
pub rns_wire::flags::DestinationType::Link = 3
pub rns_wire::flags::DestinationType::Plain = 2
pub rns_wire::flags::DestinationType::Single = 0
#[repr(u8)] pub enum rns_wire::flags::HeaderType
pub rns_wire::flags::HeaderType::Header1 = 0
pub rns_wire::flags::HeaderType::Header2 = 1
#[repr(u8)] pub enum rns_wire::flags::PacketType
pub rns_wire::flags::PacketType::Announce = 1
pub rns_wire::flags::PacketType::Data = 0
pub rns_wire::flags::PacketType::LinkRequest = 2
pub rns_wire::flags::PacketType::Proof = 3
#[repr(u8)] pub enum rns_wire::flags::TransportType
pub rns_wire::flags::TransportType::Broadcast = 0
pub rns_wire::flags::TransportType::Transport = 1
pub struct rns_wire::flags::PacketFlags
pub rns_wire::flags::PacketFlags::context_flag: bool
pub rns_wire::flags::PacketFlags::destination_type: rns_wire::flags::DestinationType
pub rns_wire::flags::PacketFlags::header_type: rns_wire::flags::HeaderType
pub rns_wire::flags::PacketFlags::packet_type: rns_wire::flags::PacketType
pub rns_wire::flags::PacketFlags::transport_type: rns_wire::flags::TransportType
impl rns_wire::flags::PacketFlags
pub fn rns_wire::flags::PacketFlags::pack(&self) -> u8
pub fn rns_wire::flags::PacketFlags::unpack(u8) -> core::option::Option<Self>
pub mod rns_wire::hash
pub fn rns_wire::hash::get_hashable_part(&[u8], rns_wire::flags::HeaderType) -> alloc::vec::Vec<u8>
pub fn rns_wire::hash::link_id_from_raw(&[u8], rns_wire::flags::HeaderType) -> [u8; 16]
pub fn rns_wire::hash::packet_hash(&[u8], rns_wire::flags::HeaderType) -> [u8; 32]
pub fn rns_wire::hash::packet_hash_pair(&[u8], rns_wire::flags::HeaderType) -> ([u8; 32], [u8; 16])
pub fn rns_wire::hash::truncated_packet_hash(&[u8], rns_wire::flags::HeaderType) -> [u8; 16]
pub mod rns_wire::header
pub enum rns_wire::header::HeaderError
pub rns_wire::header::HeaderError::TooShort(usize)
pub struct rns_wire::header::PacketHeader
pub rns_wire::header::PacketHeader::context: rns_wire::context::PacketContext
pub rns_wire::header::PacketHeader::destination_hash: [u8; 16]
pub rns_wire::header::PacketHeader::flags: rns_wire::flags::PacketFlags
pub rns_wire::header::PacketHeader::hops: u8
pub rns_wire::header::PacketHeader::transport_id: core::option::Option<[u8; 16]>
impl rns_wire::header::PacketHeader
pub fn rns_wire::header::PacketHeader::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_wire::header::PacketHeader::size(&self) -> usize
pub fn rns_wire::header::PacketHeader::unpack(&[u8]) -> core::result::Result<(Self, usize), rns_wire::header::HeaderError>
pub mod rns_wire::link_signalling
pub enum rns_wire::link_signalling::LinkSignallingError
pub rns_wire::link_signalling::LinkSignallingError::InvalidLength
pub rns_wire::link_signalling::LinkSignallingError::InvalidLength::actual: usize
pub rns_wire::link_signalling::LinkSignallingError::InvalidLength::legacy: usize
pub rns_wire::link_signalling::LinkSignallingError::InvalidLength::modern: usize
pub rns_wire::link_signalling::LinkSignallingError::InvalidMode(u8)
pub rns_wire::link_signalling::LinkSignallingError::InvalidMtu(u32)
pub rns_wire::link_signalling::LinkSignallingError::MduUnavailable
pub struct rns_wire::link_signalling::LinkMtu(_)
impl rns_wire::link_signalling::LinkMtu
pub const rns_wire::link_signalling::LinkMtu::BASE: Self
pub fn rns_wire::link_signalling::LinkMtu::checked_mdu(self) -> core::result::Result<usize, rns_wire::link_signalling::LinkSignallingError>
pub const fn rns_wire::link_signalling::LinkMtu::get(self) -> u32
pub fn rns_wire::link_signalling::LinkMtu::try_from_signal(core::option::Option<u32>) -> core::result::Result<Self, rns_wire::link_signalling::LinkSignallingError>
pub struct rns_wire::link_signalling::LinkSignalling
pub rns_wire::link_signalling::LinkSignalling::mode: u8
pub rns_wire::link_signalling::LinkSignalling::mtu: rns_wire::link_signalling::LinkMtu
pub rns_wire::link_signalling::LinkSignalling::signalling_present: bool
pub struct rns_wire::link_signalling::SignallingData
pub rns_wire::link_signalling::SignallingData::mode: u8
pub rns_wire::link_signalling::SignallingData::mtu: u32
impl rns_wire::link_signalling::SignallingData
pub fn rns_wire::link_signalling::SignallingData::new(u8, u32) -> Self
pub fn rns_wire::link_signalling::SignallingData::pack(&self) -> [u8; 3]
pub fn rns_wire::link_signalling::SignallingData::try_new(u8, u32) -> core::result::Result<Self, rns_wire::link_signalling::LinkSignallingError>
pub fn rns_wire::link_signalling::SignallingData::unpack(&[u8]) -> core::option::Option<Self>
pub const rns_wire::link_signalling::BASE_LINK_MTU: u32
pub const rns_wire::link_signalling::DEFAULT_LINK_MODE: u8
pub const rns_wire::link_signalling::MAX_SIGNALLED_LINK_MTU: u32
pub fn rns_wire::link_signalling::parse_proof_signalling(&[u8]) -> core::result::Result<rns_wire::link_signalling::LinkSignalling, rns_wire::link_signalling::LinkSignallingError>
pub fn rns_wire::link_signalling::parse_request_signalling(&[u8]) -> core::result::Result<rns_wire::link_signalling::LinkSignalling, rns_wire::link_signalling::LinkSignallingError>
pub mod rns_wire::packet
pub enum rns_wire::packet::PacketError
pub rns_wire::packet::PacketError::ExceedsMtu(usize)
pub rns_wire::packet::PacketError::Header(rns_wire::header::HeaderError)
pub rns_wire::packet::PacketError::TooShort
pub struct rns_wire::packet::Packet
pub rns_wire::packet::Packet::header: rns_wire::header::PacketHeader
pub rns_wire::packet::Packet::packet_hash: [u8; 32]
pub rns_wire::packet::Packet::raw: alloc::vec::Vec<u8>
pub rns_wire::packet::Packet::truncated_hash: [u8; 16]
impl rns_wire::packet::Packet
pub fn rns_wire::packet::Packet::data(&self) -> &[u8]
pub fn rns_wire::packet::Packet::from_raw(&[u8]) -> core::result::Result<Self, rns_wire::packet::PacketError>
pub fn rns_wire::packet::Packet::from_raw_owned(alloc::vec::Vec<u8>) -> core::result::Result<Self, rns_wire::packet::PacketError>
pub fn rns_wire::packet::Packet::increment_hops(&mut self)
pub fn rns_wire::packet::Packet::new(rns_wire::header::PacketHeader, alloc::vec::Vec<u8>) -> core::result::Result<Self, rns_wire::packet::PacketError>
pub mod rns_wire::proof
pub enum rns_wire::proof::ProofData
pub rns_wire::proof::ProofData::Explicit
pub rns_wire::proof::ProofData::Explicit::packet_hash: [u8; 32]
pub rns_wire::proof::ProofData::Explicit::signature: [u8; 64]
pub rns_wire::proof::ProofData::Implicit
pub rns_wire::proof::ProofData::Implicit::signature: [u8; 64]
impl rns_wire::proof::ProofData
pub fn rns_wire::proof::ProofData::from_bytes(&[u8]) -> core::option::Option<Self>
pub fn rns_wire::proof::ProofData::signature(&self) -> &[u8; 64]
pub fn rns_wire::proof::ProofData::to_bytes(&self) -> alloc::vec::Vec<u8>
pub mod rns_wire::receipt
#[repr(u8)] pub enum rns_wire::receipt::ReceiptStatus
pub rns_wire::receipt::ReceiptStatus::Culled = 255
pub rns_wire::receipt::ReceiptStatus::Delivered = 2
pub rns_wire::receipt::ReceiptStatus::Failed = 0
pub rns_wire::receipt::ReceiptStatus::Receiving = 6
pub rns_wire::receipt::ReceiptStatus::Sent = 1
pub struct rns_wire::receipt::PacketReceipt
pub rns_wire::receipt::PacketReceipt::callbacks: rns_wire::receipt::ReceiptCallbacks
pub rns_wire::receipt::PacketReceipt::concluded_at: core::option::Option<std::time::Instant>
pub rns_wire::receipt::PacketReceipt::destination_hash: core::option::Option<[u8; 16]>
pub rns_wire::receipt::PacketReceipt::destination_public_key: core::option::Option<[u8; 64]>
pub rns_wire::receipt::PacketReceipt::hash: [u8; 32]
pub rns_wire::receipt::PacketReceipt::sent_at: std::time::Instant
pub rns_wire::receipt::PacketReceipt::status: rns_wire::receipt::ReceiptStatus
pub rns_wire::receipt::PacketReceipt::timeout: core::option::Option<core::time::Duration>
pub rns_wire::receipt::PacketReceipt::truncated_hash: [u8; 16]
impl rns_wire::receipt::PacketReceipt
pub fn rns_wire::receipt::PacketReceipt::check_timeout(&mut self) -> bool
pub fn rns_wire::receipt::PacketReceipt::cull(&mut self)
pub fn rns_wire::receipt::PacketReceipt::deliver(&mut self)
pub fn rns_wire::receipt::PacketReceipt::fail(&mut self)
pub fn rns_wire::receipt::PacketReceipt::get_rtt(&self) -> core::option::Option<core::time::Duration>
pub fn rns_wire::receipt::PacketReceipt::is_timed_out(&self) -> bool
pub fn rns_wire::receipt::PacketReceipt::new([u8; 32], [u8; 16], core::option::Option<core::time::Duration>) -> Self
pub fn rns_wire::receipt::PacketReceipt::set_delivery_callback(&mut self, impl core::ops::function::FnOnce(&rns_wire::receipt::PacketReceipt) + core::marker::Send + 'static)
pub fn rns_wire::receipt::PacketReceipt::set_destination_identity(&mut self, [u8; 16], core::option::Option<[u8; 64]>)
pub fn rns_wire::receipt::PacketReceipt::set_timeout_callback(&mut self, impl core::ops::function::FnOnce(&rns_wire::receipt::PacketReceipt) + core::marker::Send + 'static)
pub fn rns_wire::receipt::PacketReceipt::validate_proof<F>(&mut self, &[u8], F) -> bool where F: core::ops::function::FnOnce(&[u8], &[u8]) -> bool
pub fn rns_wire::receipt::PacketReceipt::validate_proof_from_destination(&mut self, &[u8]) -> bool
pub struct rns_wire::receipt::ReceiptCallbacks
pub rns_wire::receipt::ReceiptCallbacks::delivery: core::option::Option<rns_wire::receipt::ReceiptCallback>
pub rns_wire::receipt::ReceiptCallbacks::timeout: core::option::Option<rns_wire::receipt::ReceiptCallback>
pub const rns_wire::receipt::EXPL_LENGTH: usize
pub const rns_wire::receipt::IMPL_LENGTH: usize
pub fn rns_wire::receipt::receipt_timeout_for_route(core::time::Duration, u8) -> core::time::Duration
pub type rns_wire::receipt::ReceiptCallback = alloc::boxed::Box<(dyn core::ops::function::FnOnce(&rns_wire::receipt::PacketReceipt) + core::marker::Send)>
pub mod rns_wire::types
#[repr(transparent)] pub struct rns_wire::types::DestHash(_)
impl rns_wire::types::DestHash
pub const rns_wire::types::DestHash::LEN: usize
pub const fn rns_wire::types::DestHash::as_bytes(&self) -> &[u8; 16]
pub fn rns_wire::types::DestHash::from_slice(&[u8]) -> core::option::Option<Self>
pub const fn rns_wire::types::DestHash::into_bytes(self) -> [u8; 16]
pub const fn rns_wire::types::DestHash::new([u8; 16]) -> Self
impl core::borrow::Borrow<[u8; 16]> for rns_wire::types::DestHash
pub fn rns_wire::types::DestHash::borrow(&self) -> &[u8; 16]
impl core::convert::AsRef<[u8; 16]> for rns_wire::types::DestHash
pub fn rns_wire::types::DestHash::as_ref(&self) -> &[u8; 16]
impl core::convert::AsRef<[u8]> for rns_wire::types::DestHash
pub fn rns_wire::types::DestHash::as_ref(&self) -> &[u8]
impl core::convert::From<&[u8; 16]> for rns_wire::types::DestHash
pub fn rns_wire::types::DestHash::from(&[u8; 16]) -> Self
impl core::convert::From<[u8; 16]> for rns_wire::types::DestHash
pub fn rns_wire::types::DestHash::from([u8; 16]) -> Self
impl core::convert::From<rns_wire::types::DestHash> for [u8; 16]
pub fn [u8; 16]::from(rns_wire::types::DestHash) -> [u8; 16]
impl core::fmt::Debug for rns_wire::types::DestHash
pub fn rns_wire::types::DestHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl core::fmt::Display for rns_wire::types::DestHash
pub fn rns_wire::types::DestHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl core::ops::deref::Deref for rns_wire::types::DestHash
pub type rns_wire::types::DestHash::Target = [u8; 16]
pub fn rns_wire::types::DestHash::deref(&self) -> &[u8; 16]
#[repr(transparent)] pub struct rns_wire::types::FullHash(_)
impl rns_wire::types::FullHash
pub const rns_wire::types::FullHash::LEN: usize
pub const fn rns_wire::types::FullHash::as_bytes(&self) -> &[u8; 32]
pub fn rns_wire::types::FullHash::from_slice(&[u8]) -> core::option::Option<Self>
pub const fn rns_wire::types::FullHash::into_bytes(self) -> [u8; 32]
pub const fn rns_wire::types::FullHash::new([u8; 32]) -> Self
impl core::borrow::Borrow<[u8; 32]> for rns_wire::types::FullHash
pub fn rns_wire::types::FullHash::borrow(&self) -> &[u8; 32]
impl core::convert::AsRef<[u8; 32]> for rns_wire::types::FullHash
pub fn rns_wire::types::FullHash::as_ref(&self) -> &[u8; 32]
impl core::convert::AsRef<[u8]> for rns_wire::types::FullHash
pub fn rns_wire::types::FullHash::as_ref(&self) -> &[u8]
impl core::convert::From<&[u8; 32]> for rns_wire::types::FullHash
pub fn rns_wire::types::FullHash::from(&[u8; 32]) -> Self
impl core::convert::From<[u8; 32]> for rns_wire::types::FullHash
pub fn rns_wire::types::FullHash::from([u8; 32]) -> Self
impl core::convert::From<rns_wire::types::FullHash> for [u8; 32]
pub fn [u8; 32]::from(rns_wire::types::FullHash) -> [u8; 32]
impl core::fmt::Debug for rns_wire::types::FullHash
pub fn rns_wire::types::FullHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl core::fmt::Display for rns_wire::types::FullHash
pub fn rns_wire::types::FullHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl core::ops::deref::Deref for rns_wire::types::FullHash
pub type rns_wire::types::FullHash::Target = [u8; 32]
pub fn rns_wire::types::FullHash::deref(&self) -> &[u8; 32]
#[repr(transparent)] pub struct rns_wire::types::IdentityHash(_)
impl rns_wire::types::IdentityHash
pub const rns_wire::types::IdentityHash::LEN: usize
pub const fn rns_wire::types::IdentityHash::as_bytes(&self) -> &[u8; 16]
pub fn rns_wire::types::IdentityHash::from_slice(&[u8]) -> core::option::Option<Self>
pub const fn rns_wire::types::IdentityHash::into_bytes(self) -> [u8; 16]
pub const fn rns_wire::types::IdentityHash::new([u8; 16]) -> Self
impl core::borrow::Borrow<[u8; 16]> for rns_wire::types::IdentityHash
pub fn rns_wire::types::IdentityHash::borrow(&self) -> &[u8; 16]
impl core::convert::AsRef<[u8; 16]> for rns_wire::types::IdentityHash
pub fn rns_wire::types::IdentityHash::as_ref(&self) -> &[u8; 16]
impl core::convert::AsRef<[u8]> for rns_wire::types::IdentityHash
pub fn rns_wire::types::IdentityHash::as_ref(&self) -> &[u8]
impl core::convert::From<&[u8; 16]> for rns_wire::types::IdentityHash
pub fn rns_wire::types::IdentityHash::from(&[u8; 16]) -> Self
impl core::convert::From<[u8; 16]> for rns_wire::types::IdentityHash
pub fn rns_wire::types::IdentityHash::from([u8; 16]) -> Self
impl core::convert::From<rns_wire::types::IdentityHash> for [u8; 16]
pub fn [u8; 16]::from(rns_wire::types::IdentityHash) -> [u8; 16]
impl core::fmt::Debug for rns_wire::types::IdentityHash
pub fn rns_wire::types::IdentityHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl core::fmt::Display for rns_wire::types::IdentityHash
pub fn rns_wire::types::IdentityHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl core::ops::deref::Deref for rns_wire::types::IdentityHash
pub type rns_wire::types::IdentityHash::Target = [u8; 16]
pub fn rns_wire::types::IdentityHash::deref(&self) -> &[u8; 16]
#[repr(transparent)] pub struct rns_wire::types::LinkId(_)
impl rns_wire::types::LinkId
pub const rns_wire::types::LinkId::LEN: usize
pub const fn rns_wire::types::LinkId::as_bytes(&self) -> &[u8; 16]
pub fn rns_wire::types::LinkId::from_slice(&[u8]) -> core::option::Option<Self>
pub const fn rns_wire::types::LinkId::into_bytes(self) -> [u8; 16]
pub const fn rns_wire::types::LinkId::new([u8; 16]) -> Self
impl core::borrow::Borrow<[u8; 16]> for rns_wire::types::LinkId
pub fn rns_wire::types::LinkId::borrow(&self) -> &[u8; 16]
impl core::convert::AsRef<[u8; 16]> for rns_wire::types::LinkId
pub fn rns_wire::types::LinkId::as_ref(&self) -> &[u8; 16]
impl core::convert::AsRef<[u8]> for rns_wire::types::LinkId
pub fn rns_wire::types::LinkId::as_ref(&self) -> &[u8]
impl core::convert::From<&[u8; 16]> for rns_wire::types::LinkId
pub fn rns_wire::types::LinkId::from(&[u8; 16]) -> Self
impl core::convert::From<[u8; 16]> for rns_wire::types::LinkId
pub fn rns_wire::types::LinkId::from([u8; 16]) -> Self
impl core::convert::From<rns_wire::types::LinkId> for [u8; 16]
pub fn [u8; 16]::from(rns_wire::types::LinkId) -> [u8; 16]
impl core::fmt::Debug for rns_wire::types::LinkId
pub fn rns_wire::types::LinkId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl core::fmt::Display for rns_wire::types::LinkId
pub fn rns_wire::types::LinkId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl core::ops::deref::Deref for rns_wire::types::LinkId
pub type rns_wire::types::LinkId::Target = [u8; 16]
pub fn rns_wire::types::LinkId::deref(&self) -> &[u8; 16]
#[repr(transparent)] pub struct rns_wire::types::MessageHash(_)
impl rns_wire::types::MessageHash
pub const rns_wire::types::MessageHash::LEN: usize
pub const fn rns_wire::types::MessageHash::as_bytes(&self) -> &[u8; 32]
pub fn rns_wire::types::MessageHash::from_slice(&[u8]) -> core::option::Option<Self>
pub const fn rns_wire::types::MessageHash::into_bytes(self) -> [u8; 32]
pub const fn rns_wire::types::MessageHash::new([u8; 32]) -> Self
impl core::borrow::Borrow<[u8; 32]> for rns_wire::types::MessageHash
pub fn rns_wire::types::MessageHash::borrow(&self) -> &[u8; 32]
impl core::convert::AsRef<[u8; 32]> for rns_wire::types::MessageHash
pub fn rns_wire::types::MessageHash::as_ref(&self) -> &[u8; 32]
impl core::convert::AsRef<[u8]> for rns_wire::types::MessageHash
pub fn rns_wire::types::MessageHash::as_ref(&self) -> &[u8]
impl core::convert::From<&[u8; 32]> for rns_wire::types::MessageHash
pub fn rns_wire::types::MessageHash::from(&[u8; 32]) -> Self
impl core::convert::From<[u8; 32]> for rns_wire::types::MessageHash
pub fn rns_wire::types::MessageHash::from([u8; 32]) -> Self
impl core::convert::From<rns_wire::types::MessageHash> for [u8; 32]
pub fn [u8; 32]::from(rns_wire::types::MessageHash) -> [u8; 32]
impl core::fmt::Debug for rns_wire::types::MessageHash
pub fn rns_wire::types::MessageHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl core::fmt::Display for rns_wire::types::MessageHash
pub fn rns_wire::types::MessageHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl core::ops::deref::Deref for rns_wire::types::MessageHash
pub type rns_wire::types::MessageHash::Target = [u8; 32]
pub fn rns_wire::types::MessageHash::deref(&self) -> &[u8; 32]
#[repr(transparent)] pub struct rns_wire::types::NameHash(_)
impl rns_wire::types::NameHash
pub const rns_wire::types::NameHash::LEN: usize
pub const fn rns_wire::types::NameHash::as_bytes(&self) -> &[u8; 10]
pub fn rns_wire::types::NameHash::from_slice(&[u8]) -> core::option::Option<Self>
pub const fn rns_wire::types::NameHash::into_bytes(self) -> [u8; 10]
pub const fn rns_wire::types::NameHash::new([u8; 10]) -> Self
impl core::borrow::Borrow<[u8; 10]> for rns_wire::types::NameHash
pub fn rns_wire::types::NameHash::borrow(&self) -> &[u8; 10]
impl core::convert::AsRef<[u8; 10]> for rns_wire::types::NameHash
pub fn rns_wire::types::NameHash::as_ref(&self) -> &[u8; 10]
impl core::convert::AsRef<[u8]> for rns_wire::types::NameHash
pub fn rns_wire::types::NameHash::as_ref(&self) -> &[u8]
impl core::convert::From<&[u8; 10]> for rns_wire::types::NameHash
pub fn rns_wire::types::NameHash::from(&[u8; 10]) -> Self
impl core::convert::From<[u8; 10]> for rns_wire::types::NameHash
pub fn rns_wire::types::NameHash::from([u8; 10]) -> Self
impl core::convert::From<rns_wire::types::NameHash> for [u8; 10]
pub fn [u8; 10]::from(rns_wire::types::NameHash) -> [u8; 10]
impl core::fmt::Debug for rns_wire::types::NameHash
pub fn rns_wire::types::NameHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl core::fmt::Display for rns_wire::types::NameHash
pub fn rns_wire::types::NameHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl core::ops::deref::Deref for rns_wire::types::NameHash
pub type rns_wire::types::NameHash::Target = [u8; 10]
pub fn rns_wire::types::NameHash::deref(&self) -> &[u8; 10]
#[repr(transparent)] pub struct rns_wire::types::TransportId(_)
impl rns_wire::types::TransportId
pub const rns_wire::types::TransportId::LEN: usize
pub const fn rns_wire::types::TransportId::as_bytes(&self) -> &[u8; 16]
pub fn rns_wire::types::TransportId::from_slice(&[u8]) -> core::option::Option<Self>
pub const fn rns_wire::types::TransportId::into_bytes(self) -> [u8; 16]
pub const fn rns_wire::types::TransportId::new([u8; 16]) -> Self
impl core::borrow::Borrow<[u8; 16]> for rns_wire::types::TransportId
pub fn rns_wire::types::TransportId::borrow(&self) -> &[u8; 16]
impl core::convert::AsRef<[u8; 16]> for rns_wire::types::TransportId
pub fn rns_wire::types::TransportId::as_ref(&self) -> &[u8; 16]
impl core::convert::AsRef<[u8]> for rns_wire::types::TransportId
pub fn rns_wire::types::TransportId::as_ref(&self) -> &[u8]
impl core::convert::From<&[u8; 16]> for rns_wire::types::TransportId
pub fn rns_wire::types::TransportId::from(&[u8; 16]) -> Self
impl core::convert::From<[u8; 16]> for rns_wire::types::TransportId
pub fn rns_wire::types::TransportId::from([u8; 16]) -> Self
impl core::convert::From<rns_wire::types::TransportId> for [u8; 16]
pub fn [u8; 16]::from(rns_wire::types::TransportId) -> [u8; 16]
impl core::fmt::Debug for rns_wire::types::TransportId
pub fn rns_wire::types::TransportId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl core::fmt::Display for rns_wire::types::TransportId
pub fn rns_wire::types::TransportId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl core::ops::deref::Deref for rns_wire::types::TransportId
pub type rns_wire::types::TransportId::Target = [u8; 16]
pub fn rns_wire::types::TransportId::deref(&self) -> &[u8; 16]
#[repr(transparent)] pub struct rns_wire::types::TruncatedHash(_)
impl rns_wire::types::TruncatedHash
pub const rns_wire::types::TruncatedHash::LEN: usize
pub const fn rns_wire::types::TruncatedHash::as_bytes(&self) -> &[u8; 16]
pub fn rns_wire::types::TruncatedHash::from_slice(&[u8]) -> core::option::Option<Self>
pub const fn rns_wire::types::TruncatedHash::into_bytes(self) -> [u8; 16]
pub const fn rns_wire::types::TruncatedHash::new([u8; 16]) -> Self
impl core::borrow::Borrow<[u8; 16]> for rns_wire::types::TruncatedHash
pub fn rns_wire::types::TruncatedHash::borrow(&self) -> &[u8; 16]
impl core::convert::AsRef<[u8; 16]> for rns_wire::types::TruncatedHash
pub fn rns_wire::types::TruncatedHash::as_ref(&self) -> &[u8; 16]
impl core::convert::AsRef<[u8]> for rns_wire::types::TruncatedHash
pub fn rns_wire::types::TruncatedHash::as_ref(&self) -> &[u8]
impl core::convert::From<&[u8; 16]> for rns_wire::types::TruncatedHash
pub fn rns_wire::types::TruncatedHash::from(&[u8; 16]) -> Self
impl core::convert::From<[u8; 16]> for rns_wire::types::TruncatedHash
pub fn rns_wire::types::TruncatedHash::from([u8; 16]) -> Self
impl core::convert::From<rns_wire::types::TruncatedHash> for [u8; 16]
pub fn [u8; 16]::from(rns_wire::types::TruncatedHash) -> [u8; 16]
impl core::fmt::Debug for rns_wire::types::TruncatedHash
pub fn rns_wire::types::TruncatedHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl core::fmt::Display for rns_wire::types::TruncatedHash
pub fn rns_wire::types::TruncatedHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl core::ops::deref::Deref for rns_wire::types::TruncatedHash
pub type rns_wire::types::TruncatedHash::Target = [u8; 16]
pub fn rns_wire::types::TruncatedHash::deref(&self) -> &[u8; 16]
+218
View File
@@ -0,0 +1,218 @@
{
"schemaVersion": 2,
"tool": {
"name": "cargo-public-api",
"version": "0.52.0",
"rustdocToolchain": "nightly-2026-08-01",
"target": "aarch64-apple-darwin",
"arguments": [
"--all-features",
"-sss"
]
},
"baseline": {
"commit": "47dbbf1febc0a9d3259f179a0512d9b56bb2320d"
},
"compatibilityFloor": {
"evidenceCommit": "c9b210a52b139ac9754b46c5c2639c4113e7ae53",
"sourceCommit": "47dbbf1febc0a9d3259f179a0512d9b56bb2320d"
},
"packages": [
{
"name": "rns-crypto",
"manifestPath": "Cargo.toml",
"tier": "provisional",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-crypto.txt",
"itemCount": 92,
"sha256": "1f4539cfe1dfc1bf78a75e95dc98a3bf14a432cf0292d8d654fc043d5c4d21dc"
},
{
"name": "rns-wire",
"manifestPath": "Cargo.toml",
"tier": "provisional",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-wire.txt",
"itemCount": 402,
"sha256": "47f17ed4b47f0fc9ccaccc42d00b7635b07083c4eae6782a4f5de7e1452e4688"
},
{
"name": "rns-identity",
"manifestPath": "Cargo.toml",
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-identity.txt",
"itemCount": 431,
"sha256": "377cb3b72a97b071e0d590c399d0cc0433b60fe5a6ae37a73657283d3622f037"
},
{
"name": "rns-transport",
"manifestPath": "Cargo.toml",
"tier": "provisional",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-transport.txt",
"itemCount": 1947,
"sha256": "79cd60b1cde9c92e97f58ded693d3754b53311ec16f161ffa5b90775ec3c4a45"
},
{
"name": "rns-link",
"manifestPath": "Cargo.toml",
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-link.txt",
"itemCount": 384,
"sha256": "6c7db32623681ef8b2fdce0c54edbb992d307f0fae8b361c65109a6d262d9389"
},
{
"name": "rns-protocol",
"manifestPath": "Cargo.toml",
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-protocol.txt",
"itemCount": 638,
"sha256": "f90d8a7a284b50df43e3c9936f7b3a3a9c4104f4e31cc9ef1c60b833239b7ec6"
},
{
"name": "rns-interface",
"manifestPath": "Cargo.toml",
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-interface.txt",
"itemCount": 1441,
"sha256": "141d84e59832531aa63990634d6044f79ddb7ed9bdc41aaf2b95833f7b14e7cb"
},
{
"name": "rns-runtime",
"manifestPath": "Cargo.toml",
"tier": "provisional",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-runtime.txt",
"itemCount": 2145,
"sha256": "a4496892f8c4f6aeb9f840179e1a967b576679056045dd4511d5fe064f32544c"
},
{
"name": "rns-tools",
"manifestPath": "Cargo.toml",
"tier": "tool-internal",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-tools.txt",
"itemCount": 15,
"sha256": "662566afbf8a21928529a33dcec4a23b0a4686e9b2d94a7721b111738a5b4a6b"
},
{
"name": "rns-ratkey",
"manifestPath": "Cargo.toml",
"tier": "experimental",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-ratkey.txt",
"itemCount": 618,
"sha256": "f2ab796d37f18d7d5d7a515e4b6c28900f6f1c214aec4142fed069275793fdfd"
}
],
"approvedBreakingChanges": {
"releaseLine": "1.4",
"migrationGuide": "api/migrations/1.4.md",
"removed": {
"rns-crypto": [
"pub fn rns_crypto::hkdf::derive_key_64(&[u8], &[u8]) -> core::result::Result<[u8; 64], rns_crypto::hkdf::HkdfError>",
"pub fn rns_crypto::hkdf::hkdf_sha256(usize, &[u8], core::option::Option<&[u8]>, core::option::Option<&[u8]>) -> core::result::Result<alloc::vec::Vec<u8>, rns_crypto::hkdf::HkdfError>"
],
"rns-transport": [
"pub enum rns_transport::discovery::Reason",
"pub enum rns_transport::discovery::receiver::Reason",
"pub fn rns_transport::tunnel::handle_tunnel(&mut rns_transport::tunnel::TunnelTable, [u8; 32], rns_transport::messages::InterfaceId, f64)",
"pub rns_transport::actor::DiscoveryPathRequest::requesting_interface: rns_transport::messages::InterfaceId",
"pub rns_transport::actor::DiscoveryPathRequest::timeout: f64",
"pub rns_transport::actor::TransportActor::discovery_path_requests: std::collections::hash::map::HashMap<[u8; 16], rns_transport::actor::DiscoveryPathRequest>",
"pub rns_transport::actor::TransportActor::pending_tunnel_entries: alloc::vec::Vec<rns_transport::persistence::PersistedTunnelEntry>",
"pub rns_transport::discovery::DiscoveryInterfaceConfig::height: f64",
"pub rns_transport::discovery::DiscoveryInterfaceConfig::latitude: f64",
"pub rns_transport::discovery::DiscoveryInterfaceConfig::longitude: f64",
"pub rns_transport::discovery::announcer::DiscoveryInterfaceConfig::height: f64",
"pub rns_transport::discovery::announcer::DiscoveryInterfaceConfig::latitude: f64",
"pub rns_transport::discovery::announcer::DiscoveryInterfaceConfig::longitude: f64",
"pub rns_transport::discovery::app_data::DiscoveryInfo::height: f64",
"pub rns_transport::discovery::app_data::DiscoveryInfo::latitude: f64",
"pub rns_transport::discovery::app_data::DiscoveryInfo::longitude: f64",
"pub rns_transport::messages::InterfaceEntry::ifac_key: core::option::Option<[u8; 64]>",
"pub rns_transport::tunnel::TunnelEntry::interface_id: rns_transport::messages::InterfaceId"
],
"rns-link": [
"impl rns_link::mtu_discovery::SignallingData",
"pub fn rns_link::handshake::LinkProofData::create(&rns_crypto::ed25519::Ed25519PrivateKey, &[u8; 32], &[u8; 32], &[u8; 16], rns_link::mtu_discovery::SignallingData) -> Self",
"pub fn rns_link::handshake::LinkProofData::create_with<F>(F, &[u8; 32], &[u8; 32], &[u8; 16], rns_link::mtu_discovery::SignallingData) -> Self where F: core::ops::function::FnOnce(&[u8]) -> [u8; 64]",
"pub fn rns_link::handshake::LinkRequestData::pack(&rns_link::handshake::EphemeralKeys, rns_link::mtu_discovery::SignallingData) -> alloc::vec::Vec<u8>",
"pub fn rns_link::mtu_discovery::SignallingData::new(u8, u32) -> Self",
"pub fn rns_link::mtu_discovery::SignallingData::pack(&self) -> [u8; 3]",
"pub fn rns_link::mtu_discovery::SignallingData::unpack(&[u8]) -> core::option::Option<Self>",
"pub rns_link::handshake::LinkProofData::signalling: rns_link::mtu_discovery::SignallingData",
"pub rns_link::handshake::LinkRequestData::signalling: rns_link::mtu_discovery::SignallingData",
"pub rns_link::mtu_discovery::SignallingData::mode: u8",
"pub rns_link::mtu_discovery::SignallingData::mtu: u32",
"pub struct rns_link::mtu_discovery::SignallingData"
],
"rns-interface": [
"pub async fn rns_interface::i2p::spawn_i2p_server(rns_interface::i2p::I2PServerConfig, 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>",
"pub async fn rns_interface::local::spawn_local_server(rns_interface::local::LocalServerConfig, 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>",
"pub enum rns_interface::rnode::RNodeStream",
"pub rns_interface::rnode::RNodeStream::Serial(alloc::boxed::Box<dyn serialport::SerialPort>)",
"pub rns_interface::rnode::RNodeStream::Tcp(std::net::tcp::TcpStream)"
],
"rns-runtime": [
"pub fn rns_runtime::interface_factory::InterfacePostInit::from_section(&rns_runtime::config::ConfigSection) -> Self",
"pub fn rns_runtime::link_manager::LinkManager::set_link_packet_channel(&mut self, tokio::sync::mpsc::unbounded::UnboundedSender<(alloc::vec::Vec<u8>, [u8; 16])>)",
"pub mod rns_runtime::remote_management_schema",
"pub rns_runtime::interface_factory::InterfacePostInit::ifac_passphrase: core::option::Option<alloc::string::String>",
"pub rns_runtime::remote_management_schema::InterfaceStats::announce_queue: core::option::Option<u64>",
"pub rns_runtime::remote_management_schema::InterfaceStats::bitrate: core::option::Option<u64>",
"pub rns_runtime::remote_management_schema::InterfaceStats::blocked_ips: core::option::Option<u64>",
"pub rns_runtime::remote_management_schema::InterfaceStats::burst_activated: f64",
"pub rns_runtime::remote_management_schema::InterfaceStats::burst_active: bool",
"pub rns_runtime::remote_management_schema::InterfaceStats::clients: core::option::Option<u64>",
"pub rns_runtime::remote_management_schema::InterfaceStats::hash: core::option::Option<alloc::vec::Vec<u8>>",
"pub rns_runtime::remote_management_schema::InterfaceStats::held_announces: u64",
"pub rns_runtime::remote_management_schema::InterfaceStats::ifac_netname: core::option::Option<alloc::string::String>",
"pub rns_runtime::remote_management_schema::InterfaceStats::ifac_signature: core::option::Option<alloc::vec::Vec<u8>>",
"pub rns_runtime::remote_management_schema::InterfaceStats::ifac_size: core::option::Option<u64>",
"pub rns_runtime::remote_management_schema::InterfaceStats::incoming_announce_frequency: f64",
"pub rns_runtime::remote_management_schema::InterfaceStats::incoming_pr_frequency: f64",
"pub rns_runtime::remote_management_schema::InterfaceStats::mode: u8",
"pub rns_runtime::remote_management_schema::InterfaceStats::name: alloc::string::String",
"pub rns_runtime::remote_management_schema::InterfaceStats::outgoing_announce_frequency: f64",
"pub rns_runtime::remote_management_schema::InterfaceStats::outgoing_pr_frequency: f64",
"pub rns_runtime::remote_management_schema::InterfaceStats::pr_burst_activated: f64",
"pub rns_runtime::remote_management_schema::InterfaceStats::pr_burst_active: bool",
"pub rns_runtime::remote_management_schema::InterfaceStats::rxb: u64",
"pub rns_runtime::remote_management_schema::InterfaceStats::rxs: u64",
"pub rns_runtime::remote_management_schema::InterfaceStats::short_name: alloc::string::String",
"pub rns_runtime::remote_management_schema::InterfaceStats::status: bool",
"pub rns_runtime::remote_management_schema::InterfaceStats::txb: u64",
"pub rns_runtime::remote_management_schema::InterfaceStats::txs: u64",
"pub rns_runtime::remote_management_schema::InterfaceStats::type_: alloc::string::String",
"pub rns_runtime::remote_management_schema::PathEntry::expires: f64",
"pub rns_runtime::remote_management_schema::PathEntry::hash: alloc::vec::Vec<u8>",
"pub rns_runtime::remote_management_schema::PathEntry::hops: u8",
"pub rns_runtime::remote_management_schema::PathEntry::interface: alloc::string::String",
"pub rns_runtime::remote_management_schema::PathEntry::timestamp: f64",
"pub rns_runtime::remote_management_schema::PathEntry::via: core::option::Option<alloc::vec::Vec<u8>>",
"pub rns_runtime::remote_management_schema::RateEntry::hash: alloc::vec::Vec<u8>",
"pub rns_runtime::remote_management_schema::RateEntry::rate: f64",
"pub rns_runtime::remote_management_schema::TransportStats::interfaces: alloc::vec::Vec<rns_runtime::remote_management_schema::InterfaceStats>",
"pub rns_runtime::remote_management_schema::TransportStats::network_id: core::option::Option<alloc::vec::Vec<u8>>",
"pub rns_runtime::remote_management_schema::TransportStats::probe_responder: core::option::Option<alloc::vec::Vec<u8>>",
"pub rns_runtime::remote_management_schema::TransportStats::rss: core::option::Option<u64>",
"pub rns_runtime::remote_management_schema::TransportStats::rxb: u64",
"pub rns_runtime::remote_management_schema::TransportStats::rxs: u64",
"pub rns_runtime::remote_management_schema::TransportStats::transport_id: core::option::Option<alloc::vec::Vec<u8>>",
"pub rns_runtime::remote_management_schema::TransportStats::transport_uptime: core::option::Option<f64>",
"pub rns_runtime::remote_management_schema::TransportStats::txb: u64",
"pub rns_runtime::remote_management_schema::TransportStats::txs: u64",
"pub rns_runtime::rpc::InterfaceStatEntry::ifac_size: usize",
"pub struct rns_runtime::remote_management_schema::InterfaceStats",
"pub struct rns_runtime::remote_management_schema::PathEntry",
"pub struct rns_runtime::remote_management_schema::RateEntry",
"pub struct rns_runtime::remote_management_schema::TransportStats"
]
}
}
}
+1 -1
View File
@@ -1,2 +1,2 @@
# Keep Clippy suggestions aligned with the public MSRV in Cargo.toml.
msrv = "1.85"
msrv = "1.89"
+3 -1
View File
@@ -1,9 +1,11 @@
[package]
name = "rns-crypto"
description = "Cryptographic primitives for Reticulum"
publish = false
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
license-file.workspace = true
[features]
default = ["std"]
+22 -8
View File
@@ -1,20 +1,21 @@
//! AES-CBC, no padding (callers use [`crate::pkcs7`]). Key length selects:
//! 16 → AES-128, 32 → AES-256. Wire negotiates AES-256; AES-128 kept for
//! legacy Token material.
//! 16 → AES-128, 32 → AES-256. AES-128 supports legacy Token material.
//! These primitives do not negotiate a cipher or authenticate ciphertext;
//! [`crate::token`] supplies the authenticated Token format.
use aes::{Aes128, Aes256};
use alloc::vec::Vec;
use cbc::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
use cbc::{Decryptor, Encryptor};
use thiserror::Error;
use zeroize::Zeroizing;
const AES_BLOCK_SIZE: usize = 16;
/// Rust 1.85-compatible block alignment check. Newer Clippy suggests
/// `usize::is_multiple_of`, but that API is not available on our MSRV.
/// Block alignment check kept explicit at this cryptographic boundary.
#[inline]
pub(crate) fn is_nonzero_block_aligned(len: usize) -> bool {
len != 0 && len % AES_BLOCK_SIZE == 0
len != 0 && len.is_multiple_of(AES_BLOCK_SIZE)
}
/// Errors surfaced by [`encrypt`] and [`decrypt`].
@@ -47,7 +48,8 @@ pub fn encrypt(key: &[u8], iv: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, AesCb
return Err(AesCbcError::NotBlockAligned);
}
let mut buf = plaintext.to_vec();
// Wiped if an error leaves this plaintext copy unencrypted.
let mut buf = Zeroizing::new(plaintext.to_vec());
match key.len() {
16 => {
let enc = Encryptor::<Aes128>::new_from_slices(key, iv)
@@ -69,10 +71,13 @@ pub fn encrypt(key: &[u8], iv: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, AesCb
}
n => return Err(AesCbcError::InvalidKeyLength(n)),
}
Ok(buf)
Ok(core::mem::take(&mut *buf))
}
/// AES-CBC decrypt. Output is still PKCS7-padded; caller strips it.
/// AES-CBC decrypt without checking authentication or removing padding.
/// If the sender applied PKCS7 padding, the caller must validate and strip it.
/// The key must be 16 or 32 bytes, the IV 16 bytes, and the ciphertext a
/// non-zero multiple of 16 bytes.
pub fn decrypt(key: &[u8], iv: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, AesCbcError> {
if iv.len() != AES_BLOCK_SIZE {
return Err(AesCbcError::InvalidIvLength(iv.len()));
@@ -175,6 +180,15 @@ mod tests {
assert_eq!(&pt[..], &plaintext[..]);
}
#[test]
fn cipher_state_is_wiped_on_drop() {
fn wiped_on_drop<T: zeroize::ZeroizeOnDrop>() {}
wiped_on_drop::<Encryptor<Aes128>>();
wiped_on_drop::<Encryptor<Aes256>>();
wiped_on_drop::<Decryptor<Aes128>>();
wiped_on_drop::<Decryptor<Aes256>>();
}
/// Different key sizes must produce different ciphertexts for the same input.
#[test]
fn test_aes128_vs_aes256_distinct_ciphertexts() {
+3 -1
View File
@@ -14,7 +14,9 @@ pub enum Ed25519Error {
/// Public key bytes were not a valid Ed25519 point.
#[error("invalid public key bytes")]
InvalidPublicKey,
/// Signature bytes could not be decoded as an Ed25519 signature.
/// Retained signature-decoding error variant. The current `verify` method
/// accepts a fixed 64-byte signature and returns `VerificationFailed` on
/// verification failure.
#[error("invalid signature bytes")]
InvalidSignature,
}
+23 -10
View File
@@ -5,6 +5,7 @@ use alloc::vec::Vec;
use hkdf::Hkdf;
use sha2::Sha256;
use thiserror::Error;
use zeroize::Zeroizing;
/// Per RFC 5869, HKDF-SHA256 can emit at most 255 * HashLen = 8160 bytes.
const MAX_OUTPUT_LENGTH: usize = 255 * 32;
@@ -23,31 +24,36 @@ pub enum HkdfError {
/// HKDF-SHA256 key derivation (RFC 5869).
///
/// `length` is capped at 8160 bytes. `salt = None` uses 32 zero bytes as
/// specified by the RFC; `info = None` uses an empty context string.
/// specified by the RFC; `info = None` uses an empty context string. The
/// output is wiped when it is dropped.
pub fn hkdf_sha256(
length: usize,
ikm: &[u8],
salt: Option<&[u8]>,
info: Option<&[u8]>,
) -> Result<Vec<u8>, HkdfError> {
) -> Result<Zeroizing<Vec<u8>>, HkdfError> {
if length > MAX_OUTPUT_LENGTH {
return Err(HkdfError::OutputTooLong(length));
}
let hk = Hkdf::<Sha256>::new(salt, ikm);
let mut okm = vec![0u8; length];
let mut okm = Zeroizing::new(vec![0u8; length]);
hk.expand(info.unwrap_or(b""), &mut okm)
.map_err(|_| HkdfError::ExpansionFailed)?;
Ok(okm)
}
/// Derive the 64-byte session key used for RNS link encryption:
/// `HKDF-SHA256(length=64, ikm=shared_secret, salt=identity_hash, info=None)`.
pub fn derive_key_64(shared_secret: &[u8], salt: &[u8]) -> Result<[u8; 64], HkdfError> {
let okm = hkdf_sha256(64, shared_secret, Some(salt), None)?;
let mut out = [0u8; 64];
out.copy_from_slice(&okm);
Ok(out)
/// Derive 64 key bytes with the caller-provided salt:
/// `HKDF-SHA256(length=64, ikm=shared_secret, salt=salt, info=None)`.
/// Identity encryption passes the identity hash. Link key derivation instead
/// selects its key length by mode and uses the Link ID as salt.
/// The key is expanded straight into its return buffer, which is wiped on drop.
pub fn derive_key_64(shared_secret: &[u8], salt: &[u8]) -> Result<Zeroizing<[u8; 64]>, HkdfError> {
let mut okm = Zeroizing::new([0u8; 64]);
Hkdf::<Sha256>::new(Some(salt), shared_secret)
.expand(b"", &mut okm[..])
.map_err(|_| HkdfError::ExpansionFailed)?;
Ok(okm)
}
#[cfg(test)]
@@ -84,5 +90,12 @@ mod tests {
fn test_derive_key_64() {
let key = derive_key_64(b"shared_secret", b"salt_value").unwrap();
assert_eq!(key.len(), 64);
let cases: [(&[u8], &[u8]); 2] = [(b"shared_secret", b"salt_value"), (&[7; 32], &[9; 16])];
for (ikm, salt) in cases {
assert_eq!(
&derive_key_64(ikm, salt).unwrap()[..],
&hkdf_sha256(64, ikm, Some(salt), None).unwrap()[..]
);
}
}
}
+12 -3
View File
@@ -1,6 +1,11 @@
//! Cryptographic primitives for Reticulum. Constants, derivation inputs, and
//! wire-visible byte layouts match the Python reference (`RNS/Cryptography/`)
//! exactly — downstream interop depends on it. `no_std + alloc` when `std` is off.
//! Cryptographic primitives used by Reticulum identities, Links and Tokens.
//! This crate exposes low-level ciphers, hashes, key derivation and key types;
//! callers supply the protocol-specific salts, authentication and key lifecycle.
//!
//! Disabling this crate's `std` feature selects `no_std + alloc` for its code.
//! Workspace dependencies retain their own default features, and random/key
//! generation still requires an operating-system entropy source. This setting
//! alone does not make the crate a bare-metal cryptographic backend.
#![cfg_attr(not(feature = "std"), no_std)]
#![warn(missing_docs)]
extern crate alloc;
@@ -16,6 +21,10 @@ pub mod token;
pub mod x25519;
pub use token::TOKEN_OVERHEAD;
/// The wiping types in this crate's API, such as the output of
/// [`hkdf::hkdf_sha256`], for crates that hold secrets without depending on
/// `zeroize` themselves.
pub use zeroize;
use alloc::string::String;
use core::fmt::Write;
+4 -2
View File
@@ -8,7 +8,8 @@ const BLOCK_SIZE: usize = 16;
/// Errors surfaced by [`unpad`].
#[derive(Debug, Error)]
pub enum Pkcs7Error {
/// Trailing byte is zero or greater than the 16-byte block size.
/// Trailing byte is zero, greater than the 16-byte block size, or greater
/// than the input length.
#[error("invalid padding: padding byte value {0} exceeds block size {BLOCK_SIZE}")]
InvalidPaddingValue(u8),
/// The declared padding length doesn't match the trailing bytes.
@@ -33,7 +34,8 @@ pub fn pad(data: &[u8]) -> Vec<u8> {
/// Strip PKCS7 padding for a 16-byte block size.
///
/// All padding bytes are validated; a mismatch returns an error.
/// All padding bytes are validated; a mismatch returns an error. This helper
/// checks the trailing padding only, not the input's total block alignment.
pub fn unpad(data: &[u8]) -> Result<&[u8], Pkcs7Error> {
if data.is_empty() {
return Err(Pkcs7Error::EmptyInput);
+57 -14
View File
@@ -1,15 +1,27 @@
//! RNS encryption token: AES-256-CBC + HMAC-SHA256 over an IV-prefixed ciphertext.
//! RNS encryption token: AES-CBC + HMAC-SHA256 over an IV-prefixed ciphertext.
//! A 64-byte key selects AES-256; a legacy 32-byte key selects AES-128.
use alloc::vec::Vec;
use thiserror::Error;
use zeroize::Zeroizing;
use crate::aes_cbc;
use crate::hmac::{hmac_sha256, hmac_verify};
use crate::pkcs7;
use crate::random::random_16;
use crate::random::{random_16, random_bytes};
/// IV (16) + HMAC (32). A token is this plus the PKCS7-padded ciphertext.
pub const TOKEN_OVERHEAD: usize = 48;
/// AES block size used by legacy AES-128 tokens.
pub const AES128_BLOCKSIZE: usize = 16;
/// AES block size used by current AES-256 tokens.
pub const AES256_BLOCKSIZE: usize = 16;
/// AES-256 token key size: 32-byte HMAC key + 32-byte encryption key.
pub const KEY_LENGTH: usize = 64;
/// Legacy AES-128 token key size: 16-byte HMAC key + 16-byte encryption key.
pub const LEGACY_KEY_LENGTH: usize = 32;
/// Python `Identity.DERIVED_KEY_LENGTH_LEGACY`.
pub const DERIVED_KEY_LENGTH_LEGACY: usize = LEGACY_KEY_LENGTH;
/// Errors surfaced by [`encrypt`] and [`decrypt`].
#[derive(Debug, Error)]
@@ -17,13 +29,15 @@ pub enum TokenError {
/// Key must be 32 or 64 bytes.
#[error("invalid key length: expected 32 or 64, got {0}")]
InvalidKeyLength(usize),
/// Token is shorter than [`TOKEN_OVERHEAD`] so cannot contain IV + HMAC.
/// Retained short-token error variant. The current `decrypt` method maps
/// every token shorter than 64 bytes to `AuthenticationFailed`.
#[error("token too short for decryption")]
TooShort,
/// HMAC tag did not validate.
/// Token length, authentication, block alignment, decryption or padding failed.
#[error("authentication failed")]
AuthenticationFailed,
/// Underlying AES-CBC decrypt returned an error.
/// Retained decryption error variant. The current `decrypt` method maps
/// underlying cipher failures to `AuthenticationFailed`.
#[error("decryption failed")]
DecryptionFailed,
/// Underlying AES-CBC encrypt returned an error.
@@ -35,19 +49,24 @@ pub enum TokenError {
/// 64 → 32/32 (AES-256 + HMAC-SHA256); 32 → 16/16 (AES-128, legacy).
fn split_key(key: &[u8]) -> Result<(&[u8], &[u8]), TokenError> {
match key.len() {
64 => Ok((&key[..32], &key[32..])),
32 => Ok((&key[..16], &key[16..])),
KEY_LENGTH => Ok((&key[..32], &key[32..])),
LEGACY_KEY_LENGTH => Ok((&key[..16], &key[16..])),
n => Err(TokenError::InvalidKeyLength(n)),
}
}
/// Generate a fresh AES-256 token key with the operating-system CSPRNG.
pub fn generate_key() -> Zeroizing<Vec<u8>> {
Zeroizing::new(random_bytes(KEY_LENGTH))
}
/// Token encrypt (Modified Fernet — no version byte, no timestamp).
/// Wire: `IV(16) || AES-CBC(PKCS7(plaintext)) || HMAC-SHA256(IV || ciphertext)(32)`.
pub fn encrypt(plaintext: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
let (signing_key, encryption_key) = split_key(key)?;
let iv = random_16();
let padded = pkcs7::pad(plaintext);
let padded = Zeroizing::new(pkcs7::pad(plaintext));
let ciphertext =
aes_cbc::encrypt(encryption_key, &iv, &padded).map_err(|_| TokenError::EncryptionFailed)?;
@@ -64,8 +83,13 @@ pub fn encrypt(plaintext: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
Ok(token)
}
/// Token decrypt. All failure modes collapse to `AuthenticationFailed`
/// (padding-oracle defence). HMAC comparison is constant-time.
/// Authenticate and decrypt a Token. An invalid key length returns
/// `InvalidKeyLength`; malformed-token, authentication, cipher and padding
/// failures return `AuthenticationFailed`. HMAC comparison is constant-time.
///
/// The plaintext is returned in the buffer it was decrypted into, and a failed
/// decryption wipes that buffer. Callers wrap a secret plaintext in
/// [`Zeroizing`] so it is wiped when dropped.
pub fn decrypt(token: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
let (signing_key, encryption_key) = split_key(key)?;
@@ -89,12 +113,17 @@ pub fn decrypt(token: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
return Err(TokenError::AuthenticationFailed);
}
let padded = aes_cbc::decrypt(encryption_key, iv, ciphertext)
.map_err(|_| TokenError::AuthenticationFailed)?;
let mut padded = Zeroizing::new(
aes_cbc::decrypt(encryption_key, iv, ciphertext)
.map_err(|_| TokenError::AuthenticationFailed)?,
);
let plaintext = pkcs7::unpad(&padded).map_err(|_| TokenError::AuthenticationFailed)?;
let len = pkcs7::unpad(&padded)
.map_err(|_| TokenError::AuthenticationFailed)?
.len();
padded.truncate(len);
Ok(plaintext.to_vec())
Ok(core::mem::take(&mut *padded))
}
#[cfg(test)]
@@ -112,6 +141,20 @@ mod tests {
assert_eq!(&decrypted, plaintext);
}
#[test]
fn generated_key_is_valid_and_unique() {
let first = generate_key();
let second = generate_key();
assert_eq!(first.len(), KEY_LENGTH);
assert_eq!(second.len(), KEY_LENGTH);
assert_ne!(&*first, &*second);
assert_eq!(
decrypt(&encrypt(b"generated", &first).unwrap(), &first).unwrap(),
b"generated"
);
}
#[test]
fn test_encrypt_produces_correct_structure() {
let key = [0x42u8; 64];
+7 -4
View File
@@ -4,7 +4,8 @@ use rand_core::OsRng;
use x25519_dalek::{PublicKey, StaticSecret};
use zeroize::Zeroize;
/// X25519 private key (32 bytes, clamped scalar).
/// X25519 private key material (32 bytes). Scalar clamping occurs during
/// public-key derivation and Diffie-Hellman, not when these bytes are stored.
///
/// Key material is zeroized on drop.
pub struct X25519PrivateKey {
@@ -38,14 +39,14 @@ impl X25519PrivateKey {
}
}
/// Construct from a 32-byte scalar.
/// Store 32 bytes of private key material without changing their encoding.
pub fn from_bytes(bytes: &[u8; 32]) -> Self {
Self {
secret: StaticSecret::from(*bytes),
}
}
/// Return the 32-byte scalar.
/// Return the stored 32-byte private key material.
pub fn to_bytes(&self) -> [u8; 32] {
self.secret.to_bytes()
}
@@ -58,13 +59,15 @@ impl X25519PrivateKey {
}
/// Compute the shared secret with `peer` via X25519 Diffie-Hellman.
/// This primitive does not reject an all-zero result; a protocol requiring
/// a contributory-behavior check must validate the returned secret.
pub fn exchange(&self, peer: &X25519PublicKey) -> [u8; 32] {
self.secret.diffie_hellman(&peer.key).to_bytes()
}
}
impl X25519PublicKey {
/// Parse a 32-byte u-coordinate.
/// Store a 32-byte u-coordinate without rejecting low-order public inputs.
pub fn from_bytes(bytes: &[u8; 32]) -> Self {
Self {
key: PublicKey::from(*bytes),
+168
View File
@@ -0,0 +1,168 @@
//! Shared by the secret-residue test binaries. A recording allocator copies
//! every block the calling thread frees while a check runs; each check then
//! searches those copies for its secrets.
#![allow(dead_code)]
use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::{Cell, UnsafeCell};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Mutex, MutexGuard};
const RECORD_CAPACITY: usize = 8 << 20;
struct Recording(UnsafeCell<[u8; RECORD_CAPACITY]>);
// Written only by the armed thread while armed, read only after disarming.
unsafe impl Sync for Recording {}
static RECORDING: Recording = Recording(UnsafeCell::new([0; RECORD_CAPACITY]));
static RECORDED: AtomicUsize = AtomicUsize::new(0);
static OVERFLOWED: AtomicBool = AtomicBool::new(false);
static PEAK: AtomicUsize = AtomicUsize::new(0);
static SERIAL: Mutex<()> = Mutex::new(());
thread_local! {
static ARMED: Cell<bool> = const { Cell::new(false) };
}
struct RecordingAllocator;
fn armed() -> bool {
ARMED.try_with(Cell::get).unwrap_or(false)
}
unsafe impl GlobalAlloc for RecordingAllocator {
// Blocks handed out while armed start zeroed, so a recorded block holds
// only what was written during the check, never a reused block's old bytes.
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
if !armed() {
return unsafe { System.alloc(layout) };
}
PEAK.fetch_max(layout.size(), Ordering::Relaxed);
unsafe { System.alloc_zeroed(layout) }
}
// The default `realloc` frees the old block through `dealloc`, so blocks
// left behind by growth are recorded too.
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
if armed() {
let start = RECORDED.load(Ordering::Relaxed);
let end = start + 4 + layout.size();
if end <= RECORD_CAPACITY {
let base = RECORDING.0.get().cast::<u8>();
unsafe {
base.add(start)
.cast::<[u8; 4]>()
.write_unaligned((layout.size() as u32).to_le_bytes());
std::ptr::copy_nonoverlapping(ptr, base.add(start + 4), layout.size());
}
RECORDED.store(end, Ordering::Relaxed);
} else {
OVERFLOWED.store(true, Ordering::Relaxed);
}
}
unsafe { System.dealloc(ptr, layout) }
}
}
#[global_allocator]
static ALLOCATOR: RecordingAllocator = RecordingAllocator;
pub fn serial() -> MutexGuard<'static, ()> {
SERIAL
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
pub struct Freed {
pub blocks: Vec<Vec<u8>>,
pub peak_allocation: usize,
}
/// Run `f` and return its result with a copy of every block it freed.
pub fn freed_by<R>(f: impl FnOnce() -> R) -> (R, Freed) {
RECORDED.store(0, Ordering::Relaxed);
OVERFLOWED.store(false, Ordering::Relaxed);
PEAK.store(0, Ordering::Relaxed);
ARMED.with(|armed| armed.set(true));
let result = f();
ARMED.with(|armed| armed.set(false));
assert!(
!OVERFLOWED.load(Ordering::Relaxed),
"freed blocks exceeded the recording buffer"
);
let len = RECORDED.load(Ordering::Relaxed);
let recorded = unsafe { std::slice::from_raw_parts(RECORDING.0.get().cast::<u8>(), len) };
let mut blocks = Vec::new();
let mut at = 0;
while at < len {
let size = u32::from_le_bytes(recorded[at..at + 4].try_into().unwrap()) as usize;
blocks.push(recorded[at + 4..at + 4 + size].to_vec());
at += 4 + size;
}
let freed = Freed {
blocks,
peak_allocation: PEAK.load(Ordering::Relaxed),
};
(result, freed)
}
/// Whether `block` holds 16 consecutive bytes of `secret`.
pub fn holds(block: &[u8], secret: &[u8]) -> bool {
!find(&[block.to_vec()], &[secret]).is_empty()
}
/// For each block holding 16 consecutive bytes of any of `secrets`: its
/// length and the indexes of the secrets it holds.
pub fn find(blocks: &[Vec<u8>], secrets: &[&[u8]]) -> Vec<(usize, Vec<usize>)> {
let mut windows: HashMap<&[u8], Vec<usize>> = HashMap::new();
for (index, secret) in secrets.iter().enumerate() {
assert!(secret.len() >= 16, "secret is too short to search for");
for window in secret.windows(16) {
let owners = windows.entry(window).or_default();
if owners.last() != Some(&index) {
owners.push(index);
}
}
}
let mut found = Vec::new();
for block in blocks {
let mut held: Vec<usize> = block
.windows(16)
.filter_map(|window| windows.get(window))
.flatten()
.copied()
.collect();
held.sort_unstable();
held.dedup();
if !held.is_empty() {
found.push((block.len(), held));
}
}
found
}
/// Fail if any freed block holds part of a secret.
pub fn assert_no_residue(freed: &Freed, secrets: &[(&str, &[u8])]) {
let values: Vec<&[u8]> = secrets.iter().map(|(_, secret)| *secret).collect();
let mut found = Vec::new();
for (len, held) in find(&freed.blocks, &values) {
for index in held {
found.push(format!("{} in a freed {len}-byte block", secrets[index].0));
}
}
assert!(found.is_empty(), "secret residue: {found:?}");
}
pub fn pseudo_random<const N: usize>(seed: u64) -> [u8; N] {
let mut state = seed;
let mut out = [0u8; N];
for byte in &mut out {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
*byte = (state >> 24) as u8;
}
out
}
+137
View File
@@ -0,0 +1,137 @@
//! Plaintext and key material must not survive in freed heap memory.
mod residue;
use residue::{assert_no_residue, freed_by, holds, pseudo_random, serial};
use rns_crypto::{aes_cbc, hkdf, hmac, token};
use std::hint::black_box;
use zeroize::Zeroizing;
#[test]
fn the_harness_finds_unwiped_copies() {
let _serial = serial();
let secret: [u8; 64] = pseudo_random(12);
let ((), dropped) = freed_by(|| drop(black_box(secret.to_vec())));
// A wiped buffer that grew still frees its first block unwiped.
let ((), grown) = freed_by(|| {
let mut copy = Zeroizing::new(Vec::with_capacity(32));
copy.extend_from_slice(&secret[..32]);
copy.extend_from_slice(&secret[32..]);
black_box(&copy);
});
for (case, freed) in [("dropped", dropped), ("grown", grown)] {
assert!(
freed.blocks.iter().any(|block| holds(block, &secret)),
"{case}: copy not found"
);
}
}
#[test]
fn the_harness_ignores_bytes_freed_before_the_check() {
let _serial = serial();
let secret: [u8; 64] = pseudo_random(13);
// Large enough that the allocator hands the same block straight back.
drop(black_box(secret.repeat(1024)));
let ((), freed) = freed_by(|| drop(black_box(Vec::<u8>::with_capacity(64 * 1024))));
assert_no_residue(&freed, &[("secret", &secret)]);
}
#[test]
fn token_encrypt_frees_no_plaintext() {
let _serial = serial();
let key: [u8; 64] = pseudo_random(1);
let plaintext: [u8; 100] = pseudo_random(2);
let (token, freed) = freed_by(|| token::encrypt(&plaintext, &key).unwrap());
assert_no_residue(&freed, &[("plaintext", &plaintext)]);
assert_eq!(
&Zeroizing::new(token::decrypt(&token, &key).unwrap())[..],
&plaintext[..]
);
}
#[test]
fn token_decrypt_frees_no_plaintext() {
let _serial = serial();
let key: [u8; 64] = pseudo_random(3);
let plaintext: [u8; 100] = pseudo_random(4);
let token = token::encrypt(&plaintext, &key).unwrap();
let ((), freed) = freed_by(|| {
let decrypted = Zeroizing::new(token::decrypt(&token, &key).unwrap());
assert_eq!(&decrypted[..], &plaintext[..]);
});
assert_no_residue(&freed, &[("plaintext", &plaintext)]);
}
#[test]
fn token_decrypt_wipes_an_authenticated_plaintext_with_bad_padding() {
let _serial = serial();
let key: [u8; 64] = pseudo_random(5);
let mut plaintext: [u8; 64] = pseudo_random(6);
plaintext[63] = 0;
let iv = [0x24u8; 16];
let mut token = iv.to_vec();
token.extend_from_slice(&aes_cbc::encrypt(&key[32..], &iv, &plaintext).unwrap());
let mac = hmac::hmac_sha256(&key[..32], &token);
token.extend_from_slice(&mac);
let (result, freed) = freed_by(|| token::decrypt(&token, &key));
assert!(matches!(
result,
Err(token::TokenError::AuthenticationFailed)
));
assert_no_residue(&freed, &[("plaintext", &plaintext[..63])]);
}
#[test]
fn aes_cbc_encrypt_with_a_bad_key_frees_no_plaintext() {
let _serial = serial();
let plaintext: [u8; 64] = pseudo_random(7);
let (result, freed) = freed_by(|| aes_cbc::encrypt(&[0x11; 24], &[0x22; 16], &plaintext));
assert!(matches!(
result,
Err(aes_cbc::AesCbcError::InvalidKeyLength(24))
));
assert_no_residue(&freed, &[("plaintext", &plaintext)]);
}
#[test]
fn derive_key_64_frees_no_key() {
let _serial = serial();
let shared: [u8; 32] = pseudo_random(8);
let salt: [u8; 16] = pseudo_random(9);
let expected = hkdf::hkdf_sha256(64, &shared, Some(&salt), None).unwrap();
let ((), freed) = freed_by(|| {
let derived = hkdf::derive_key_64(&shared, &salt).unwrap();
assert_eq!(&derived[..], &expected[..]);
});
assert_no_residue(&freed, &[("derived key", &expected)]);
}
#[test]
fn hkdf_output_is_wiped_when_dropped() {
let _serial = serial();
let ikm: [u8; 32] = pseudo_random(10);
let salt: [u8; 16] = pseudo_random(11);
let expected = hkdf::derive_key_64(&ikm, &salt).unwrap();
let ((), freed) = freed_by(|| {
let okm: Zeroizing<Vec<u8>> = hkdf::hkdf_sha256(64, &ikm, Some(&salt), None).unwrap();
assert_eq!(&okm[..], &expected[..]);
});
assert_no_residue(&freed, &[("HKDF output", &expected[..])]);
}
+11 -1
View File
@@ -1,9 +1,11 @@
[package]
name = "rns-identity"
description = "Identity, Destination, and Announce system for Reticulum"
publish = false
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
license-file.workspace = true
[dependencies]
rns-crypto = { workspace = true, features = ["std"] }
@@ -13,9 +15,17 @@ thiserror = { workspace = true }
rmp-serde = { workspace = true }
rmpv = { workspace = true }
serde = { workspace = true }
serde_bytes = { workspace = true }
rand = { workspace = true }
tracing = { workspace = true }
hex = { workspace = true }
sha2 = { workspace = true }
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem"] }
[dev-dependencies]
proptest = { workspace = true }
+60 -19
View File
@@ -12,6 +12,9 @@ const RANDOM_HASH_SIZE: usize = 10;
const SIGNATURE_SIZE: usize = 64;
const RATCHET_SIZE: usize = 32;
/// Maximum value carried in the low five bytes of an announce random hash.
pub const ANNOUNCE_TIME_MAX: u64 = (1u64 << 40) - 1;
const MIN_ANNOUNCE_SIZE: usize = PUBKEY_SIZE + NAME_HASH_SIZE + RANDOM_HASH_SIZE + SIGNATURE_SIZE;
#[derive(Debug, Error)]
@@ -28,9 +31,13 @@ pub enum AnnounceError {
InvalidPublicKey,
#[error("hash collision detected for destination")]
HashCollision,
#[error("announce wire time exceeds 40-bit field: {0}")]
InvalidWireTime(u64),
}
/// Parsed announce data.
/// Parsed announce fields; parsing alone does not authenticate them.
/// Call [`Self::validate`] or [`Self::validate_with_known_key`] before learning
/// a destination. Replay, age and ingress policy belong to the caller.
#[derive(Debug, Clone)]
pub struct AnnounceData {
pub public_key: [u8; 64],
@@ -44,26 +51,43 @@ pub struct AnnounceData {
impl AnnounceData {
/// Create and sign an announce for a destination.
///
/// The `random_hash` is `random(5) || timestamp_be(5)` so receivers can
/// detect replays without a shared clock.
/// The `random_hash` is `random(5) || timestamp_be(5)`, using current Unix
/// seconds. This supplies randomness and ordering information; replay
/// rejection requires receiver state and is not performed by this type.
pub fn create(
identity: &Identity,
app_name: &str,
app_data: Option<&[u8]>,
ratchet_pub: Option<&[u8; 32]>,
) -> Result<Self, AnnounceError> {
let public_key = identity.get_public_key();
let nh = name_hash(app_name);
let random_bytes = rns_crypto::random::random_bytes(5);
let ts = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let ts_bytes = ts.to_be_bytes();
Self::create_at(identity, app_name, app_data, ratchet_pub, ts)
}
/// Create and sign an announce with an explicit 40-bit ordering value.
/// The caller manages persistence before transmission, and manages rotation
/// and expiry clocks separately. No state is persisted by this method.
pub fn create_at(
identity: &Identity,
app_name: &str,
app_data: Option<&[u8]>,
ratchet_pub: Option<&[u8; 32]>,
wire_time: u64,
) -> Result<Self, AnnounceError> {
if wire_time > ANNOUNCE_TIME_MAX {
return Err(AnnounceError::InvalidWireTime(wire_time));
}
let public_key = identity.get_public_key();
let nh = name_hash(app_name);
let random_bytes = rns_crypto::random::random_bytes(5);
let ts_bytes = wire_time.to_be_bytes();
let mut random_hash = [0u8; 10];
random_hash[..5].copy_from_slice(&random_bytes);
// Low 5 bytes of the u64 timestamp; wraps ~every 34 000 years.
// The value was range checked, so these are the complete 40 bits.
random_hash[5..].copy_from_slice(&ts_bytes[3..8]);
let dest_hash = crate::destination::Destination::hash_from_name_and_identity(
@@ -129,7 +153,8 @@ impl AnnounceData {
/// Parse an announce from packet payload bytes.
///
/// `has_ratchet` must match the packet header's context flag; the ratchet
/// field is not self-delimiting.
/// field is not self-delimiting. This checks minimum length only; use the
/// validation methods before trusting a parsed announce.
pub fn unpack(data: &[u8], has_ratchet: bool) -> Result<Self, AnnounceError> {
let min_size = if has_ratchet {
MIN_ANNOUNCE_SIZE + RATCHET_SIZE
@@ -241,7 +266,8 @@ impl AnnounceData {
}
/// Validate destination-hash binding and first-seen public-key continuity
/// after [`verify_signature`] has succeeded.
/// after [`Self::verify_signature`] has succeeded. Pass the identity
/// returned by that call; this method does not repeat signature validation.
pub fn validate_destination_binding(
&self,
packet_dest_hash: &[u8; 16],
@@ -269,15 +295,15 @@ impl AnnounceData {
// First-seen key binding: a valid signature on a different public key
// for an already-known destination hash implies a collision attack.
if let Some(known_key) = known_public_key {
if known_key != &self.public_key {
tracing::error!(
dest = hex::encode(packet_dest_hash),
"announce has valid signature and destination hash, but public key \
if let Some(known_key) = known_public_key
&& known_key != &self.public_key
{
tracing::error!(
dest = hex::encode(packet_dest_hash),
"announce has valid signature and destination hash, but public key \
differs from already known key — possible hash collision attack, rejecting"
);
return Err(AnnounceError::HashCollision);
}
);
return Err(AnnounceError::HashCollision);
}
Ok(())
@@ -302,6 +328,21 @@ mod tests {
assert_eq!(validated_id.hash, id.hash);
}
#[test]
fn explicit_wire_time_uses_exact_40_bit_value() {
let id = Identity::new();
let wire_time = 0x12_3456_789Au64;
let announce = AnnounceData::create_at(&id, "test.time", None, None, wire_time).unwrap();
assert_eq!(&announce.random_hash[5..], &wire_time.to_be_bytes()[3..]);
let maximum = AnnounceData::create_at(&id, "test.time", None, None, ANNOUNCE_TIME_MAX);
assert!(maximum.is_ok());
assert!(matches!(
AnnounceData::create_at(&id, "test.time", None, None, ANNOUNCE_TIME_MAX + 1,),
Err(AnnounceError::InvalidWireTime(_))
));
}
#[test]
fn test_create_and_validate_with_ratchet() {
let id = Identity::new();
+326
View File
@@ -0,0 +1,326 @@
//! Durable control-plane state for ratcheted announces.
//!
//! The signed Python-compatible ratchet ring contains only private keys. This
//! sidecar deliberately keeps local policy metadata separate: the last wall
//! time used for rotation and the last 40-bit value emitted on the wire.
use std::path::Path;
use serde::{Deserialize, Serialize};
use zeroize::Zeroizing;
use crate::announce::ANNOUNCE_TIME_MAX;
use crate::identity::Identity;
use crate::persistence;
const CONTROL_STATE_VERSION: u8 = 1;
const CONTROL_STATE_MAX_BYTES: usize = 4096;
fn invalid_data(message: impl Into<String>) -> std::io::Error {
std::io::Error::new(std::io::ErrorKind::InvalidData, message.into())
}
/// Signed, identity- and destination-bound state used to plan a ratcheted
/// announce without mutating live state before persistence succeeds.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RatchetControlState {
identity_hash: [u8; 16],
destination_hash: [u8; 16],
last_rotation_wall: Option<u64>,
last_announce_wire: Option<u64>,
}
impl RatchetControlState {
pub fn new(identity_hash: [u8; 16], destination_hash: [u8; 16]) -> Self {
Self {
identity_hash,
destination_hash,
last_rotation_wall: None,
last_announce_wire: None,
}
}
pub fn identity_hash(&self) -> [u8; 16] {
self.identity_hash
}
pub fn destination_hash(&self) -> [u8; 16] {
self.destination_hash
}
pub fn last_rotation_wall(&self) -> Option<u64> {
self.last_rotation_wall
}
pub fn last_announce_wire(&self) -> Option<u64> {
self.last_announce_wire
}
/// Anchor unknown rotation age at the current wall time. Existing age is
/// never overwritten by this operation.
pub fn anchor_rotation_if_unknown(&mut self, wall_now: u64) {
if self.last_rotation_wall.is_none() {
self.last_rotation_wall = Some(wall_now);
}
}
/// Rotation is due only when an age anchor exists and the wall clock has
/// advanced by the full interval. Clock rollback never looks elapsed.
pub fn rotation_due(&self, wall_now: u64, interval_secs: u64) -> bool {
self.last_rotation_wall
.is_some_and(|last| wall_now >= last && wall_now.saturating_sub(last) >= interval_secs)
}
/// Return a cloned candidate recording the supplied rotation time.
/// The caller performs the rotation and persists the candidate.
pub fn with_rotation_at(&self, wall_now: u64) -> Self {
let mut candidate = self.clone();
candidate.last_rotation_wall = Some(wall_now);
candidate
}
/// Prepare the next wire-ordering value without mutating this live state.
///
/// `None` means wall time has not advanced beyond the last durable value;
/// callers must coalesce/defer instead of inventing `last + 1`, which could
/// make an announce appear to come from the future.
pub fn prepare_announce(&self, wall_now: u64) -> std::io::Result<Option<Self>> {
if wall_now > ANNOUNCE_TIME_MAX {
return Err(invalid_data(format!(
"wall time {wall_now} exceeds 40-bit announce field"
)));
}
if self.last_announce_wire.is_some_and(|last| wall_now <= last) {
return Ok(None);
}
let mut candidate = self.clone();
candidate.last_announce_wire = Some(wall_now);
Ok(Some(candidate))
}
/// Persist this state as a signed, bounded MessagePack envelope.
pub fn save_verified(&self, path: &Path, identity: &Identity) -> std::io::Result<()> {
self.save_verified_impl(path, identity, false)
}
/// Persist announce ordering through [`persistence::durable_write`].
/// The caller must wait for success before releasing the corresponding
/// wire bytes and must handle the storage limits documented by that helper.
pub fn save_verified_durable(&self, path: &Path, identity: &Identity) -> std::io::Result<()> {
self.save_verified_impl(path, identity, true)
}
fn save_verified_impl(
&self,
path: &Path,
identity: &Identity,
durable: bool,
) -> std::io::Result<()> {
if identity.hash != self.identity_hash {
return Err(invalid_data("control state identity binding mismatch"));
}
self.validate()?;
let body = ControlStateBody {
version: CONTROL_STATE_VERSION,
identity_hash: self.identity_hash.to_vec(),
destination_hash: self.destination_hash.to_vec(),
last_rotation_wall: self.last_rotation_wall,
last_announce_wire: self.last_announce_wire,
};
let packed = Zeroizing::new(
rmp_serde::to_vec_named(&body).map_err(|e| std::io::Error::other(e.to_string()))?,
);
let signature = identity.sign(&packed).ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"identity cannot sign ratchet control state",
)
})?;
let envelope = ControlStateEnvelope {
signature: signature.to_vec(),
state: packed.to_vec(),
};
let encoded = Zeroizing::new(
rmp_serde::to_vec_named(&envelope).map_err(|e| std::io::Error::other(e.to_string()))?,
);
if encoded.len() > CONTROL_STATE_MAX_BYTES {
return Err(invalid_data("ratchet control state exceeds size limit"));
}
if durable {
persistence::durable_write(path, &encoded)
.map(|_| ())
.map_err(std::io::Error::other)
} else {
persistence::atomic_write(path, &encoded)
}
}
/// Load and verify state for exactly `identity` and `destination_hash`.
pub fn load_verified(
path: &Path,
identity: &Identity,
destination_hash: [u8; 16],
) -> std::io::Result<Self> {
let encoded = Zeroizing::new(
persistence::read_file_bounded(path, CONTROL_STATE_MAX_BYTES)?
.ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound))?,
);
let envelope: ControlStateEnvelope =
rmp_serde::from_slice(&encoded).map_err(|e| std::io::Error::other(e.to_string()))?;
if envelope.signature.len() != 64 {
return Err(invalid_data("invalid control-state signature length"));
}
let signature: [u8; 64] = envelope
.signature
.as_slice()
.try_into()
.map_err(|_| invalid_data("invalid control-state signature length"))?;
let packed = Zeroizing::new(envelope.state);
if !identity.verify(&packed, &signature) {
return Err(invalid_data("invalid ratchet control-state signature"));
}
let body: ControlStateBody =
rmp_serde::from_slice(&packed).map_err(|e| std::io::Error::other(e.to_string()))?;
if body.version != CONTROL_STATE_VERSION {
return Err(invalid_data(format!(
"unsupported ratchet control-state version {}",
body.version
)));
}
let identity_hash: [u8; 16] = body
.identity_hash
.as_slice()
.try_into()
.map_err(|_| invalid_data("invalid control-state identity hash"))?;
let stored_destination: [u8; 16] = body
.destination_hash
.as_slice()
.try_into()
.map_err(|_| invalid_data("invalid control-state destination hash"))?;
if identity_hash != identity.hash {
return Err(invalid_data("control state belongs to another identity"));
}
if stored_destination != destination_hash {
return Err(invalid_data("control state belongs to another destination"));
}
let state = Self {
identity_hash,
destination_hash: stored_destination,
last_rotation_wall: body.last_rotation_wall,
last_announce_wire: body.last_announce_wire,
};
state.validate()?;
Ok(state)
}
fn validate(&self) -> std::io::Result<()> {
if self
.last_announce_wire
.is_some_and(|value| value > ANNOUNCE_TIME_MAX)
{
return Err(invalid_data("stored announce time exceeds 40-bit field"));
}
Ok(())
}
}
#[derive(Serialize, Deserialize)]
struct ControlStateBody {
version: u8,
#[serde(with = "serde_bytes")]
identity_hash: Vec<u8>,
#[serde(with = "serde_bytes")]
destination_hash: Vec<u8>,
last_rotation_wall: Option<u64>,
last_announce_wire: Option<u64>,
}
#[derive(Serialize, Deserialize)]
struct ControlStateEnvelope {
#[serde(with = "serde_bytes")]
signature: Vec<u8>,
#[serde(with = "serde_bytes")]
state: Vec<u8>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn announce_time_never_moves_into_the_future() {
let identity = Identity::new();
let destination = [0x22; 16];
let state = RatchetControlState::new(identity.hash, destination);
let state = state.prepare_announce(100).unwrap().unwrap();
assert_eq!(state.last_announce_wire(), Some(100));
assert!(state.prepare_announce(100).unwrap().is_none());
assert!(state.prepare_announce(99).unwrap().is_none());
let next = state.prepare_announce(101).unwrap().unwrap();
assert_eq!(next.last_announce_wire(), Some(101));
}
#[test]
fn unknown_rotation_age_is_anchored_without_immediate_rotation() {
let identity = Identity::new();
let mut state = RatchetControlState::new(identity.hash, [0x33; 16]);
assert!(!state.rotation_due(100, 30));
state.anchor_rotation_if_unknown(100);
assert!(!state.rotation_due(100, 30));
assert!(!state.rotation_due(99, 30));
assert!(!state.rotation_due(129, 30));
assert!(state.rotation_due(130, 30));
}
#[test]
fn signed_state_roundtrip_enforces_identity_and_destination_binding() {
let dir = std::env::temp_dir().join("reticulum_ratchet_control_state");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("control");
let identity = Identity::new();
let wrong_identity = Identity::new();
let destination = [0x44; 16];
let mut state = RatchetControlState::new(identity.hash, destination);
state.anchor_rotation_if_unknown(100);
let state = state.prepare_announce(101).unwrap().unwrap();
state.save_verified(&path, &identity).unwrap();
assert_eq!(
RatchetControlState::load_verified(&path, &identity, destination).unwrap(),
state
);
assert!(RatchetControlState::load_verified(&path, &wrong_identity, destination).is_err());
assert!(RatchetControlState::load_verified(&path, &identity, [0x55; 16]).is_err());
assert!(
path.exists(),
"rejected state remains available for recovery"
);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn failed_candidate_persistence_cannot_mutate_live_state() {
let identity = Identity::new();
let destination = [0x66; 16];
let live = RatchetControlState::new(identity.hash, destination);
let candidate = live.prepare_announce(100).unwrap().unwrap();
let missing_parent = std::env::temp_dir()
.join("reticulum_missing_control_parent")
.join("nested")
.join("state");
let _ = std::fs::remove_dir_all(
missing_parent
.parent()
.and_then(Path::parent)
.unwrap_or_else(|| Path::new("/tmp")),
);
assert!(candidate.save_verified(&missing_parent, &identity).is_err());
assert_eq!(live.last_announce_wire(), None);
}
}
File diff suppressed because it is too large. Load diff
+323 -29
View File
@@ -3,14 +3,28 @@ use rns_crypto::hkdf::derive_key_64;
use rns_crypto::sha::truncated_hash;
use rns_crypto::token;
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
use serde::{Deserialize, Serialize};
use serde::Deserialize;
use thiserror::Error;
use zeroize::{Zeroize, Zeroizing};
use crate::persistence;
use crate::persistence::{self, SecretBytes};
use std::fmt;
use std::path::Path;
use std::sync::Arc;
/// HKDF-derived key length: 32 bytes AES key || 32 bytes HMAC key.
/// Elliptic curve used for identity encryption and ratchets.
pub const CURVE: &str = "Curve25519";
/// Combined X25519 and Ed25519 public/private key size, in bits.
pub const KEY_SIZE_BITS: usize = 512;
/// X25519 ratchet key size, in bits.
pub const RATCHET_SIZE_BITS: usize = 256;
/// X25519 ratchet key size, in bytes (Python `Identity.RATCHETSIZE`).
pub const RATCHETSIZE: usize = RATCHET_SIZE_BITS / 8;
/// Addressable identity hash size, in bits.
pub const HASH_LENGTH_BITS: usize = 128;
/// Ratchet identifier size, in bytes.
pub const RATCHET_ID_LENGTH: usize = 10;
/// HKDF-derived token key length: 32-byte HMAC key || 32-byte AES key.
pub const DERIVED_KEY_LENGTH: usize = 64;
/// Per-message overhead of `Identity::encrypt` before PKCS7 padding:
@@ -33,18 +47,69 @@ pub enum IdentityError {
Io(#[from] std::io::Error),
}
/// Delegate for an `Identity` whose private key is not in memory (e.g. a PIV
/// hardware token). Implemented outside this crate (see `rns-ratkey`). Both
/// operations must produce standard output — RFC 8032 Ed25519 / RFC 7748 X25519
/// — so the resulting identity is wire-identical to a software one.
pub trait LocalKeyBackend: Send + Sync {
/// Ed25519 signature over `message`, or `None` if currently unavailable.
fn sign_ed25519(&self, message: &[u8]) -> Option<[u8; 64]>;
/// X25519 ECDH shared secret with `peer_pub`, or `None` if unavailable.
fn ecdh(&self, peer_pub: &[u8; 32]) -> Option<[u8; 32]>;
/// Drop any cached authentication so the next operation must re-authenticate
/// (e.g. a hardware token re-locks its PIN). The default is a no-op;
/// backends with cached authentication must implement their own reset.
fn lock(&self) {}
}
/// A Reticulum identity: X25519 keypair for encryption + Ed25519 keypair for signing.
///
/// Wire representation:
/// - Private (64 B): `X25519_prv(32) || Ed25519_seed(32)`
/// - Public (64 B): `X25519_pub(32) || Ed25519_pub(32)`
/// - Hash (16 B): `SHA-256(public_64)[:16]`
///
/// Public-only identities can verify and encrypt. Hardware-backed identities
/// delegate private operations without exposing a software private key. Keep
/// the public `hash` unchanged: encryption derivation uses it as the HKDF salt.
pub struct Identity {
prv: Option<X25519PrivateKey>,
sig_prv: Option<Ed25519PrivateKey>,
pub_key: X25519PublicKey,
sig_pub: Ed25519PublicKey,
pub hash: [u8; 16],
/// Set only for hardware-backed identities; `None` for all software ones.
backend: Option<Arc<dyn LocalKeyBackend>>,
}
/// Successful identity decryption plus the ratchet that authenticated it.
///
/// `ratchet_id` is absent when the identity's base key performed decryption.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecryptionResult {
pub plaintext: Vec<u8>,
pub ratchet_id: Option<[u8; RATCHET_ID_LENGTH]>,
}
impl Clone for Identity {
/// Software identities clone their key material; hardware-backed identities
/// share the same `LocalKeyBackend` (Arc) — there is no extractable key to copy.
fn clone(&self) -> Self {
Self {
prv: self
.prv
.as_ref()
.map(|k| X25519PrivateKey::from_bytes(&k.to_bytes())),
sig_prv: self
.sig_prv
.as_ref()
.map(|k| Ed25519PrivateKey::from_bytes(&k.to_bytes())),
pub_key: self.pub_key.clone(),
sig_pub: self.sig_pub.clone(),
hash: self.hash,
backend: self.backend.clone(),
}
}
}
impl Default for Identity {
@@ -54,6 +119,13 @@ impl Default for Identity {
}
impl Identity {
pub const CURVE: &'static str = CURVE;
pub const KEY_SIZE_BITS: usize = KEY_SIZE_BITS;
pub const RATCHET_SIZE_BITS: usize = RATCHET_SIZE_BITS;
pub const RATCHETSIZE: usize = RATCHET_SIZE_BITS / 8;
pub const HASH_LENGTH_BITS: usize = HASH_LENGTH_BITS;
/// Generate a software identity with fresh X25519 and Ed25519 keys.
pub fn new() -> Self {
let prv = X25519PrivateKey::generate();
let sig_prv = Ed25519PrivateKey::generate();
@@ -67,9 +139,12 @@ impl Identity {
pub_key,
sig_pub,
hash,
backend: None,
}
}
/// Load exactly 64 bytes: an X25519 private key followed by an Ed25519 seed.
/// The caller remains responsible for protecting and wiping its input.
pub fn from_private_key(key: &[u8]) -> Result<Self, IdentityError> {
if key.len() != 64 {
return Err(IdentityError::InvalidPrivateKeyLength(key.len()));
@@ -91,10 +166,13 @@ impl Identity {
pub_key,
sig_pub,
hash,
backend: None,
})
}
/// Construct a verify/encrypt-only identity from its 64-byte public key.
/// Checks the length and Ed25519 key encoding; it does not establish who
/// owns the key or reject low-order X25519 input.
pub fn from_public_key(key: &[u8]) -> Result<Self, IdentityError> {
if key.len() != 64 {
return Err(IdentityError::InvalidPublicKeyLength(key.len()));
@@ -114,15 +192,34 @@ impl Identity {
pub_key,
sig_pub,
hash,
backend: None,
})
}
/// Load an identity from file, accepting either the current msgpack envelope
/// or a legacy raw 64-byte private key.
pub fn from_file(path: &Path) -> Result<Self, IdentityError> {
let data = std::fs::read(path)?;
/// Construct an identity whose private operations are served by `backend`
/// (e.g. a hardware token). Public-key-only in memory; `sign` and `decrypt`
/// delegate to the backend for base-key operations. The caller must ensure
/// the backend owns the matching private keys and implements the trait
/// contract; construction does not perform a signing or ECDH challenge.
pub fn from_backend(
public_key: &[u8],
backend: Arc<dyn LocalKeyBackend>,
) -> Result<Self, IdentityError> {
let mut id = Self::from_public_key(public_key)?;
id.backend = Some(backend);
Ok(id)
}
if let Ok(persisted) = rmp_serde::from_slice::<IdentityPersisted>(&data) {
/// Load an identity from file, accepting either the raw 64-byte private key
/// that Python and [`Self::to_file`] write, or the older msgpack envelope.
/// A file larger than 1 KiB is refused once 1025 bytes have been read.
pub fn from_file(path: &Path) -> Result<Self, IdentityError> {
let data = persistence::read_secret_file(path, IDENTITY_FILE_MAX_BYTES)?;
// An envelope never fits in 64 bytes, so a raw key is never parsed as one.
if data.len() != 64
&& let Ok(persisted) = rmp_serde::from_slice::<IdentityPersisted>(&data)
{
return Self::from_private_key(&persisted.private_key);
}
@@ -130,7 +227,9 @@ impl Identity {
}
/// Persist the identity as the raw 64-byte private key used by the Python
/// reference implementation, so identity files are interchangeable.
/// reference implementation. This is an unencrypted secret-key file.
/// Fails for public-only and hardware-backed identities because their
/// private key is not extractable here. Uses [`persistence::atomic_write`].
pub fn to_file(&self, path: &Path) -> Result<(), IdentityError> {
let key = self
.get_private_key()
@@ -145,7 +244,8 @@ impl Identity {
Ok(())
}
/// Return the 64-byte private key (`X25519_prv || Ed25519_seed`), zeroised on drop.
/// Return a copy of the software private key (`X25519_prv || Ed25519_seed`),
/// zeroised on drop. Returns `None` for public-only or backend identities.
pub fn get_private_key(&self) -> Option<Zeroizing<[u8; 64]>> {
let prv = self.prv.as_ref()?;
let sig_prv = self.sig_prv.as_ref()?;
@@ -163,21 +263,48 @@ impl Identity {
key
}
/// Lowercase, delimiter-free hexadecimal identity hash.
pub fn hexhash(&self) -> String {
hex::encode(self.hash)
}
/// Whether both software private keys are present. A hardware-backed
/// identity returns false even when its backend can sign or decrypt.
pub fn has_private_key(&self) -> bool {
self.prv.is_some() && self.sig_prv.is_some()
}
/// True if private operations are served by a hardware backend.
pub fn has_backend(&self) -> bool {
self.backend.is_some()
}
/// Ask the backend to clear cached authentication; a no-op without a backend.
/// Subsequent authentication behavior is defined by [`LocalKeyBackend::lock`].
pub fn lock(&self) {
if let Some(b) = self.backend.as_ref() {
b.lock();
}
}
/// Copy the software signing key; returns `None` for public-only and
/// backend identities. Use [`Self::sign`] to support either private backend.
pub fn get_signing_key(&self) -> Option<Ed25519PrivateKey> {
self.sig_prv
.as_ref()
.map(|k| Ed25519PrivateKey::from_bytes(&k.to_bytes()))
}
/// Sign `message` with the Ed25519 key; `None` if this is a public-only identity.
/// Sign `message` with the Ed25519 key, delegating to the hardware backend
/// when the in-memory key is absent; `None` if neither is available.
pub fn sign(&self, message: &[u8]) -> Option<[u8; 64]> {
self.sig_prv.as_ref().map(|key| key.sign(message))
match self.sig_prv.as_ref() {
Some(key) => Some(key.sign(message)),
None => self.backend.as_ref().and_then(|b| b.sign_ed25519(message)),
}
}
/// Verify an Ed25519 signature with this identity's public signing key.
pub fn verify(&self, message: &[u8], signature: &[u8; 64]) -> bool {
self.sig_pub.verify(message, signature).is_ok()
}
@@ -187,8 +314,10 @@ impl Identity {
/// Output layout: `ephemeral_X25519_pub(32) || IV(16) || AES-256-CBC(PKCS7(pt)) || HMAC(32)`.
///
/// Passing a `ratchet` public key substitutes it for the identity's X25519
/// public key in the ECDH, giving forward secrecy against later key
/// compromise.
/// public key in ECDH. Later compromise of the base identity key alone
/// does not reveal that ciphertext; compromise of a retained ratchet
/// private key still does. The caller must authenticate the target key.
/// Encryption does not sign the plaintext or identify its sender.
pub fn encrypt(
&self,
plaintext: &[u8],
@@ -208,7 +337,7 @@ impl Identity {
shared.zeroize();
let derived = derived?;
let ciphertext =
token::encrypt(plaintext, &derived).map_err(|_| IdentityError::DecryptionFailed)?;
token::encrypt(plaintext, &derived[..]).map_err(|_| IdentityError::DecryptionFailed)?;
let mut result = Vec::with_capacity(32 + ciphertext.len());
result.extend_from_slice(&ephemeral_pub.to_bytes());
@@ -224,6 +353,21 @@ impl Identity {
ratchets: Option<&[&[u8; 32]]>,
enforce_ratchets: bool,
) -> Result<Vec<u8>, IdentityError> {
self.decrypt_with_ratchet_id(ciphertext, ratchets, enforce_ratchets)
.map(|result| result.plaintext)
}
/// Decrypt ciphertext and report the ratchet key that authenticated it.
///
/// The identifier is `SHA-256(ratchet_public_key)[:10]`, matching the
/// reference implementation. Base-identity decryption returns no ratchet
/// identifier.
pub fn decrypt_with_ratchet_id(
&self,
ciphertext: &[u8],
ratchets: Option<&[&[u8; 32]]>,
enforce_ratchets: bool,
) -> Result<DecryptionResult, IdentityError> {
if ciphertext.len() < 32 {
return Err(IdentityError::DecryptionFailed);
}
@@ -239,10 +383,13 @@ impl Identity {
let mut shared = ratchet_prv.exchange(&peer_pub);
let derived_result = derive_key_64(&shared, &self.hash);
shared.zeroize();
if let Ok(derived) = derived_result {
if let Ok(plaintext) = token::decrypt(ct, &derived) {
return Ok(plaintext);
}
if let Ok(derived) = derived_result
&& let Ok(plaintext) = token::decrypt(ct, &derived[..])
{
return Ok(DecryptionResult {
plaintext,
ratchet_id: Some(Self::ratchet_id(&ratchet_prv.public_key().to_bytes())),
});
}
}
}
@@ -251,21 +398,41 @@ impl Identity {
return Err(IdentityError::DecryptionFailed);
}
let prv = self.prv.as_ref().ok_or(IdentityError::DecryptionFailed)?;
let mut shared = prv.exchange(&peer_pub);
// Identity-key ECDH: in-memory key if present, else the hardware backend.
let mut shared: [u8; 32] = if let Some(prv) = self.prv.as_ref() {
prv.exchange(&peer_pub)
} else if let Some(backend) = self.backend.as_ref() {
backend
.ecdh(&peer_pub_bytes)
.ok_or(IdentityError::DecryptionFailed)?
} else {
return Err(IdentityError::DecryptionFailed);
};
let derived_result =
derive_key_64(&shared, &self.hash).map_err(|_| IdentityError::DecryptionFailed);
shared.zeroize();
let derived = derived_result?;
let plaintext =
token::decrypt(ct, &derived).map_err(|_| IdentityError::DecryptionFailed)?;
Ok(plaintext)
token::decrypt(ct, &derived[..]).map_err(|_| IdentityError::DecryptionFailed)?;
Ok(DecryptionResult {
plaintext,
ratchet_id: None,
})
}
/// Derive the stable 80-bit identifier for a ratchet public key.
pub fn ratchet_id(ratchet_public_key: &[u8; 32]) -> [u8; RATCHET_ID_LENGTH] {
let full = rns_crypto::sha::sha256(ratchet_public_key);
let mut id = [0u8; RATCHET_ID_LENGTH];
id.copy_from_slice(&full[..RATCHET_ID_LENGTH]);
id
}
/// Sign `packet_hash` and return proof bytes.
///
/// `implicit_proof = true` returns the 64-byte signature alone; `false`
/// returns `packet_hash(32) || signature(64)` (96 bytes).
/// returns `packet_hash || signature`. Pass a 32-byte packet hash for the
/// 96-byte wire form; this method accepts other input lengths without validation.
pub fn prove(
&self,
packet_hash: &[u8],
@@ -293,10 +460,21 @@ impl Identity {
}
}
impl fmt::Display for Identity {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "<{}>", self.hexhash())
}
}
/// Identity files are a raw key or a small envelope; reading stops one byte
/// past this limit and refuses the file.
const IDENTITY_FILE_MAX_BYTES: usize = 1024;
// Msgpack envelope wrapping the raw 64-byte private key on disk.
#[derive(Serialize, Deserialize)]
struct IdentityPersisted {
private_key: Vec<u8>,
#[derive(Deserialize)]
struct IdentityPersisted<'a> {
#[serde(borrow)]
private_key: SecretBytes<'a, IDENTITY_FILE_MAX_BYTES>,
}
#[cfg(test)]
@@ -306,6 +484,8 @@ mod tests {
#[test]
fn test_generate_identity() {
let id = Identity::new();
assert_eq!(Identity::CURVE, "Curve25519");
assert_eq!(Identity::RATCHETSIZE, 32);
assert!(id.has_private_key());
assert_ne!(id.hash, [0u8; 16]);
}
@@ -365,8 +545,38 @@ mod tests {
assert!(id.decrypt(&ct, None, false).is_err());
let ratchets: Vec<&[u8; 32]> = vec![&ratchet_prv_bytes];
let pt = id.decrypt(&ct, Some(&ratchets), false).unwrap();
assert_eq!(&pt, plaintext);
let decrypted = id
.decrypt_with_ratchet_id(&ct, Some(&ratchets), false)
.unwrap();
assert_eq!(&decrypted.plaintext, plaintext);
assert_eq!(
decrypted.ratchet_id,
Some(Identity::ratchet_id(&ratchet_pub))
);
}
#[test]
fn base_identity_decryption_reports_no_ratchet() {
let id = Identity::new();
let ciphertext = id.encrypt(b"base identity", None).unwrap();
let decrypted = id
.decrypt_with_ratchet_id(&ciphertext, None, false)
.unwrap();
assert_eq!(decrypted.plaintext, b"base identity");
assert_eq!(decrypted.ratchet_id, None);
}
#[test]
fn identity_metadata_and_display_match_wire_identity() {
let id = Identity::new();
assert_eq!(CURVE, "Curve25519");
assert_eq!(KEY_SIZE_BITS, id.get_public_key().len() * 8);
assert_eq!(RATCHET_SIZE_BITS, 32 * 8);
assert_eq!(HASH_LENGTH_BITS, id.hash.len() * 8);
assert_eq!(id.hexhash(), hex::encode(id.hash));
assert_eq!(id.to_string(), format!("<{}>", hex::encode(id.hash)));
}
#[test]
@@ -414,6 +624,39 @@ mod tests {
let _ = std::fs::remove_dir(&dir);
}
#[test]
fn raw_keys_that_begin_like_an_envelope_load_as_raw_keys() {
let dir = std::env::temp_dir().join(format!(
"reticulum_identity_test_envelope_prefix_{}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
// One-field msgpack arrays holding an empty array, 61 bytes of binary
// that end exactly at byte 64, and three integers.
let prefixes: [&[u8]; 3] = [&[0x91, 0x90], &[0x91, 0xc4, 0x3d], &[0x91, 0x93, 1, 2, 3]];
let mut failures = Vec::new();
for (index, prefix) in prefixes.into_iter().enumerate() {
let mut key = [0u8; 64];
for (offset, byte) in key.iter_mut().enumerate() {
*byte = (offset as u8).wrapping_mul(37).wrapping_add(index as u8);
}
key[..prefix.len()].copy_from_slice(prefix);
let expected = Identity::from_private_key(&key).unwrap();
let path = dir.join(format!("identity-{index}"));
std::fs::write(&path, key).unwrap();
match Identity::from_file(&path) {
Ok(loaded) => {
assert_eq!(loaded.hash, expected.hash, "prefix {prefix:02x?}");
assert_eq!(*loaded.get_private_key().unwrap(), key);
}
Err(e) => failures.push(format!("prefix {prefix:02x?}: {e}")),
}
}
std::fs::remove_dir_all(&dir).unwrap();
assert!(failures.is_empty(), "{failures:?}");
}
#[test]
fn test_file_backward_compat_raw() {
let dir = std::env::temp_dir().join("reticulum_identity_test_compat");
@@ -483,4 +726,55 @@ mod tests {
let pub_id = Identity::from_public_key(&id.get_public_key()).unwrap();
assert!(pub_id.prove(b"test", true).is_err());
}
// A software-keyed backend, standing in for a hardware token in tests.
struct SoftwareBackend {
sig: rns_crypto::ed25519::Ed25519PrivateKey,
x: rns_crypto::x25519::X25519PrivateKey,
}
impl LocalKeyBackend for SoftwareBackend {
fn sign_ed25519(&self, message: &[u8]) -> Option<[u8; 64]> {
Some(self.sig.sign(message))
}
fn ecdh(&self, peer_pub: &[u8; 32]) -> Option<[u8; 32]> {
let peer = rns_crypto::x25519::X25519PublicKey::from_bytes(peer_pub);
Some(self.x.exchange(&peer))
}
}
#[test]
fn test_backend_identity_is_wire_identical() {
use std::sync::Arc;
// Build a backend from a software identity's keys, then a separate
// backend-driven identity over the same public key.
let sw = Identity::new();
let prv = sw.get_private_key().unwrap();
let mut x_bytes = [0u8; 32];
x_bytes.copy_from_slice(&prv[..32]);
let mut ed_bytes = [0u8; 32];
ed_bytes.copy_from_slice(&prv[32..]);
let backend = Arc::new(SoftwareBackend {
sig: rns_crypto::ed25519::Ed25519PrivateKey::from_bytes(&ed_bytes),
x: rns_crypto::x25519::X25519PrivateKey::from_bytes(&x_bytes),
});
let hw = Identity::from_backend(&sw.get_public_key(), backend).unwrap();
// Same identity, but no extractable in-memory key.
assert_eq!(hw.hash, sw.hash);
assert!(!hw.has_private_key());
assert!(hw.get_private_key().is_none());
// sign() delegates and is byte-identical (Ed25519 is deterministic).
let msg = b"hardware parity";
assert_eq!(hw.sign(msg), sw.sign(msg));
assert!(hw.verify(msg, &hw.sign(msg).unwrap()));
// decrypt() delegates the ECDH to the backend; round-trips, and the
// software identity decrypts the same ciphertext (identical key material).
let ct = hw.encrypt(b"secret payload", None).unwrap();
assert_eq!(hw.decrypt(&ct, None, false).unwrap(), b"secret payload");
assert_eq!(sw.decrypt(&ct, None, false).unwrap(), b"secret payload");
}
}
+113 -10
View File
@@ -1,9 +1,16 @@
use std::sync::Arc;
use rns_crypto::hkdf::hkdf_sha256;
use rns_crypto::sha::sha256;
use thiserror::Error;
use zeroize::Zeroizing;
// Fixed IFAC HKDF salt. Shared with the Python reference; changing it breaks interop.
const IFAC_SALT: &str = "adf54d882c9a9b80771eb4995d702d4a3e733391b2a0f53f416d9f907e55cff8";
/// Fixed IFAC HKDF salt shared with the Python reference.
///
/// This is public for applications that need to derive or inspect
/// Python-compatible IFAC material outside the runtime helper. Changing it
/// would break interoperability.
pub const IFAC_SALT: &str = "adf54d882c9a9b80771eb4995d702d4a3e733391b2a0f53f416d9f907e55cff8";
#[derive(Debug, Error)]
pub enum IfacError {
@@ -17,13 +24,24 @@ pub enum IfacError {
///
/// `ifac_origin` concatenates `SHA-256(network_name)` and `SHA-256(passphrase)`
/// for whichever fields are `Some(_)` (a `None` field is omitted, so `None`
/// and `Some("")` differ), then HKDF-SHA256 expands it under the fixed salt.
/// and `Some("")` differ). HKDF-SHA256 expands `SHA-256(ifac_origin)` under
/// the fixed salt.
/// First 32 bytes → X25519 private; second 32 → Ed25519 seed.
pub fn derive_ifac_key(
network_name: Option<&str>,
passphrase: Option<&str>,
) -> Result<[u8; 64], IfacError> {
let mut ifac_origin = Vec::new();
let mut key = [0u8; 64];
derive_into(network_name, passphrase, &mut key)?;
Ok(key)
}
fn derive_into(
network_name: Option<&str>,
passphrase: Option<&str>,
key: &mut [u8; 64],
) -> Result<(), IfacError> {
let mut ifac_origin = Zeroizing::new(Vec::with_capacity(64));
if let Some(name) = network_name {
ifac_origin.extend_from_slice(&sha256(name.as_bytes()));
@@ -32,14 +50,60 @@ pub fn derive_ifac_key(
ifac_origin.extend_from_slice(&sha256(key.as_bytes()));
}
let ifac_origin_hash = sha256(&ifac_origin);
let ifac_origin_hash = Zeroizing::new(sha256(&ifac_origin));
let salt = hex_decode(IFAC_SALT).ok_or(IfacError::InvalidSalt)?;
let derived = hkdf_sha256(64, &ifac_origin_hash, Some(&salt), None)?;
let mut key = [0u8; 64];
let derived = hkdf_sha256(64, &*ifac_origin_hash, Some(&salt), None)?;
key.copy_from_slice(&derived);
Ok(key)
Ok(())
}
/// A derived IFAC key in one heap allocation, wiped when its last clone
/// drops. Clones share the allocation, so tables and queues that move or copy
/// an interface's settings never copy the key.
#[derive(Clone)]
pub struct IfacKey(Arc<Zeroizing<[u8; 64]>>);
impl IfacKey {
/// [`derive_ifac_key`], written straight into the shared allocation.
pub fn derive(network_name: Option<&str>, passphrase: Option<&str>) -> Result<Self, IfacError> {
let mut key = Arc::new(Zeroizing::new([0u8; 64]));
derive_into(
network_name,
passphrase,
Arc::get_mut(&mut key).expect("a new Arc is unique"),
)?;
Ok(Self(key))
}
}
impl From<[u8; 64]> for IfacKey {
fn from(key: [u8; 64]) -> Self {
Self(Arc::new(Zeroizing::new(key)))
}
}
impl std::ops::Deref for IfacKey {
type Target = [u8; 64];
fn deref(&self) -> &[u8; 64] {
&self.0
}
}
impl PartialEq for IfacKey {
fn eq(&self, other: &Self) -> bool {
self.0[..] == other.0[..]
}
}
impl Eq for IfacKey {}
impl std::fmt::Debug for IfacKey {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("IfacKey(<redacted>)")
}
}
/// Build the IFAC identity plus a self-signature over `SHA-256(ifac_key)`.
@@ -60,13 +124,24 @@ pub fn derive_ifac_identity(
Ok((identity, ifac_key, signature))
}
/// Split IFAC key into `(signing_key, masking_key)`, each 32 bytes.
/// The IFAC identity's signature over `SHA-256(ifac_key)`, which Python
/// publishes as an interface's `ifac_signature`.
pub fn ifac_signature(ifac_key: &[u8; 64]) -> Option<[u8; 64]> {
crate::identity::Identity::from_private_key(ifac_key)
.ok()?
.sign(&sha256(ifac_key))
}
/// Split the derived identity material into its first and second 32-byte halves.
/// They are the X25519 private bytes and Ed25519 seed, respectively.
/// IFAC packet masking uses the full 64-byte key as its HKDF salt; the first
/// half is not a separate packet-signing key.
pub fn split_ifac_key(key: &[u8; 64]) -> (&[u8], &[u8]) {
(&key[..32], &key[32..])
}
fn hex_decode(s: &str) -> Option<Vec<u8>> {
if s.len() % 2 != 0 {
if !s.len().is_multiple_of(2) {
return None;
}
(0..s.len())
@@ -79,6 +154,17 @@ fn hex_decode(s: &str) -> Option<Vec<u8>> {
mod tests {
use super::*;
#[test]
fn shared_key_matches_the_derived_bytes() {
let key = IfacKey::derive(Some("testnet"), Some("password")).unwrap();
assert_eq!(
*key,
derive_ifac_key(Some("testnet"), Some("password")).unwrap()
);
assert_eq!(key, IfacKey::from(*key));
assert_eq!(format!("{key:?}"), "IfacKey(<redacted>)");
}
#[test]
fn test_ifac_derivation_deterministic() {
let key1 = derive_ifac_key(Some("testnet"), Some("password")).unwrap();
@@ -135,5 +221,22 @@ mod tests {
let key_hash = sha256(&ifac_key);
assert!(identity.verify(&key_hash, &signature));
assert_eq!(ifac_signature(&ifac_key), Some(signature));
}
/// Upstream `Identity.from_bytes(key).sign(Identity.full_hash(key))` for
/// the `ifac_testnet_password` vector key.
#[test]
fn ifac_signature_matches_upstream() {
let key = derive_ifac_key(Some("testnet"), Some("password")).unwrap();
let expected = hex_decode(
"ce6b8bc4028852077243868e4b5f7faadb715c7a2fb75d1a211d30035f65b0c1\
fc4271ef61e91599e7bcc42723afe97503e3c432b01264185233274e3603e708",
)
.unwrap();
assert_eq!(
ifac_signature(&key).unwrap().as_slice(),
expected.as_slice()
);
}
}
@@ -5,7 +5,8 @@ use std::path::Path;
use crate::persistence;
use rmpv::Value;
/// Record of a destination learnt from a validated announce.
/// Record intended for a destination learned from a validated announce.
/// Construction and file loading do not perform announce authentication.
#[derive(Debug, Clone)]
pub struct KnownDestination {
/// Learn time as a Unix timestamp (seconds).
@@ -33,6 +34,8 @@ impl KnownDestinations {
/// Insert or refresh the entry for `dest_hash`. The `retained` flag is
/// preserved on update so a fresh announce never un-pins an entry.
/// The caller validates the announce, destination binding and key continuity;
/// this method can replace an existing key without checking them.
pub fn remember(
&mut self,
dest_hash: [u8; 16],
@@ -147,7 +150,8 @@ impl KnownDestinations {
/// Drop stale entries past `destination_timeout_secs`. `has_path` is a
/// caller-supplied path-table lookup (this crate doesn't depend on
/// rns-transport). Returns the hashes that were dropped.
/// rns-transport). Pinned entries and entries with a current path are retained.
/// Returns the hashes that were dropped.
pub fn cleanup(
&mut self,
now: f64,
+1
View File
@@ -3,6 +3,7 @@
//! Python reference: `RNS/Identity.py`, `RNS/Destination.py`.
pub mod announce;
pub mod announce_state;
pub mod destination;
pub mod identity;
pub mod ifac;
+550 -16
View File
@@ -1,34 +1,261 @@
use std::fs;
use std::io::Write;
use std::path::Path;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use zeroize::Zeroizing;
/// Write `data` to `path` via `<path>.tmp` + `rename`, fsyncing first.
mod file_lock;
mod strict;
pub use file_lock::try_lock_exclusive;
pub use strict::{
DurableCleanupOutcome, DurableCommitPhase, DurableDirectoryReceipt, DurableErrorKind,
DurableFileReceipt, DurableWriteError, StorageRisk, durable_create_dir_all, durable_reconcile,
durable_reconcile_directory, durable_reconcile_hash, durable_remove, durable_rename_directory,
durable_write, storage_risk, validate_durable_storage_directory,
};
static TEMP_FILE_COUNTER: AtomicU64 = AtomicU64::new(0);
static ATOMIC_WRITE_LOCK: Mutex<()> = Mutex::new(());
fn invalid_data(message: &'static str) -> std::io::Error {
std::io::Error::new(std::io::ErrorKind::InvalidData, message)
}
fn unique_temp_path(path: &Path) -> std::io::Result<PathBuf> {
let parent = path.parent().unwrap_or_else(|| Path::new("."));
let file_name = path.file_name().ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"atomic-write target has no file name",
)
})?;
let sequence = TEMP_FILE_COUNTER.fetch_add(1, Ordering::Relaxed);
let mut temp_name = file_name.to_os_string();
temp_name.push(format!(".tmp-{}-{sequence}", std::process::id()));
Ok(parent.join(temp_name))
}
#[cfg(not(windows))]
fn atomic_replace(source: &Path, destination: &Path) -> std::io::Result<()> {
fs::rename(source, destination)
}
#[cfg(windows)]
fn atomic_replace(source: &Path, destination: &Path) -> std::io::Result<()> {
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Storage::FileSystem::{
MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW,
};
let source: Vec<u16> = source.as_os_str().encode_wide().chain(Some(0)).collect();
let destination: Vec<u16> = destination
.as_os_str()
.encode_wide()
.chain(Some(0))
.collect();
// Same-directory temporary files keep this on one volume. MoveFileExW is
// the Windows replacement primitive; std::fs::rename rejects an existing
// destination on Windows instead of replacing it.
let replaced = unsafe {
MoveFileExW(
source.as_ptr(),
destination.as_ptr(),
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
)
};
if replaced == 0 {
Err(std::io::Error::last_os_error())
} else {
Ok(())
}
}
/// `Read::read`, retried when a signal interrupts it.
fn read_retrying(reader: &mut impl Read, buf: &mut [u8]) -> std::io::Result<usize> {
loop {
match reader.read(buf) {
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
result => return result,
}
}
}
/// Compare the file at `path` with `data`. The file is read through a stack
/// buffer that is wiped afterwards, so reading back a secret leaves no copy.
fn verify_bytes(path: &Path, data: &[u8]) -> std::io::Result<()> {
let mut file = fs::File::open(path)?;
let mut offset: usize = 0;
let mut chunk = Zeroizing::new([0u8; 8192]);
loop {
let count = read_retrying(&mut file, &mut chunk[..])?;
if count == 0 {
break;
}
let end = offset
.checked_add(count)
.filter(|end| data.get(offset..*end) == Some(&chunk[..count]))
.ok_or_else(|| invalid_data("file readback mismatch"))?;
offset = end;
}
if offset != data.len() {
return Err(invalid_data("file readback length mismatch"));
}
Ok(())
}
/// Read a secret file of at most `max_len` bytes into one buffer that is
/// allocated up front and wiped on drop, so neither growth nor a failed read
/// leaves a copy behind. A longer file is refused with `InvalidData` once
/// `max_len + 1` bytes have been read.
pub fn read_secret_file(path: &Path, max_len: usize) -> std::io::Result<Zeroizing<Vec<u8>>> {
let mut file = fs::File::open(path)?;
let mut data = Zeroizing::new(vec![0u8; max_len.saturating_add(1)]);
let mut filled = 0;
while filled < data.len() {
match read_retrying(&mut file, &mut data[filled..])? {
0 => break,
count => filled += count,
}
}
if filled > max_len {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("file exceeds {max_len}-byte limit"),
));
}
data.truncate(filled);
Ok(data)
}
/// A msgpack byte field read from a secret file. Binary and string values
/// borrow from a slice input; integer arrays fill a buffer reserved once (at
/// most `MAX` bytes) and wiped on drop, so neither growth nor a failed decode
/// leaves a copy behind.
pub(crate) enum SecretBytes<'a, const MAX: usize> {
Borrowed(&'a [u8]),
Owned(Zeroizing<Vec<u8>>),
}
impl<const MAX: usize> std::ops::Deref for SecretBytes<'_, MAX> {
type Target = [u8];
fn deref(&self) -> &[u8] {
match self {
Self::Borrowed(bytes) => bytes,
Self::Owned(bytes) => bytes,
}
}
}
impl<'de: 'a, 'a, const MAX: usize> serde::Deserialize<'de> for SecretBytes<'a, MAX> {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_bytes(SecretBytesVisitor::<MAX>)
}
}
struct SecretBytesVisitor<const MAX: usize>;
impl<'de, const MAX: usize> serde::de::Visitor<'de> for SecretBytesVisitor<MAX> {
type Value = SecretBytes<'de, MAX>;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("a byte array")
}
fn visit_borrowed_bytes<E: serde::de::Error>(self, bytes: &'de [u8]) -> Result<Self::Value, E> {
Ok(SecretBytes::Borrowed(bytes))
}
fn visit_borrowed_str<E: serde::de::Error>(self, text: &'de str) -> Result<Self::Value, E> {
Ok(SecretBytes::Borrowed(text.as_bytes()))
}
fn visit_bytes<E: serde::de::Error>(self, bytes: &[u8]) -> Result<Self::Value, E> {
Ok(SecretBytes::Owned(Zeroizing::new(bytes.to_vec())))
}
fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<Self::Value, E> {
self.visit_bytes(text.as_bytes())
}
fn visit_byte_buf<E: serde::de::Error>(self, bytes: Vec<u8>) -> Result<Self::Value, E> {
Ok(SecretBytes::Owned(Zeroizing::new(bytes)))
}
fn visit_string<E: serde::de::Error>(self, text: String) -> Result<Self::Value, E> {
self.visit_byte_buf(text.into_bytes())
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
let capacity = seq.size_hint().unwrap_or(0).min(MAX);
let mut bytes = Zeroizing::new(Vec::with_capacity(capacity));
while let Some(byte) = seq.next_element::<u8>()? {
if bytes.len() == capacity {
return Err(serde::de::Error::invalid_length(capacity + 1, &self));
}
bytes.push(byte);
}
Ok(SecretBytes::Owned(bytes))
}
}
/// Write `data` to `path` via a unique same-directory temporary file and
/// atomic rename.
///
/// On Unix the temp file is created with mode `0600` so that key material is
/// not world-readable even during the write.
/// not world-readable even during the write. The bytes are flushed, fsynced,
/// and verified before the rename, then verified again at the final path. After
/// the rename, parent-directory fsync is best-effort on Unix; its failure does
/// not fail this operation. This is not a guarantee of survival after power
/// loss. Use [`durable_write`] when the caller needs its stricter receipt and
/// recovery-path handling, subject to that helper's filesystem limits.
pub fn atomic_write(path: &Path, data: &[u8]) -> std::io::Result<()> {
let tmp_path = path.with_extension("tmp");
let _write_guard = ATOMIC_WRITE_LOCK
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let tmp_path = unique_temp_path(path)?;
{
let result = (|| {
#[cfg(unix)]
let mut f = {
use std::os::unix::fs::OpenOptionsExt;
std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.create_new(true)
.mode(0o600)
.open(&tmp_path)?
};
#[cfg(not(unix))]
let mut f = fs::File::create(&tmp_path)?;
let mut f = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp_path)?;
f.write_all(data)?;
f.flush()?;
f.sync_all()?;
drop(f);
verify_bytes(&tmp_path, data)?;
atomic_replace(&tmp_path, path)?;
verify_bytes(path, data)?;
#[cfg(unix)]
if let Some(dir) = path.parent()
&& let Ok(d) = fs::File::open(dir)
{
let _ = d.sync_all();
}
Ok(())
})();
if result.is_err() {
let _ = fs::remove_file(&tmp_path);
}
fs::rename(&tmp_path, path)?;
Ok(())
result
}
/// Read `path` in full, returning `None` if the file does not exist.
@@ -40,29 +267,336 @@ pub fn read_file(path: &Path) -> std::io::Result<Option<Vec<u8>>> {
}
}
/// Read at most `max_len` bytes from `path`.
///
/// A file larger than the supplied bound is rejected before it can be handed
/// to a deserializer. `None` means the path did not exist.
pub fn read_file_bounded(path: &Path, max_len: usize) -> std::io::Result<Option<Vec<u8>>> {
let file = match fs::File::open(path) {
Ok(file) => file,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e),
};
let mut data = Vec::with_capacity(max_len.min(4096));
file.take(max_len.saturating_add(1) as u64)
.read_to_end(&mut data)?;
if data.len() > max_len {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("file exceeds {max_len}-byte limit"),
));
}
Ok(Some(data))
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
pub(super) fn unique_test_dir(label: &str) -> PathBuf {
static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let id = NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
std::env::temp_dir().join(format!(
"reticulum-{label}-{}-{}-{id}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos()
))
}
#[test]
fn test_atomic_write_and_read() {
let dir = std::env::temp_dir().join("reticulum_test_persistence");
let _ = fs::create_dir_all(&dir);
let dir = unique_test_dir("persistence");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("test_atomic");
atomic_write(&path, b"hello world").unwrap();
let data = read_file(&path).unwrap().unwrap();
assert_eq!(data, b"hello world");
let _ = fs::remove_file(&path);
let _ = fs::remove_dir(&dir);
atomic_write(&path, b"replacement").unwrap();
let data = read_file(&path).unwrap().unwrap();
assert_eq!(
data, b"replacement",
"Windows must replace an existing state file instead of failing after the first write"
);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn test_read_nonexistent() {
let path = PathBuf::from("/tmp/reticulum_nonexistent_file_xyz");
let path = unique_test_dir("nonexistent").join("missing");
let result = read_file(&path).unwrap();
assert!(result.is_none());
}
#[test]
fn test_bounded_read_rejects_oversize_file() {
let dir = unique_test_dir("bounded-read");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("bounded");
fs::write(&path, [0xA5; 17]).unwrap();
let err = read_file_bounded(&path, 16).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
assert_eq!(read_file_bounded(&path, 17).unwrap().unwrap().len(), 17);
fs::remove_dir_all(dir).unwrap();
}
/// Root ignores directory permissions.
#[cfg(unix)]
pub(super) fn is_root() -> bool {
unsafe { libc::geteuid() == 0 }
}
/// Holds the macOS user immutable flag (`chflags uchg`) on a file.
#[cfg(target_os = "macos")]
pub(super) struct Immutable(PathBuf);
#[cfg(target_os = "macos")]
impl Immutable {
pub(super) fn new(path: &Path) -> Self {
Self::set(path, libc::UF_IMMUTABLE);
Self(path.to_path_buf())
}
fn set(path: &Path, flags: libc::c_uint) {
use std::os::unix::ffi::OsStrExt;
let path = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap();
assert_eq!(unsafe { libc::chflags(path.as_ptr(), flags) }, 0);
}
}
#[cfg(target_os = "macos")]
impl Drop for Immutable {
fn drop(&mut self) {
Self::set(&self.0, 0);
}
}
#[test]
fn atomic_write_into_a_missing_directory_fails_without_creating_it() {
let dir = unique_test_dir("atomic-missing-parent");
let err = atomic_write(&dir.join("state"), b"candidate").unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
assert!(!dir.exists());
}
#[cfg(unix)]
#[test]
fn atomic_write_in_a_read_only_directory_keeps_the_previous_file() {
use std::os::unix::fs::PermissionsExt;
if is_root() {
return;
}
let dir = unique_test_dir("atomic-read-only");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("state");
fs::write(&path, b"previous").unwrap();
fs::set_permissions(&dir, fs::Permissions::from_mode(0o500)).unwrap();
let result = atomic_write(&path, b"candidate");
fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap();
assert_eq!(
result.unwrap_err().kind(),
std::io::ErrorKind::PermissionDenied
);
assert_eq!(fs::read(&path).unwrap(), b"previous");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn atomic_write_onto_a_directory_leaves_it_and_no_temporary_file() {
let dir = unique_test_dir("atomic-directory-target");
let target = dir.join("state");
fs::create_dir_all(&target).unwrap();
fs::write(target.join("kept"), b"kept").unwrap();
assert!(atomic_write(&target, b"candidate").is_err());
assert_eq!(fs::read(target.join("kept")).unwrap(), b"kept");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_dir_all(dir).unwrap();
}
#[cfg(target_os = "macos")]
#[test]
fn atomic_write_onto_an_immutable_file_keeps_it() {
let dir = unique_test_dir("atomic-immutable");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("state");
fs::write(&path, b"previous").unwrap();
let immutable = Immutable::new(&path);
let result = atomic_write(&path, b"candidate");
drop(immutable);
assert!(result.is_err());
assert_eq!(fs::read(&path).unwrap(), b"previous");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn readback_verification_rejects_changed_short_and_long_files() {
let dir = unique_test_dir("readback");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("state");
let data: Vec<u8> = (0..20_000u32).map(|i| (i % 251) as u8).collect();
fs::write(&path, &data).unwrap();
verify_bytes(&path, &data).unwrap();
let mut changed = data.clone();
changed[12_345] ^= 1;
for (name, contents) in [
("changed", changed),
("short", data[..data.len() - 1].to_vec()),
("long", [&data[..], b"!"].concat()),
("empty", Vec::new()),
] {
fs::write(&path, contents).unwrap();
let err = verify_bytes(&path, &data).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData, "{name}");
}
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn secret_reads_are_bounded() {
let dir = unique_test_dir("secret-read");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("secret");
fs::write(&path, [0xA5; 64]).unwrap();
assert_eq!(&read_secret_file(&path, 64).unwrap()[..], &[0xA5; 64]);
assert_eq!(
read_secret_file(&path, 63).unwrap_err().kind(),
std::io::ErrorKind::InvalidData
);
fs::write(&path, b"").unwrap();
assert!(read_secret_file(&path, 64).unwrap().is_empty());
assert_eq!(
read_secret_file(&dir.join("missing"), 64)
.unwrap_err()
.kind(),
std::io::ErrorKind::NotFound
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn concurrent_atomic_writers_do_not_share_temp_paths() {
let dir = unique_test_dir("atomic-concurrent");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("state");
let mut writers = Vec::new();
for byte in 0u8..16 {
let path = path.clone();
writers.push(std::thread::spawn(move || atomic_write(&path, &[byte; 64])));
}
for writer in writers {
writer.join().unwrap().unwrap();
}
let final_data = fs::read(&path).unwrap();
assert_eq!(final_data.len(), 64);
assert!(final_data.iter().all(|byte| *byte == final_data[0]));
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_dir_all(dir).unwrap();
}
/// Feed `data` to `read` through a FIFO in two halves, signalling the
/// reading thread while it waits for the second. The handler is installed
/// without `SA_RESTART`, so that wait fails with EINTR.
#[cfg(unix)]
pub(super) fn read_through_a_signal<T: Send + 'static>(
label: &str,
data: &[u8],
read: impl FnOnce(&Path) -> std::io::Result<T> + Send + 'static,
) -> std::io::Result<T> {
use std::os::unix::ffi::OsStrExt;
extern "C" fn ignore(_: libc::c_int) {}
let dir = unique_test_dir(label);
fs::create_dir_all(&dir).unwrap();
let path = dir.join("fifo");
let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap();
unsafe {
assert_eq!(libc::mkfifo(c_path.as_ptr(), 0o600), 0);
let mut action: libc::sigaction = std::mem::zeroed();
action.sa_sigaction = ignore as extern "C" fn(libc::c_int) as libc::sighandler_t;
libc::sigemptyset(&mut action.sa_mask);
assert_eq!(
libc::sigaction(libc::SIGUSR1, &action, std::ptr::null_mut()),
0
);
}
let (thread_tx, thread_rx) = std::sync::mpsc::channel();
let reader_path = path.clone();
let reader = std::thread::spawn(move || {
thread_tx
.send(unsafe { libc::pthread_self() } as usize)
.unwrap();
read(&reader_path)
});
let thread = thread_rx.recv().unwrap() as libc::pthread_t;
let mut fifo = fs::OpenOptions::new().write(true).open(&path).unwrap();
let (first, second) = data.split_at(data.len() / 2);
fifo.write_all(first).unwrap();
for _ in 0..5 {
std::thread::sleep(std::time::Duration::from_millis(20));
unsafe { libc::pthread_kill(thread, libc::SIGUSR1) };
}
// A reader that gave up has closed its end.
let _ = fifo.write_all(second);
drop(fifo);
// Fail instead of hanging if another descriptor still holds the writer.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
while !reader.is_finished() {
assert!(
std::time::Instant::now() < deadline,
"reader of {} saw no EOF 30 s after the writer closed",
path.display()
);
std::thread::sleep(std::time::Duration::from_millis(1));
}
let result = reader.join().unwrap();
fs::remove_dir_all(dir).unwrap();
result
}
#[cfg(unix)]
#[test]
fn readback_verification_retries_an_interrupted_read() {
let data = vec![0x5a; 64];
let expected = data.clone();
let result = read_through_a_signal("verify-interrupted", &data, move |path| {
verify_bytes(path, &expected)
});
assert!(result.is_ok(), "{result:?}");
}
#[cfg(unix)]
#[test]
fn secret_file_read_retries_an_interrupted_read() {
let data = vec![0xa5; 64];
let read = read_through_a_signal("secret-read-interrupted", &data, |path| {
read_secret_file(path, 1024)
});
assert_eq!(read.unwrap()[..], data[..]);
}
}
@@ -0,0 +1,72 @@
//! Nonblocking OS file-lock portability. Android's standard-library File lock
//! implementation is unsupported on some supported toolchains; bionic flock
//! provides the same retained-open-file-description ownership on that target.
use std::fs::File;
use std::io;
/// Take an exclusive advisory lock without waiting. Retain the original file
/// for the complete protected operation; do not clone/close handles to transfer
/// ownership since duplication semantics differ by platform. Closing the owning
/// handles (including on process exit) releases the lock. Contention is
/// `WouldBlock`, and unsupported or failed backends are errors, never success.
/// Do not delete/recreate the lock file while an owner may still hold it.
pub fn try_lock_exclusive(file: &File) -> io::Result<()> {
#[cfg(target_os = "android")]
{
use std::os::fd::AsRawFd;
// SAFETY: the borrowed File keeps its descriptor alive for this call;
// flock neither takes ownership nor writes through any Rust pointer.
if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
#[cfg(not(target_os = "android"))]
file.try_lock().map_err(|error| match error {
std::fs::TryLockError::WouldBlock => {
io::Error::new(io::ErrorKind::WouldBlock, "file is locked by another owner")
}
std::fs::TryLockError::Error(error) => error,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn lock_files() -> (std::path::PathBuf, File, File) {
let path = super::super::tests::unique_test_dir("native-lock");
let first = File::create_new(&path).unwrap();
let second = File::options().read(true).write(true).open(&path).unwrap();
(path, first, second)
}
#[test]
fn native_file_lock_contends_and_releases_on_drop() {
let (path, first, second) = lock_files();
try_lock_exclusive(&first).unwrap();
assert_eq!(
try_lock_exclusive(&second).unwrap_err().kind(),
io::ErrorKind::WouldBlock
);
drop(first);
try_lock_exclusive(&second).unwrap();
drop(second);
std::fs::remove_file(path).unwrap();
}
#[cfg(unix)]
#[test]
fn native_file_lock_duplicate_keeps_exclusion_until_last_close() {
let (path, first, second) = lock_files();
try_lock_exclusive(&first).unwrap();
let retained = first.try_clone().unwrap();
drop(first);
assert_eq!(
try_lock_exclusive(&second).unwrap_err().kind(),
io::ErrorKind::WouldBlock
);
drop(retained);
try_lock_exclusive(&second).unwrap();
drop(second);
std::fs::remove_file(path).unwrap();
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,100 @@
//! Writes beyond the process file-size limit fail with EFBIG and keep the
//! previous file. Each test re-runs itself in a child with a lowered limit.
//! Spawning stays out of the unit-test binary: until a child execs it holds
//! copies of all its parent's descriptors, close-on-exec ones included, so a
//! sibling test's lock or FIFO end would outlive that test's close.
#![cfg(unix)]
use std::fs;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use rns_identity::persistence::{DurableCommitPhase, atomic_write, durable_write};
fn unique_test_dir(label: &str) -> PathBuf {
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
let dir = std::env::temp_dir().join(format!(
"reticulum-{label}-{}-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos(),
NEXT_ID.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(&dir).unwrap();
dir
}
/// Re-run `test` in a child process whose files are limited to `limit`
/// bytes, with SIGXFSZ ignored so a longer write fails with EFBIG. Returns
/// true in the child, which then runs the test body.
fn in_file_size_limited_child(test: &str, limit: u64) -> bool {
const CHILD: &str = "RNS_FILE_SIZE_LIMITED_CHILD";
if std::env::var_os(CHILD).is_some() {
unsafe {
libc::signal(libc::SIGXFSZ, libc::SIG_IGN);
let mut current = std::mem::zeroed::<libc::rlimit>();
assert_eq!(libc::getrlimit(libc::RLIMIT_FSIZE, &mut current), 0);
current.rlim_cur = limit as libc::rlim_t;
assert_eq!(libc::setrlimit(libc::RLIMIT_FSIZE, &current), 0);
}
return true;
}
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([test, "--exact", "--nocapture", "--test-threads=1"])
.env(CHILD, "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("1 passed"),
"file-size-limited child failed:\n{stdout}\n{}",
String::from_utf8_lossy(&output.stderr)
);
false
}
#[test]
fn atomic_write_beyond_the_file_size_limit_keeps_the_previous_file() {
if !in_file_size_limited_child(
"atomic_write_beyond_the_file_size_limit_keeps_the_previous_file",
4096,
) {
return;
}
let dir = unique_test_dir("atomic-file-size");
let path = dir.join("state");
fs::write(&path, b"previous").unwrap();
let err = atomic_write(&path, &[0x5a; 16384]).unwrap_err();
assert_eq!(err.raw_os_error(), Some(libc::EFBIG));
assert_eq!(fs::read(&path).unwrap(), b"previous");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn strict_write_beyond_the_file_size_limit_keeps_the_previous_file() {
if !in_file_size_limited_child(
"strict_write_beyond_the_file_size_limit_keeps_the_previous_file",
4096,
) {
return;
}
let root = unique_test_dir("durable-file-size");
let target = root.join("state");
durable_write(&target, b"old").unwrap();
let failure = durable_write(&target, &[0x5a; 16384]).unwrap_err();
assert_eq!(failure.phase, DurableCommitPhase::NotCommitted);
let source = std::error::Error::source(&failure)
.and_then(|source| source.downcast_ref::<std::io::Error>())
.unwrap();
assert_eq!(source.raw_os_error(), Some(libc::EFBIG));
assert_eq!(fs::read(&target).unwrap(), b"old");
assert_eq!(failure.recovery_paths.len(), 2);
fs::remove_dir_all(root).unwrap();
}
+424
View File
@@ -0,0 +1,424 @@
//! Private keys, derived keys and plaintext must not survive in freed heap
//! memory when identities are stored, loaded and used.
#[path = "../../rns-crypto/tests/residue/mod.rs"]
mod residue;
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use residue::{assert_no_residue, freed_by, pseudo_random, serial};
use rns_crypto::hkdf::hkdf_sha256;
use rns_crypto::sha::sha256;
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
use rns_identity::identity::Identity;
use rns_identity::ifac::derive_ifac_key;
use rns_identity::ratchet::{RatchetRing, RatchetRingFormat};
use zeroize::Zeroizing;
struct TempDir(PathBuf);
impl TempDir {
fn new(label: &str) -> Self {
static NEXT: AtomicUsize = AtomicUsize::new(0);
let path = std::env::temp_dir().join(format!(
"rns-residue-{label}-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn derived_key(private: &[u8; 32], ephemeral_public: &[u8], salt: &[u8]) -> Zeroizing<Vec<u8>> {
let private = X25519PrivateKey::from_bytes(private);
let public = X25519PublicKey::from_bytes(ephemeral_public.try_into().unwrap());
let shared = Zeroizing::new(private.exchange(&public));
hkdf_sha256(64, &*shared, Some(salt), None).unwrap()
}
#[test]
fn identity_to_file_frees_no_key() {
let _serial = serial();
let dir = TempDir::new("to-file");
let key: [u8; 64] = pseudo_random(11);
let identity = Identity::from_private_key(&key).unwrap();
let path = dir.0.join("identity");
let ((), freed) = freed_by(|| identity.to_file(&path).unwrap());
assert_no_residue(&freed, &[("private key", &key)]);
assert_eq!(std::fs::read(&path).unwrap(), key);
}
#[test]
fn identity_from_file_frees_no_key() {
let _serial = serial();
let dir = TempDir::new("from-file");
let key: [u8; 64] = pseudo_random(12);
let expected = Identity::from_private_key(&key).unwrap().hash;
let path = dir.0.join("identity");
std::fs::write(&path, key).unwrap();
let (hash, freed) = freed_by(|| Identity::from_file(&path).unwrap().hash);
assert_no_residue(&freed, &[("private key", &key)]);
assert_eq!(hash, expected);
}
#[test]
fn identity_from_file_with_a_msgpack_looking_key_frees_no_key() {
let _serial = serial();
let dir = TempDir::new("from-file-msgpack-prefix");
// A one-field array holding a long integer array: a parse of this key as
// an envelope runs out of input partway through.
let mut key = [0u8; 64];
key[..4].copy_from_slice(&[0x91, 0xdc, 0xff, 0xff]);
let tail: [u8; 60] = pseudo_random(13);
for (out, byte) in key[4..].iter_mut().zip(tail) {
*out = byte & 0x7f;
}
let expected = Identity::from_private_key(&key).unwrap().hash;
let path = dir.0.join("identity");
std::fs::write(&path, key).unwrap();
let (hash, freed) = freed_by(|| Identity::from_file(&path).unwrap().hash);
assert_no_residue(&freed, &[("private key", &key[4..])]);
assert_eq!(hash, expected);
}
#[test]
fn identity_from_envelope_file_frees_no_key() {
#[derive(serde::Serialize)]
struct Envelope {
private_key: Vec<u8>,
}
let _serial = serial();
let dir = TempDir::new("from-envelope");
let key: [u8; 64] = pseudo_random(14);
let expected = Identity::from_private_key(&key).unwrap().hash;
let envelope = Envelope {
private_key: key.to_vec(),
};
for (name, bytes) in [
("named", rmp_serde::to_vec_named(&envelope).unwrap()),
("compact", rmp_serde::to_vec(&envelope).unwrap()),
] {
let path = dir.0.join(name);
std::fs::write(&path, bytes).unwrap();
let (hash, freed) = freed_by(|| Identity::from_file(&path).unwrap().hash);
assert_no_residue(
&freed,
&[
("private key", &key),
("msgpack integers private key", &msgpack_integers(&key)),
],
);
assert_eq!(hash, expected, "{name} envelope");
}
}
#[test]
fn identity_from_file_refuses_an_oversize_file_without_reading_it_whole() {
let _serial = serial();
let dir = TempDir::new("from-file-oversize");
let path = dir.0.join("identity");
std::fs::write(&path, vec![0xc1; 1 << 20]).unwrap();
let (result, freed) = freed_by(|| Identity::from_file(&path));
assert!(result.is_err());
assert!(
freed.peak_allocation < 64 * 1024,
"loading allocated {} bytes",
freed.peak_allocation
);
}
#[test]
fn identity_encrypt_frees_no_plaintext_or_key() {
let _serial = serial();
let key: [u8; 64] = pseudo_random(15);
let identity = Identity::from_private_key(&key).unwrap();
let plaintext: [u8; 100] = pseudo_random(16);
let (ciphertext, freed) = freed_by(|| identity.encrypt(&plaintext, None).unwrap());
let derived = derived_key(
key[..32].try_into().unwrap(),
&ciphertext[..32],
&identity.hash,
);
assert_no_residue(
&freed,
&[("plaintext", &plaintext), ("derived key", &derived)],
);
}
#[test]
fn identity_decrypt_frees_no_plaintext_or_key() {
let _serial = serial();
let key: [u8; 64] = pseudo_random(17);
let identity = Identity::from_private_key(&key).unwrap();
let plaintext: [u8; 100] = pseudo_random(18);
let ciphertext = identity.encrypt(&plaintext, None).unwrap();
let derived = derived_key(
key[..32].try_into().unwrap(),
&ciphertext[..32],
&identity.hash,
);
let ((), freed) = freed_by(|| {
let decrypted = Zeroizing::new(identity.decrypt(&ciphertext, None, false).unwrap());
assert_eq!(&decrypted[..], &plaintext[..]);
});
assert_no_residue(
&freed,
&[("plaintext", &plaintext), ("derived key", &derived)],
);
}
#[test]
fn identity_ratchet_decrypt_frees_no_plaintext_or_key() {
let _serial = serial();
let key: [u8; 64] = pseudo_random(19);
let identity = Identity::from_private_key(&key).unwrap();
let ratchet: [u8; 32] = pseudo_random(20);
let ratchet_public = X25519PrivateKey::from_bytes(&ratchet)
.public_key()
.to_bytes();
let plaintext: [u8; 100] = pseudo_random(21);
let ciphertext = identity.encrypt(&plaintext, Some(&ratchet_public)).unwrap();
let derived = derived_key(&ratchet, &ciphertext[..32], &identity.hash);
let ((), freed) = freed_by(|| {
let ratchets = [&ratchet];
let decrypted = identity
.decrypt_with_ratchet_id(&ciphertext, Some(&ratchets), true)
.unwrap();
let plaintext_copy = Zeroizing::new(decrypted.plaintext);
assert_eq!(&plaintext_copy[..], &plaintext[..]);
});
assert_no_residue(
&freed,
&[
("plaintext", &plaintext),
("derived key", &derived),
("ratchet key", &ratchet),
],
);
}
#[test]
fn ratchet_ring_save_and_load_free_no_ratchet_keys() {
let _serial = serial();
let dir = TempDir::new("ratchets");
let identity = Identity::from_private_key(&pseudo_random::<64>(22)).unwrap();
let mut ring = RatchetRing::new();
for _ in 0..200 {
ring.rotate();
}
let keys = Zeroizing::new(ring.private_keys().to_vec());
let path = dir.0.join("ratchets");
let ((), saved) = freed_by(|| ring.save_verified(&path, &identity).unwrap());
let ((), read) = freed_by(|| {
let loaded = RatchetRing::load_verified(&path, &identity).unwrap();
assert_eq!(loaded.ring().private_keys(), &keys[..]);
});
let mut found = Vec::new();
for (stage, freed) in [("save", &saved), ("load", &read)] {
for residue in ratchet_key_residue(freed, &keys) {
found.push(format!("{stage}: {residue}"));
}
}
assert!(found.is_empty(), "secret residue: {found:?}");
}
#[test]
fn ifac_key_derivation_frees_no_key() {
let _serial = serial();
let passphrase = "correct horse battery staple";
let key = derive_ifac_key(Some("residue"), Some(passphrase)).unwrap();
let ((), freed) = freed_by(|| {
let derived = derive_ifac_key(Some("residue"), Some(passphrase)).unwrap();
assert_eq!(derived, key);
});
assert_no_residue(
&freed,
&[
("IFAC key", &key),
("passphrase hash", &sha256(passphrase.as_bytes())),
],
);
}
/// A key as msgpack writes it in an integer array: bytes above 0x7f carry a
/// 0xcc prefix.
fn msgpack_integers(key: &[u8]) -> Vec<u8> {
key.iter()
.flat_map(|&byte| {
if byte < 0x80 {
vec![byte]
} else {
vec![0xcc, byte]
}
})
.collect()
}
/// Ratchet keys found in freed blocks: raw, as packed in an integer array, and
/// as that packing appears again inside the file's integer array.
fn ratchet_key_residue(freed: &residue::Freed, keys: &[[u8; 32]]) -> Vec<String> {
type Encode = fn(&[u8]) -> Vec<u8>;
let forms: [(&str, Encode); 3] = [
("raw", |key| key.to_vec()),
("msgpack integers", msgpack_integers),
("nested msgpack integers", |key| {
msgpack_integers(&msgpack_integers(key))
}),
];
let mut found = Vec::new();
for (form, encode) in forms {
let encoded: Vec<Vec<u8>> = keys.iter().map(|key| encode(key)).collect();
let secrets: Vec<&[u8]> = encoded.iter().map(Vec::as_slice).collect();
let sizes: Vec<usize> = residue::find(&freed.blocks, &secrets)
.into_iter()
.map(|(len, _)| len)
.collect();
if !sizes.is_empty() {
found.push(format!(
"{form} ratchet keys in freed blocks of {sizes:?} bytes"
));
}
}
found
}
/// Releases before the canonical envelope wrote the packed ring and its keys
/// as msgpack integer arrays.
#[derive(serde::Serialize)]
struct LegacyRatchets<T> {
signature: Vec<u8>,
ratchets: Vec<u8>,
last_rotation: T,
}
fn legacy_keys(count: u64, seed: u64) -> Vec<[u8; 32]> {
(0..count).map(|i| pseudo_random(seed + i)).collect()
}
fn legacy_signature(identity: &Identity, keys: &[[u8; 32]]) -> Vec<u8> {
let current_public = X25519PrivateKey::from_bytes(&keys[0])
.public_key()
.to_bytes();
identity.sign(&current_public).unwrap().to_vec()
}
#[test]
fn legacy_ratchet_ring_load_frees_no_ratchet_keys() {
let _serial = serial();
let dir = TempDir::new("legacy-ratchets");
let identity = Identity::from_private_key(&pseudo_random::<64>(23)).unwrap();
let keys = legacy_keys(120, 1000);
let legacy = LegacyRatchets {
signature: legacy_signature(&identity, &keys),
ratchets: rmp_serde::to_vec(&keys).unwrap(),
last_rotation: 0.0,
};
let path = dir.0.join("ratchets");
std::fs::write(&path, rmp_serde::to_vec(&legacy).unwrap()).unwrap();
let ((), freed) = freed_by(|| {
let loaded = RatchetRing::load_verified(&path, &identity).unwrap();
assert_eq!(loaded.format(), RatchetRingFormat::LegacyRust);
assert_eq!(loaded.ring().private_keys(), &keys[..]);
});
let found = ratchet_key_residue(&freed, &keys);
assert!(found.is_empty(), "secret residue: {found:?}");
}
#[test]
fn failed_legacy_ratchet_ring_loads_free_no_ratchet_keys() {
let _serial = serial();
let dir = TempDir::new("legacy-ratchets-failed");
let identity = Identity::from_private_key(&pseudo_random::<64>(25)).unwrap();
// Few enough keys that the packed ring is decoded without regrowing.
let keys = legacy_keys(40, 2000);
let signature = legacy_signature(&identity, &keys);
let packed = rmp_serde::to_vec(&keys).unwrap();
assert_eq!(packed[..3], [0xdc, 0x00, 40]);
let mut short_packed = packed.clone();
short_packed[2] += 1;
let file = |signature: &[u8], ratchets: &[u8]| {
rmp_serde::to_vec(&LegacyRatchets {
signature: signature.to_vec(),
ratchets: ratchets.to_vec(),
last_rotation: 0.0,
})
.unwrap()
};
let cases = [
("short signature", file(&signature[..63], &packed)),
(
"malformed rotation",
rmp_serde::to_vec(&LegacyRatchets {
signature: signature.clone(),
ratchets: packed.clone(),
last_rotation: "never",
})
.unwrap(),
),
("missing key", file(&signature, &short_packed)),
];
let mut found = Vec::new();
for (case, bytes) in cases {
let path = dir.0.join(case.replace(' ', "-"));
std::fs::write(&path, bytes).unwrap();
let (result, freed) = freed_by(|| RatchetRing::load_verified(&path, &identity).map(drop));
assert!(result.is_err(), "{case}");
for residue in ratchet_key_residue(&freed, &keys) {
found.push(format!("{case}: {residue}"));
}
}
assert!(found.is_empty(), "secret residue: {found:?}");
}
#[test]
fn identity_from_a_truncated_envelope_frees_no_key() {
let _serial = serial();
let dir = TempDir::new("truncated-envelope");
let mut key: [u8; 64] = pseudo_random(24);
for byte in &mut key {
*byte &= 0x7f;
}
// A one-field envelope declaring 65 key bytes and ending after 64.
let path = dir.0.join("identity");
std::fs::write(&path, [&[0x91, 0xdc, 0x00, 0x41][..], &key].concat()).unwrap();
let (result, freed) = freed_by(|| Identity::from_file(&path));
assert!(result.is_err());
assert_no_residue(&freed, &[("private key", &key)]);
}
+22 -7
View File
@@ -1,16 +1,17 @@
[package]
name = "rns-interface"
description = "Network interface trait and implementations for Reticulum"
publish = false
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
license-file.workspace = true
[features]
default = []
serial = ["dep:serialport"]
rnode-tcp = []
ble = ["dep:btleplug", "dep:futures", "dep:uuid", "dep:bluer"]
ble_peer = ["ble"]
# See rns-transport's mobile-throttle. When enabled, auto-interface beacons
# and reverse-peering probes slow down in the background; BLE peer scan
# cadence adjusts to `is_foreground`. Disabled on desktop builds.
@@ -19,6 +20,7 @@ mobile-throttle = ["rns-transport/mobile-throttle"]
[dependencies]
rns-crypto = { workspace = true, features = ["std"] }
rns-wire = { workspace = true, features = ["std"] }
rns-identity = { workspace = true }
rns-transport = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }
@@ -27,28 +29,36 @@ tracing = { workspace = true }
socket2 = { workspace = true }
if-addrs = { workspace = true }
serialport = { workspace = true, optional = true }
btleplug = { version = "0.11", optional = true }
btleplug = { version = "=0.13.4", optional = true }
futures = { version = "0.3", optional = true }
uuid = { version = "1", optional = true }
rand = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
hex = { workspace = true }
md-5 = { workspace = true }
# Apple BLE Peripheral (CoreBluetooth GATT server, iOS + macOS).
# Version pinned to match btleplug's internal objc2 version so the shared
# runtime types stay binary-compatible. objc2-core-bluetooth gives us
# These native owners do not exchange Objective-C types with btleplug. Keep
# their binding generation and required features explicit. objc2-core-bluetooth gives us
# linked-symbol access to NSString constants (CBCentralManagerScanOption*,
# CB*RestoreIdentifierKey, etc.) instead of re-declaring their literal
# values, which Apple is free to change.
[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies]
objc2 = "0.5"
objc2-foundation = "0.2"
objc2-core-bluetooth = "0.2"
objc2-foundation = { version = "0.2", features = ["NSString"] }
objc2-core-bluetooth = { version = "0.2", features = ["CBAdvertisementData", "CBCentralManagerConstants"] }
[target.'cfg(target_os = "macos")'.dependencies]
libc = "0.2"
[dev-dependencies]
tokio = { workspace = true, features = ["test-util"] }
# Keepalive-tuning tests read socket options back via getsockopt.
[target.'cfg(unix)'.dev-dependencies]
libc = "0.2"
# Android JNI (BLE Peripheral, USB Serial)
[target.'cfg(target_os = "android")'.dependencies]
jni = "0.19"
@@ -67,6 +77,11 @@ bluer = { version = "0.17", features = ["bluetoothd"], optional = true }
# unavailable event so embedding UIs can direct users to an MSIX build for
# discoverability.
[target.'cfg(target_os = "windows")'.dependencies]
# Resolution floor for Tokio's socket backend: older Mio lets child processes
# inherit sockets and keep shared/network listeners alive after shutdown.
# 1.2.3 includes the no-inheritance fix and its Wine compatibility follow-up.
# https://github.com/tokio-rs/mio/pull/1946
mio = { version = "1.2.3", default-features = false }
windows = { version = "0.58", features = [
"Devices_Bluetooth",
"Devices_Bluetooth_Advertisement",
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,360 @@
//! Production descriptor selection and serial control requests for Android USB.
#[derive(Clone, Debug)]
pub(crate) struct UsbEndpointDescriptor {
pub direction: i32,
pub transfer_type: i32,
}
#[derive(Clone, Debug)]
pub(crate) struct UsbInterfaceDescriptor {
pub number: u16,
pub alternate_setting: i32,
pub class: i32,
pub subclass: i32,
pub endpoints: Vec<UsbEndpointDescriptor>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum UsbSerialKind {
Cp210x,
CdcAcm,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct UsbSerialPort {
pub kind: UsbSerialKind,
/// Positions in UsbDevice's interface array, not bInterfaceNumber.
pub data_interface: usize,
pub control_interface: usize,
/// bInterfaceNumber used as wIndex in control transfers.
pub control_number: u16,
/// Positions in the data interface's endpoint array.
pub input_endpoint: usize,
pub output_endpoint: usize,
}
fn bulk_pair(interface: &UsbInterfaceDescriptor) -> Option<(usize, usize)> {
let mut input = None;
let mut output = None;
for (index, endpoint) in interface.endpoints.iter().enumerate() {
if endpoint.transfer_type != 2 {
continue;
}
match endpoint.direction {
0x80 if input.is_none() => input = Some(index),
0x00 if output.is_none() => output = Some(index),
_ => return None,
}
}
Some((input?, output?))
}
pub(crate) fn select_serial_port(
vendor_id: i32,
product_id: i32,
interfaces: &[UsbInterfaceDescriptor],
) -> Result<UsbSerialPort, String> {
// Heltec V3 uses the standard CP2102/CP2102N VID/PID. Do not apply
// Silicon Labs requests to every vendor-specific interface or VID.
let cp210x = vendor_id == 0x10c4 && product_id == 0xea60;
let mut candidates = interfaces
.iter()
.enumerate()
.filter_map(|(index, interface)| {
if interface.alternate_setting != 0
|| interface.class != if cp210x { 0xff } else { 0x0a }
{
return None;
}
bulk_pair(interface).map(|pair| (index, pair))
});
let (data_interface, (input_endpoint, output_endpoint)) =
candidates.next().ok_or_else(|| {
"No supported USB serial interface with bulk IN and OUT endpoints".to_string()
})?;
if candidates.next().is_some() {
return Err("Multiple USB serial data interfaces are unsupported".into());
}
let control_interface = if cp210x {
data_interface
} else {
// A single CDC-ACM function is unambiguous even when unrelated JTAG
// or other interfaces precede it. Multi-port CDC needs a union/IAD
// association parser; never guess a control interface for it.
let mut controls = interfaces.iter().enumerate().filter(|(_, interface)| {
interface.alternate_setting == 0
&& interface.class == 0x02
&& interface.subclass == 0x02
});
let (index, _) = controls
.next()
.ok_or_else(|| "No CDC-ACM control interface found".to_string())?;
if controls.next().is_some() {
return Err("Multiple CDC-ACM control interfaces are unsupported".into());
}
index
};
Ok(UsbSerialPort {
kind: if cp210x {
UsbSerialKind::Cp210x
} else {
UsbSerialKind::CdcAcm
},
data_interface,
control_interface,
control_number: interfaces[control_interface].number,
input_endpoint,
output_endpoint,
})
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct UsbControlRequest<'a> {
pub request_type: u8,
pub request: u8,
pub value: u16,
pub index: u16,
pub payload: &'a [u8],
}
pub(crate) fn configure_serial_port(
port: &UsbSerialPort,
baud_rate: u32,
mut transfer: impl FnMut(&UsbControlRequest<'_>) -> Result<i32, String>,
) -> Result<(), String> {
if baud_rate == 0 {
return Err("USB serial baud rate must be nonzero".into());
}
let request_type = match port.kind {
UsbSerialKind::Cp210x => 0x41,
UsbSerialKind::CdcAcm => 0x21,
};
let mut send = |request, value, payload: &[u8]| {
let setup = UsbControlRequest {
request_type,
request,
value,
index: port.control_number,
payload,
};
let transferred = transfer(&setup)
.map_err(|error| format!("USB serial setup request 0x{request:02x}: {error}"))?;
if transferred != payload.len() as i32 {
return Err(format!(
"USB serial setup request 0x{request:02x} transferred {transferred} bytes; expected {}",
payload.len()
));
}
Ok(())
};
match port.kind {
UsbSerialKind::Cp210x => {
// Silicon Labs AN571 sections 5.1, 5.5, 5.7, 5.9, 5.11 and
// tables 9-11: https://www.silabs.com/documents/public/application-notes/AN571.pdf
send(0x00, 0x0001, &[])?; // IFC_ENABLE must precede other requests.
send(0x1e, 0, &baud_rate.to_le_bytes())?;
send(0x03, 0x0800, &[])?; // 8 data bits, no parity, 1 stop bit.
// Static DTR/RTS active, no CTS/DSR/DCD or XON/XOFF handshake,
// no NULL stripping or inserted characters. Thresholds unused.
let mut flow = [0u8; 16];
flow[0..4].copy_from_slice(&1u32.to_le_bytes());
flow[4..8].copy_from_slice(&0x40u32.to_le_bytes());
send(0x13, 0, &flow)?;
// Set both lines together, with both write masks. No reset pulse
// or one-line transition to ESP download mode is requested.
// https://docs.espressif.com/projects/esptool/en/latest/esp32s3/advanced-topics/boot-mode-selection.html
send(0x07, 0x0303, &[])?;
}
UsbSerialKind::CdcAcm => {
let mut line_coding = [0u8; 7];
line_coding[..4].copy_from_slice(&baud_rate.to_le_bytes());
line_coding[6] = 8;
send(0x20, 0, &line_coding)?; // SET_LINE_CODING, 8N1.
send(0x22, 3, &[])?; // SET_CONTROL_LINE_STATE, DTR and RTS.
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn interface(
number: u16,
class: i32,
subclass: i32,
endpoints: &[(i32, i32)],
) -> UsbInterfaceDescriptor {
UsbInterfaceDescriptor {
number,
alternate_setting: 0,
class,
subclass,
endpoints: endpoints
.iter()
.map(|&(direction, transfer_type)| UsbEndpointDescriptor {
direction,
transfer_type,
})
.collect(),
}
}
fn cp210x() -> UsbSerialPort {
select_serial_port(
0x10c4,
0xea60,
&[interface(4, 0xff, 0, &[(0x80, 2), (0, 2)])],
)
.unwrap()
}
#[test]
fn cp210x_setup_is_scoped_and_uses_vendor_requests_without_reset() {
let descriptors = [interface(4, 0xff, 0, &[(0x80, 2), (0, 2)])];
for (vid, pid) in [
(0x10c4, 0xea61),
(0x0403, 0x6001),
(0x1a86, 0x7523),
(0x303a, 0x1001),
] {
assert!(select_serial_port(vid, pid, &descriptors).is_err());
}
let mut requests = Vec::new();
configure_serial_port(&cp210x(), 115_200, |request| {
requests.push((
request.request_type,
request.request,
request.value,
request.index,
request.payload.to_vec(),
));
Ok(request.payload.len() as i32)
})
.unwrap();
assert_eq!(
requests,
vec![
(0x41, 0x00, 1, 4, vec![]),
(0x41, 0x1e, 0, 4, vec![0x00, 0xc2, 0x01, 0x00]),
(0x41, 0x03, 0x0800, 4, vec![]),
(
0x41,
0x13,
0,
4,
vec![1, 0, 0, 0, 0x40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
),
(0x41, 0x07, 0x0303, 4, vec![]),
]
);
}
#[test]
fn cdc_uses_actual_control_number_and_only_bulk_endpoints() {
let port = select_serial_port(
0x303a,
0x1001,
&[
interface(0, 0xff, 0, &[(0x80, 2), (0, 2)]), // JTAG, not CDC.
interface(6, 0x02, 0x02, &[(0x80, 3)]),
interface(7, 0x0a, 0, &[(0x80, 3), (0x80, 2), (0, 2), (0, 3)]),
],
)
.unwrap();
assert_eq!(port.data_interface, 2);
assert_eq!(port.control_interface, 1);
assert_eq!((port.input_endpoint, port.output_endpoint), (1, 2));
let mut requests = Vec::new();
configure_serial_port(&port, 9_600, |request| {
requests.push((
request.request_type,
request.request,
request.value,
request.index,
request.payload.to_vec(),
));
Ok(request.payload.len() as i32)
})
.unwrap();
assert_eq!(
requests,
vec![
(0x21, 0x20, 0, 6, vec![0x80, 0x25, 0, 0, 0, 0, 8]),
(0x21, 0x22, 3, 6, vec![]),
]
);
}
#[test]
fn selection_rejects_incomplete_ambiguous_and_nonbulk_interfaces() {
let control = interface(0, 2, 2, &[(0x80, 3)]);
let data = interface(1, 0x0a, 0, &[(0x80, 2), (0, 2)]);
for descriptors in [
vec![data.clone()],
vec![control.clone(), interface(1, 0x0a, 0, &[(0x80, 3), (0, 3)])],
vec![
control.clone(),
interface(1, 0x0a, 0, &[(0x80, 2)]),
interface(2, 0x0a, 0, &[(0, 2)]),
],
vec![control.clone(), data.clone(), interface(2, 2, 2, &[])],
vec![
control.clone(),
data.clone(),
interface(2, 0x0a, 0, &[(0x80, 2), (0, 2)]),
],
vec![
control.clone(),
interface(1, 0x0a, 0, &[(0x80, 2), (0, 2), (0, 2)]),
],
] {
assert!(select_serial_port(0x303a, 0x1001, &descriptors).is_err());
}
let mut alternate = data.clone();
alternate.alternate_setting = 1;
assert!(select_serial_port(0x303a, 0x1001, &[control, alternate]).is_err());
}
#[test]
fn setup_stops_on_every_failed_short_or_impossible_control_completion() {
let cdc = select_serial_port(
0x303a,
0x1001,
&[
interface(0, 2, 2, &[]),
interface(1, 0x0a, 0, &[(0x80, 2), (0, 2)]),
],
)
.unwrap();
for (port, count) in [(cp210x(), 5), (cdc, 2)] {
for fail_at in 0..count {
for failure in 0..4 {
let mut called = 0;
let result = configure_serial_port(&port, 115_200, |request| {
let index = called;
called += 1;
let length = request.payload.len() as i32;
if index != fail_at {
return Ok(length);
}
match failure {
0 => Err("JNI exception".into()),
1 => Ok(-1),
2 => Ok(length - 1),
_ => Ok(length + 1),
}
});
assert!(result.is_err());
assert_eq!(called, fail_at + 1);
}
}
}
assert!(
configure_serial_port(&cp210x(), 0, |_| panic!("invalid baud must not touch USB"))
.is_err()
);
}
}
+259 -139
View File
@@ -1,9 +1,12 @@
//! Automatic peer discovery over IPv6 link-local multicast.
//! Automatic peer discovery over IPv6 multicast, using link scope by default.
//!
//! Beacons go to a multicast group derived from `SHA-256(group_id)` every
//! ~1.6 s; data flows over unicast UDP. Peers age out after 22 s of silence.
//! Beacons use a group derived from `SHA-256(group_id)`; data uses unicast UDP.
//! The normal beacon interval is 1.6 seconds. With `mobile-throttle`, background
//! beacons use 8 seconds. Periodic maintenance removes peers after at least
//! 22 seconds without a beacon.
use std::collections::{HashMap, VecDeque};
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::collections::{HashMap, HashSet, VecDeque};
use std::net::{Ipv6Addr, SocketAddr, SocketAddrV6};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};
@@ -19,7 +22,7 @@ use rns_transport::messages::{InboundPacket, TransportMessage};
pub const DISCOVERY_PORT: u16 = 29716;
pub const DATA_PORT: u16 = 42671;
pub const BEACON_INTERVAL: f64 = 1.6;
/// Background beacon — slow enough to save battery, still inside expiry window.
/// Background beacon interval with feature `mobile-throttle`, in seconds.
pub const BEACON_INTERVAL_BG: f64 = 8.0;
pub const PEER_EXPIRY: f64 = 22.0;
pub const HW_MTU: u32 = 1196;
@@ -157,23 +160,20 @@ impl std::fmt::Display for McastAddrType {
}
}
/// Async events from `spawn_auto_interface`; forwarded to Tauri broadcasts.
/// Async events from AutoInterface instances for embedding applications.
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum AutoInterfaceEvent {
/// `IPV6_JOIN_GROUP` was rejected by the OS. On Apple this is the
/// canonical signal for missing `com.apple.developer.networking.multicast`
/// entitlement (free dev team can't sign it). On Linux it usually means
/// the interface vanished between enumeration and join.
/// `IPV6_JOIN_GROUP` was rejected by the OS. `reason` contains the reported
/// error; this event alone does not establish a permission or network cause.
JoinFailed {
interface_name: String,
ifname: String,
reason: String,
},
/// Carrier state changed — multicast echoes started or stopped arriving
/// on `ifname` within `MCAST_ECHO_TIMEOUT`. `ok=false` is the trip-wire
/// for Windows Public-profile firewall block, bridged-AP reboot, or
/// general IPv6 multicast suppression. `reason` is human-readable.
/// Carrier state changed as local multicast echoes arrived or timed out on
/// `ifname`. `ok=false` reports missing echoes within `MCAST_ECHO_TIMEOUT`;
/// it does not identify the underlying network or firewall cause.
CarrierState {
interface_name: String,
ifname: String,
@@ -293,7 +293,8 @@ impl MultiIfDedup {
}
}
/// Record the packet and return whether it was already seen within TTL.
/// Return whether this packet hash is still in the bounded TTL cache. New
/// hashes are recorded; a duplicate does not refresh its timestamp.
pub fn is_duplicate(&mut self, data: &[u8]) -> bool {
let hash = rns_crypto::sha::sha256(data);
let now = Instant::now();
@@ -330,7 +331,9 @@ impl Default for MultiIfDedup {
}
}
/// Verify a beacon against `SHA-256(group_id + peer_addr_string)`.
/// Compare the first 32 beacon bytes with `SHA-256(group_id + peer_addr_string)`.
/// Shorter inputs fail; trailing bytes are ignored. This shared-group digest
/// does not authenticate a peer identity.
pub fn verify_beacon(beacon: &[u8], group_id: &str, peer_addr: &Ipv6Addr) -> bool {
if beacon.len() < 32 {
return false;
@@ -507,7 +510,9 @@ pub struct NetworkInterfaceInfo {
pub is_loopback: bool,
}
/// Enumerate all host NICs (including loopback / ignored). Callers filter on top.
/// Enumerate addresses reported by the host and group them by NIC name,
/// including loopback and normally ignored names. Callers apply filters.
/// `is_up` means an address was found; it is not a carrier or reachability test.
pub fn list_network_interfaces() -> Result<Vec<NetworkInterfaceInfo>, String> {
use std::collections::BTreeMap;
@@ -579,10 +584,10 @@ fn iface_passes_filters(
if ignored_devices.iter().any(|n| n == iface_name) {
return false;
}
if let Some(allowed) = devices {
if !allowed.iter().any(|n| n == iface_name) {
return false;
}
if let Some(allowed) = devices
&& !allowed.iter().any(|n| n == iface_name)
{
return false;
}
true
}
@@ -623,19 +628,19 @@ fn get_link_local_addrs(
if !iface_passes_filters(&iface.name, devices, ignored_devices) {
continue;
}
if let std::net::IpAddr::V6(addr) = iface.addr.ip() {
if (addr.segments()[0] & 0xffc0) == 0xfe80 {
let scope_id = iface_scope_id(&iface);
if scope_id == 0 {
tracing::warn!(
iface = %iface.name,
addr = %addr,
"skipping link-local: could not resolve scope id (would send on wrong NIC)"
);
continue;
}
result.push((iface.name.clone(), addr, scope_id));
if let std::net::IpAddr::V6(addr) = iface.addr.ip()
&& (addr.segments()[0] & 0xffc0) == 0xfe80
{
let scope_id = iface_scope_id(&iface);
if scope_id == 0 {
tracing::warn!(
iface = %iface.name,
addr = %addr,
"skipping link-local: could not resolve scope id (would send on wrong NIC)"
);
continue;
}
result.push((iface.name.clone(), addr, scope_id));
}
}
}
@@ -1021,6 +1026,17 @@ fn hex_prefix(bytes: &[u8], n: usize) -> String {
s
}
fn multicast_join_candidates(
link_locals: &[(String, Ipv6Addr, u32)],
joined_memberships: &HashSet<(String, u32)>,
) -> Vec<(String, Ipv6Addr, u32)> {
link_locals
.iter()
.filter(|(ifname, _, scope_id)| !joined_memberships.contains(&(ifname.clone(), *scope_id)))
.cloned()
.collect()
}
/// Spawn the auto-discovery interface.
pub async fn spawn_auto_interface(
config: AutoInterfaceConfig,
@@ -1028,6 +1044,8 @@ pub async fn spawn_auto_interface(
transport_tx: mpsc::Sender<TransportMessage>,
is_foreground: Arc<AtomicBool>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let mcast_group = derive_multicast_address(
&config.group_id,
config.discovery_scope,
@@ -1070,6 +1088,8 @@ pub async fn spawn_auto_interface(
})?);
tracing::info!(name = %config.name, port = config.discovery_port, "auto discovery socket bound");
let mut joined_memberships: HashSet<(String, u32)> = HashSet::new();
let mut reported_join_failures: HashSet<(String, u32)> = HashSet::new();
for (iface_name, _ll_addr, scope_id) in &initial_link_locals {
if let Err(e) = set_multicast_if_v6(disc_sock.as_ref(), *scope_id) {
tracing::warn!(
@@ -1080,28 +1100,33 @@ pub async fn spawn_auto_interface(
"failed to set IPv6 multicast outbound interface"
);
}
if let Err(e) = disc_sock.join_multicast_v6(&mcast_group, *scope_id) {
// EPERM/EACCES on Apple is the canonical signal that the
// multicast networking entitlement isn't provisioned (e.g. iOS
// PermissionDenied covers EPERM/EACCES/Windows ERROR_ACCESS_DENIED.
// Surfaced as an event so UIs can show pending Apple approval.
if e.kind() == std::io::ErrorKind::PermissionDenied {
tracing::warn!(
iface = %iface_name,
error = %e,
"multicast join denied by OS — entitlement / firewall / capability missing"
);
dispatch_auto_event(AutoInterfaceEvent::JoinFailed {
interface_name: config.name.clone(),
ifname: iface_name.clone(),
reason: format!("os_permission_denied: {e}"),
});
} else {
tracing::debug!(
iface = %iface_name,
error = %e,
"failed to join multicast group"
);
match disc_sock.join_multicast_v6(&mcast_group, *scope_id) {
Ok(()) => {
joined_memberships.insert((iface_name.clone(), *scope_id));
}
Err(e) => {
// iOS can reject the first operation while Local Network
// authorization is being resolved. Keep the interface alive;
// the jobs task retries missing memberships periodically.
if e.kind() == std::io::ErrorKind::PermissionDenied {
reported_join_failures.insert((iface_name.clone(), *scope_id));
tracing::warn!(
iface = %iface_name,
error = %e,
"multicast join denied by OS — permission, entitlement, firewall, or capability missing"
);
dispatch_auto_event(AutoInterfaceEvent::JoinFailed {
interface_name: config.name.clone(),
ifname: iface_name.clone(),
reason: format!("os_permission_denied: {e}"),
});
} else {
tracing::debug!(
iface = %iface_name,
error = %e,
"failed to join multicast group"
);
}
}
}
}
@@ -1199,12 +1224,17 @@ pub async fn spawn_auto_interface(
let disc_sock_recv = disc_sock.clone();
tokio::spawn(async move {
let mut buf = [0u8; 256];
// Python's read loops swallow exceptions and keep serving; Linux
// surfaces transient async errors (ICMP unreachable) via recv_from,
// so only sustained failure may kill the loop.
let mut consecutive_errors = 0u32;
loop {
if !online_d.load(Ordering::SeqCst) {
break;
}
match disc_sock_recv.recv_from(&mut buf).await {
Ok((n, src)) => {
consecutive_errors = 0;
if n < 32 {
tracing::debug!(src = %src, n, "auto-instr mcast RX too short");
continue;
@@ -1220,20 +1250,21 @@ pub async fn spawn_auto_interface(
.map(|(name, _, _)| name.clone())
};
let is_self = self_iface.is_some();
let received_hash = hex32(&buf[..32]);
let expected = make_beacon(&auth_group_id, &peer_ip);
let expected_hex = hex32(&expected);
let match_ok = expected[..] == buf[..32];
tracing::debug!(
src = %src_v6,
scope_id = src_v6.scope_id(),
n,
is_self,
recv_hash = %received_hash,
expected_hash = %expected_hex,
match_ok,
"auto-instr mcast RX"
);
// Hash hex strings only materialize when debug is on.
if tracing::enabled!(tracing::Level::DEBUG) {
tracing::debug!(
src = %src_v6,
scope_id = src_v6.scope_id(),
n,
is_self,
recv_hash = %hex32(&buf[..32]),
expected_hash = %hex32(&expected),
match_ok,
"auto-instr mcast RX"
);
}
if let Some(ifname) = self_iface {
// Self-echo: carrier confirmed; record for jobs task.
let mut echoes = disc_echoes.lock().await;
@@ -1267,8 +1298,12 @@ pub async fn spawn_auto_interface(
}
}
Err(e) => {
tracing::warn!(error = %e, "auto discovery recv error");
break;
consecutive_errors += 1;
tracing::warn!(error = %e, consecutive_errors, "auto discovery recv error");
if consecutive_errors >= 50 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
}
@@ -1300,12 +1335,14 @@ pub async fn spawn_auto_interface(
let urecv_link_locals = unicast_link_locals.clone();
tokio::spawn(async move {
let mut buf = [0u8; 256];
let mut consecutive_errors = 0u32;
loop {
if !urecv_online.load(Ordering::SeqCst) {
break;
}
match urecv_sock.recv_from(&mut buf).await {
Ok((n, src)) => {
consecutive_errors = 0;
if n < 32 {
continue;
}
@@ -1341,8 +1378,16 @@ pub async fn spawn_auto_interface(
}
}
Err(e) => {
tracing::debug!(error = %e, "auto unicast discovery recv error");
break;
consecutive_errors += 1;
tracing::debug!(
error = %e,
consecutive_errors,
"auto unicast discovery recv error"
);
if consecutive_errors >= 50 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
}
@@ -1381,39 +1426,52 @@ pub async fn spawn_auto_interface(
}
let snapshot = { rev_link_locals.lock().await.clone() };
let now = Instant::now();
let mut table = rev_peers.lock().await;
for (_key, peer) in table.iter_mut() {
if now.duration_since(peer.last_reverse).as_secs_f64()
>= REVERSE_PEERING_INTERVAL
{
let mut targets: Vec<_> = snapshot
.iter()
.filter(|(_, _, scope_id)| {
peer.scope_id == 0 || *scope_id == peer.scope_id
})
.collect();
if targets.is_empty() {
targets = snapshot.iter().collect();
// Snapshot due peers under a short lock; sends happen lock-free
// so discovery/data tasks aren't stalled by the fan-out.
let due: Vec<(PeerKey, Peer)> = {
let table = rev_peers.lock().await;
table
.iter()
.filter(|(_, peer)| {
now.duration_since(peer.last_reverse).as_secs_f64()
>= REVERSE_PEERING_INTERVAL
})
.map(|(key, peer)| (*key, peer.clone()))
.collect()
};
for (_, peer) in &due {
let mut targets: Vec<_> = snapshot
.iter()
.filter(|(_, _, scope_id)| peer.scope_id == 0 || *scope_id == peer.scope_id)
.collect();
if targets.is_empty() {
targets = snapshot.iter().collect();
}
for (_name, ll_addr, scope_id) in targets {
let beacon = make_beacon(&rev_group_id, ll_addr);
let dest =
SocketAddrV6::new(*peer.addr.ip(), unicast_disc_port, 0, *scope_id);
if let Err(e) = unicast_sock.send_to(&beacon, dest).await {
tracing::debug!(
peer = %peer.ip,
peer_ifname = %peer.ifname,
peer_scope_id = peer.scope_id,
local_iface = %_name,
local_scope_id = scope_id,
dst = %dest,
error = %e,
raw_os_error = ?e.raw_os_error(),
"auto: reverse peering TX failed"
);
}
for (_name, ll_addr, scope_id) in targets {
let beacon = make_beacon(&rev_group_id, ll_addr);
let dest =
SocketAddrV6::new(*peer.addr.ip(), unicast_disc_port, 0, *scope_id);
if let Err(e) = unicast_sock.send_to(&beacon, dest).await {
tracing::debug!(
peer = %peer.ip,
peer_ifname = %peer.ifname,
peer_scope_id = peer.scope_id,
local_iface = %_name,
local_scope_id = scope_id,
dst = %dest,
error = %e,
raw_os_error = ?e.raw_os_error(),
"auto: reverse peering TX failed"
);
}
}
}
if !due.is_empty() {
let mut table = rev_peers.lock().await;
for (key, _) in &due {
if let Some(peer) = table.get_mut(key) {
peer.last_reverse = now;
}
peer.last_reverse = now;
}
}
}
@@ -1476,7 +1534,9 @@ pub async fn spawn_auto_interface(
"AutoInterface link-local set changed"
);
}
for (ifname, addr, scope_id) in &added {
let join_candidates = multicast_join_candidates(&new_set, &joined_memberships);
for (ifname, addr, scope_id) in &join_candidates {
let membership = (ifname.clone(), *scope_id);
if let Err(e) = set_multicast_if_v6(jobs_disc_sock.as_ref(), *scope_id) {
tracing::warn!(
iface = %jobs_iface_name,
@@ -1489,32 +1549,50 @@ pub async fn spawn_auto_interface(
);
}
match jobs_disc_sock.join_multicast_v6(&jobs_mcast, *scope_id) {
Ok(()) => tracing::info!(
iface = %jobs_iface_name,
nic = %ifname,
addr = %addr,
scope_id,
"AutoInterface joined multicast on new NIC"
),
Ok(()) => {
joined_memberships.insert(membership.clone());
reported_join_failures.remove(&membership);
tracing::info!(
iface = %jobs_iface_name,
nic = %ifname,
addr = %addr,
scope_id,
"AutoInterface joined multicast on NIC"
);
}
Err(e) => {
if e.kind() == std::io::ErrorKind::PermissionDenied {
let first_report = reported_join_failures.insert(membership);
if first_report && e.kind() == std::io::ErrorKind::PermissionDenied {
dispatch_auto_event(AutoInterfaceEvent::JoinFailed {
interface_name: jobs_iface_name.clone(),
ifname: ifname.clone(),
reason: format!("os_permission_denied: {e}"),
});
}
tracing::warn!(
iface = %jobs_iface_name,
nic = %ifname,
error = %e,
"AutoInterface multicast join failed on new NIC"
);
if first_report {
tracing::warn!(
iface = %jobs_iface_name,
nic = %ifname,
error = %e,
"AutoInterface multicast join failed; will retry"
);
} else {
tracing::debug!(
iface = %jobs_iface_name,
nic = %ifname,
error = %e,
"AutoInterface multicast join retry failed"
);
}
}
}
}
for (ifname, _addr, scope_id) in &removed {
let _ = jobs_disc_sock.leave_multicast_v6(&jobs_mcast, *scope_id);
let membership = (ifname.clone(), *scope_id);
if joined_memberships.remove(&membership) {
let _ = jobs_disc_sock.leave_multicast_v6(&jobs_mcast, *scope_id);
}
reported_join_failures.remove(&membership);
jobs_echoes.lock().await.remove(ifname);
carrier_state.remove(ifname);
}
@@ -1572,32 +1650,46 @@ pub async fn spawn_auto_interface(
tokio::spawn(async move {
while let Some(data) = rx.recv().await {
let len = data.len();
let prefix = hex_prefix(&data, 16);
let table = peers_write.lock().await;
let peer_count = table.len();
if peer_count == 0 {
// Hex prefix only materializes when debug logging is active; the
// error path below recomputes it (errors are rare).
let debug_enabled = tracing::enabled!(tracing::Level::DEBUG);
let prefix = if debug_enabled {
hex_prefix(&data, 16)
} else {
String::new()
};
// Snapshot under a short lock so the discovery/jobs tasks are not
// blocked while we await per-peer sends.
let targets: Vec<Peer> = {
let table = peers_write.lock().await;
table.values().cloned().collect()
};
let peer_count = targets.len();
if peer_count == 0 && debug_enabled {
tracing::debug!(
len,
prefix = %prefix,
"auto-instr data TX skipped: no discovered peers"
);
}
for (_key, peer) in table.iter() {
for peer in &targets {
let res = data_sock_w.send_to(&data, peer.addr).await;
match res {
Ok(n) => {
tracing::debug!(
peer = %peer.ip,
ifname = %peer.ifname,
scope_id = peer.scope_id,
scope_source = ?peer.scope_source,
dst = %peer.addr,
len,
sent_bytes = n,
prefix = %prefix,
peer_count,
"auto-instr data TX"
);
if debug_enabled {
tracing::debug!(
peer = %peer.ip,
ifname = %peer.ifname,
scope_id = peer.scope_id,
scope_source = ?peer.scope_source,
dst = %peer.addr,
len,
sent_bytes = n,
prefix = %prefix,
peer_count,
"auto-instr data TX"
);
}
task_txb.fetch_add(len as u64, Ordering::Relaxed);
}
Err(e) => {
@@ -1608,7 +1700,7 @@ pub async fn spawn_auto_interface(
scope_source = ?peer.scope_source,
dst = %peer.addr,
len,
prefix = %prefix,
prefix = %hex_prefix(&data, 16),
peer_count,
error = %e,
raw_os_error = ?e.raw_os_error(),
@@ -1625,9 +1717,11 @@ pub async fn spawn_auto_interface(
let dedup = Arc::new(Mutex::new(MultiIfDedup::new()));
let read_task = tokio::spawn(async move {
let mut buf = [0u8; 2048];
let mut consecutive_errors = 0u32;
loop {
match data_sock.recv_from(&mut buf).await {
Ok((n, _src)) => {
consecutive_errors = 0;
if n == 0 {
continue;
}
@@ -1658,8 +1752,12 @@ pub async fn spawn_auto_interface(
}
}
Err(e) => {
tracing::warn!(error = %e, "auto data recv error");
break;
consecutive_errors += 1;
tracing::warn!(error = %e, consecutive_errors, "auto data recv error");
if consecutive_errors >= 50 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
}
@@ -1670,6 +1768,8 @@ pub async fn spawn_auto_interface(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(1196, 1196, true),
parent_id: None,
name,
mode,
@@ -1684,6 +1784,7 @@ pub async fn spawn_auto_interface(
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: None,
tx,
read_task,
})
@@ -1711,6 +1812,26 @@ mod tests {
assert_eq!(group.segments()[7], 0x31e1);
}
#[test]
fn multicast_join_candidates_retries_unchanged_missing_membership() {
let en0_addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
let en1_addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
let link_locals = vec![
("en0".to_string(), en0_addr, 4),
("en1".to_string(), en1_addr, 7),
];
let joined = HashSet::from([("en0".to_string(), 4)]);
assert_eq!(
multicast_join_candidates(&link_locals, &joined),
vec![("en1".to_string(), en1_addr, 7)]
);
assert_eq!(
multicast_join_candidates(&link_locals, &HashSet::new()),
link_locals
);
}
#[test]
fn test_derive_multicast_address_all_scopes() {
// High u16 = 0xff_T_S; bytes 2-13 of SHA-256("reticulum") fill the body.
@@ -1950,7 +2071,6 @@ mod tests {
#[test]
fn test_constants() {
assert_eq!(HW_MTU, 1196);
const { assert!(FIXED_MTU) };
assert_eq!(DISCOVERY_PORT, 29716);
assert_eq!(DATA_PORT, 42671);
assert_eq!(UNICAST_DISCOVERY_PORT, 29717);
+69 -63
View File
@@ -1,5 +1,7 @@
//! AX.25-over-KISS — prepends a UI header (src/dst call+SSID) and strips on RX.
#[cfg(feature = "serial")]
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
#[cfg(feature = "serial")]
use std::sync::Arc;
#[cfg(feature = "serial")]
@@ -56,6 +58,10 @@ pub struct AX25KISSConfig {
/// Honour CMD_READY from TNC.
pub flow_control: bool,
pub mode: InterfaceMode,
/// Serial line params in Python config form (converted at open).
pub data_bits: u8,
pub parity: String,
pub stop_bits: u8,
}
impl AX25KISSConfig {
@@ -74,6 +80,9 @@ impl AX25KISSConfig {
slottime: 20,
flow_control: false,
mode: InterfaceMode::Full,
data_bits: 8,
parity: "N".to_string(),
stop_bits: 1,
}
}
@@ -91,10 +100,12 @@ impl AX25KISSConfig {
}
}
/// 16-byte AX.25 UI header (AX.25 v2.2 §3.12):
/// Build a 16-byte UI header:
/// `dst_call(6) | dst_ssid(1) | src_call(6) | src_ssid(1) | CTRL | PID`.
/// Callsign bytes left-shifted 1, space-padded to 6. SSID = `0x60 | (ssid<<1)`;
/// src SSID also sets end-of-address bit.
/// At most six input callsign bytes are copied and left-shifted by one; unused
/// positions are filled with literal `0x20`. SSID is `0x60 | (ssid << 1)`;
/// the source SSID also sets the end-of-address bit. This helper does not
/// validate callsigns or SSID ranges.
pub fn build_ax25_header(
dst_call: &[u8],
dst_ssid: u8,
@@ -142,7 +153,8 @@ pub fn frame_ax25_kiss(
kiss::frame(&payload)
}
/// Payload after the 16-byte header, or `None` if too short.
/// Return bytes after the fixed 16-byte header, or `None` for frames of
/// 16 bytes or fewer. Addresses, control, and PID are not validated.
pub fn strip_ax25_header(data: &[u8]) -> Option<&[u8]> {
if data.len() > AX25_HEADER_SIZE {
Some(&data[AX25_HEADER_SIZE..])
@@ -183,9 +195,6 @@ pub fn build_ax25_kiss_init(config: &AX25KISSConfig) -> Vec<u8> {
#[cfg(feature = "serial")]
const AX25_READ_TIMEOUT_MS: u64 = 100;
#[cfg(feature = "serial")]
const FLOW_CONTROL_TIMEOUT_SECS: u64 = 5;
/// Parse `"CALL-SSID"` or `"CALL"`; uppercased call, SSID defaults to 0.
pub fn parse_callsign_ssid(input: &str) -> Result<(String, u8), String> {
let (call_part, ssid) = if let Some(idx) = input.rfind('-') {
@@ -228,19 +237,24 @@ pub async fn spawn_ax25kiss_interface(
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
config.validate().map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("ax25kiss config: {}", e))
})?;
let port = serialport::new(&config.port, config.baud_rate)
.data_bits(serialport::DataBits::Eight)
.parity(serialport::Parity::None)
.stop_bits(serialport::StopBits::One)
.timeout(Duration::from_millis(AX25_READ_TIMEOUT_MS))
.open()
.map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("ax25kiss serial open: {}", e))
})?;
let (data_bits, parity, stop_bits) =
crate::serial::serial_params_from(config.data_bits, &config.parity, config.stop_bits);
let port = crate::serial::open_port(
serialport::new(&config.port, config.baud_rate)
.data_bits(data_bits)
.parity(parity)
.stop_bits(stop_bits)
.timeout(Duration::from_millis(AX25_READ_TIMEOUT_MS)),
)
.map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("ax25kiss serial open: {}", e))
})?;
tracing::info!(
name = %config.name,
@@ -255,6 +269,7 @@ pub async fn spawn_ax25kiss_interface(
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let (tx, mut rx) = mpsc::channel::<Bytes>(256);
let background = crate::background_announce::register(&tx)?;
let name = config.name.clone();
let mode = config.mode;
let flow_control = config.flow_control;
@@ -286,50 +301,53 @@ pub async fn spawn_ax25kiss_interface(
let txb_w = shared_txb.clone();
tokio::spawn(async move {
let mut port_w = port_write;
while let Some(data) = rx.recv().await {
loop {
if !online_w.load(Ordering::SeqCst) {
break;
}
let background_packet = if rx.is_empty() {
background.try_start_when(rns_transport::now_f64(), || {
!flow_control
|| ready_w
.compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
.is_ok()
})
} else {
None
};
let data = if let Some(packet) = &background_packet {
packet.raw().clone()
} else {
match tokio::time::timeout(Duration::from_millis(100), rx.recv()).await {
Ok(Some(data)) => data,
Ok(None) => break,
Err(_) => continue,
}
};
txb_w.fetch_add(data.len() as u64, Ordering::Relaxed);
if flow_control {
let start = std::time::Instant::now();
while !ready_w.load(Ordering::SeqCst) {
if flow_control && background_packet.is_none() {
while ready_w
.compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
.is_err()
{
tokio::time::sleep(Duration::from_millis(10)).await;
if !online_w.load(Ordering::SeqCst) {
return;
}
if start.elapsed() > Duration::from_secs(FLOW_CONTROL_TIMEOUT_SECS) {
tracing::warn!("AX.25 KISS flow control timeout, unlocking");
ready_w.store(true, Ordering::SeqCst);
break;
}
}
}
let framed =
frame_ax25_kiss(&data, &dst_call_bytes, dst_ssid, &src_call_bytes, src_ssid);
if flow_control {
ready_w.store(false, Ordering::SeqCst);
}
let online_ref = online_w.clone();
let result = tokio::task::spawn_blocking(move || {
use std::io::Write;
port_w.write_all(&framed)?;
port_w.flush()?;
Ok::<_, std::io::Error>(port_w)
})
.await;
match result {
Ok(Ok(p)) => {
match crate::serial_io::blocking_write_all(port_w, framed).await {
Ok(p) => {
port_w = p;
}
Ok(Err(e)) => {
tracing::warn!(error = %e, "AX.25 KISS write error");
online_ref.store(false, Ordering::SeqCst);
break;
}
Err(e) => {
tracing::warn!(error = %e, "AX.25 KISS write task panicked");
tracing::warn!(error = %e, "AX.25 KISS write error");
online_w.store(false, Ordering::SeqCst);
break;
}
}
@@ -348,18 +366,8 @@ pub async fn spawn_ax25kiss_interface(
if !online_r.load(Ordering::SeqCst) {
break;
}
let result = tokio::task::spawn_blocking(move || {
use std::io::Read;
match port_r.read(&mut buf) {
Ok(n) => Ok((port_r, buf, n)),
Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok((port_r, buf, 0)),
Err(e) => Err((port_r, e)),
}
})
.await;
match result {
Ok(Ok((p, b, n))) => {
match crate::serial_io::poll_read(port_r, buf).await {
Ok((p, b, n)) => {
port_r = p;
buf = b;
if n > 0 {
@@ -395,13 +403,8 @@ pub async fn spawn_ax25kiss_interface(
}
}
}
Ok(Err((_p, e))) => {
tracing::warn!(error = %e, "AX.25 KISS read error");
online_r.store(false, Ordering::SeqCst);
return;
}
Err(e) => {
tracing::warn!(error = %e, "AX.25 KISS read task panicked");
tracing::warn!(error = %e, "AX.25 KISS read error");
online_r.store(false, Ordering::SeqCst);
return;
}
@@ -411,6 +414,8 @@ pub async fn spawn_ax25kiss_interface(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 564, false),
parent_id: None,
name,
mode,
@@ -425,6 +430,7 @@ pub async fn spawn_ax25kiss_interface(
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: None,
tx,
read_task,
})
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,119 @@
//! Exact-channel optional lane shared by the built-in final writers.
#[cfg(any(
feature = "serial",
feature = "rnode-tcp",
feature = "ble",
target_os = "android",
test
))]
use bytes::Bytes;
#[cfg(any(
feature = "serial",
feature = "rnode-tcp",
feature = "ble",
target_os = "android",
test
))]
pub(crate) use rns_transport::background_egress::BackgroundAnnounceReceiver;
#[cfg(any(
feature = "serial",
feature = "rnode-tcp",
feature = "ble",
target_os = "android",
test
))]
use tokio::sync::mpsc;
#[cfg(any(
feature = "serial",
feature = "rnode-tcp",
feature = "ble",
target_os = "android",
test
))]
pub(crate) fn register(
tx: &mpsc::Sender<Bytes>,
) -> Result<BackgroundAnnounceReceiver, crate::traits::InterfaceError> {
BackgroundAnnounceReceiver::register(tx).map_err(|error| {
crate::traits::InterfaceError::SendFailed(format!(
"background announce registration failed: {error:?}"
))
})
}
#[cfg(test)]
pub(crate) fn scheduled_actor(
tx: mpsc::Sender<Bytes>,
) -> (
tokio::task::JoinHandle<()>,
mpsc::Sender<rns_transport::messages::TransportMessage>,
Bytes,
) {
scheduled_actor_with_backlog(tx, 1)
}
/// A saturated scheduler uses a sub-clock-resolution cap interval so every
/// explicit actor tick is a due window. Writer readiness remains independent.
#[cfg(test)]
pub(crate) fn scheduled_actor_with_backlog(
tx: mpsc::Sender<Bytes>,
count: usize,
) -> (
tokio::task::JoinHandle<()>,
mpsc::Sender<rns_transport::messages::TransportMessage>,
Bytes,
) {
use rns_transport::{
actor::TransportActor,
constants::{InterfaceDirection, InterfaceMode},
messages::{InterfaceEntry, QueuedAnnounce},
};
let (mut actor, control) = TransportActor::new();
let bitrate = if count > 1 { u64::MAX } else { 500 };
let mut entry = InterfaceEntry::new(
"radio with no name heuristic".into(),
InterfaceMode::Full,
InterfaceDirection::bidirectional(),
bitrate,
500,
tx,
);
let identity = rns_identity::identity::Identity::new();
let mut first = Bytes::new();
for index in 0..count {
let app = format!("test.background.{index}");
let dest = rns_identity::destination::Destination::hash_from_name_and_identity(
&app,
Some(&identity.hash),
);
let announce =
rns_identity::announce::AnnounceData::create(&identity, &app, None, None).unwrap();
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Single,
packet_type: rns_wire::flags::PacketType::Announce,
},
hops: 1,
transport_id: None,
destination_hash: dest,
context: rns_wire::context::PacketContext::None,
};
let mut raw = header.pack();
raw.extend(announce.pack());
let raw = Bytes::from(raw);
if index == 0 {
first = raw.clone();
}
entry.announce_queue.push(QueuedAnnounce {
destination_hash: dest,
time: rns_transport::now_f64(),
hops: 1,
raw,
});
actor.local_destinations.insert(dest);
}
actor.interfaces.insert(1, entry);
(tokio::spawn(actor.run()), control, first)
}
+24 -26
View File
@@ -1,9 +1,6 @@
//! Apple CBCentralManager scan driver.
//!
//! Exists to pass `CBCentralManagerScanOptionAllowDuplicatesKey = YES` to
//! `scanForPeripheralsWithServices:options:` — btleplug does not expose
//! that key, and without it CoreBluetooth reports each peripheral at most
//! once per scan session.
//! Apple CBCentralManager scan driver. Requests repeated advertisement
//! callbacks with `CBCentralManagerScanOptionAllowDuplicatesKey = YES` and
//! reuses its native manager between scan cycles.
#![cfg(any(target_os = "ios", target_os = "macos"))]
@@ -77,8 +74,10 @@ fn manager_slot() -> &'static Mutex<SendPtr> {
MANAGER_PTR.get_or_init(|| Mutex::new(SendPtr(std::ptr::null_mut())))
}
/// Start a CBCentralManager scan with `AllowDuplicatesKey = YES`. Empty
/// `services` scans for all advertisements.
/// Request a CBCentralManager scan with `AllowDuplicatesKey = YES`. Empty
/// `services` removes the service filter. On first startup, manager creation
/// and the wait for PoweredOn continue on a worker thread after this function
/// returns; `Ok` is not confirmation that scanning has started.
pub async fn start_scan(
services: Vec<Uuid>,
) -> Result<mpsc::UnboundedReceiver<DiscoveryEvent>, String> {
@@ -228,8 +227,9 @@ pub async fn stop_scan() -> Result<(), String> {
Ok(())
}
/// Full teardown — interface shutdown only. Per-cycle stops use
/// [`stop_scan`] to keep the manager alive (macOS alloc-cycle bug).
/// Detach the delegate, release this module's explicit manager retain, and
/// clear its manager slot during interface shutdown. Per-cycle stops use
/// [`stop_scan`] and retain the manager for reuse.
pub async fn teardown_central() -> Result<(), String> {
let _ = stop_scan().await;
@@ -256,16 +256,16 @@ pub async fn teardown_central() -> Result<(), String> {
}
fn finalize_stop() {
if let Some(lock) = POWERED_ON_TX.get() {
if let Ok(mut g) = lock.lock() {
*g = None;
}
if let Some(lock) = POWERED_ON_TX.get()
&& let Ok(mut g) = lock.lock()
{
*g = None;
}
// Drop the discovery sender so receivers don't hang on recv.
if let Some(lock) = DISCOVERY_TX.get() {
if let Ok(mut g) = lock.lock() {
*g = None;
}
if let Some(lock) = DISCOVERY_TX.get()
&& let Ok(mut g) = lock.lock()
{
*g = None;
}
apply_event(CentralEvent::ScanStopped);
apply_event(CentralEvent::Reset);
@@ -275,9 +275,9 @@ pub fn current_state() -> CentralState {
lifecycle().current()
}
/// Persistent `CBCentralManager` pointer. Apple central peripheral caches
/// are per-manager, not per-process — `ble_central_apple_connect` must
/// drive `connectPeripheral:` against the same manager that scanned.
/// Borrow the current `CBCentralManager` pointer without retaining it.
/// Connection setup uses the manager that performed discovery. Callers must
/// coordinate teardown; this accessor does not extend the pointer's lifetime.
pub fn central_manager_ptr() -> Option<*mut AnyObject> {
let lock = MANAGER_PTR.get()?;
let g = lock.lock().ok()?;
@@ -566,13 +566,11 @@ fn get_delegate_class() -> &'static AnyClass {
// No sender means stop_scan raced us between the radio event
// and this callback — drop silently.
if let Some(lock) = DISCOVERY_TX.get() {
if let Ok(g) = lock.lock() {
if let Some(tx) = g.as_ref() {
if let Some(lock) = DISCOVERY_TX.get()
&& let Ok(g) = lock.lock()
&& let Some(tx) = g.as_ref() {
let _ = tx.send(event);
}
}
}
}
// Connection-state callbacks share this delegate (one delegate per
@@ -1,16 +1,15 @@
//! Apple central-role connect lifecycle. Sister to
//! [`ble_central_apple`](crate::ble_central_apple) (which owns scanning).
//!
//! Apple-specific because btleplug's CoreBluetooth backend allocates its
//! own manager, and two managers in the same process don't share peripheral
//! caches on macOS, so `adapter.peripherals()` returns empty every cycle.
//! Apple central-role connection lifecycle, using the manager and discovered
//! peripherals owned by [`ble_central_apple`](crate::ble_central_apple).
//! Scanning and connection setup share that manager rather than creating a
//! separate btleplug adapter.
#![cfg(any(target_os = "ios", target_os = "macos"))]
use crate::ble_tx_queue::PacketQueue;
use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel};
use objc2::{msg_send, sel};
use objc2_foundation::NSString;
use std::collections::{HashMap, VecDeque};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
@@ -22,21 +21,16 @@ use crate::ble_peer::{
RATSPEAK_SERVICE_UUID, RATSPEAK_TX_UUID,
};
/// `connectPeripheral:` does not self-time-out; iOS RPA rotation leaves
/// ghost identifiers in `Connecting` state forever. 5s recycles ghosts
/// before they block the scan-loop pipeline.
/// Deadline for the connect callback. On timeout, partial connection state
/// is cancelled and released.
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
/// Generous safety net for service / characteristic / notify discovery
/// (CoreBluetooth normally responds in ~200 ms).
/// Per-step deadline for service discovery, characteristic discovery, and
/// notification subscription callbacks.
pub const DISCOVERY_TIMEOUT: Duration = Duration::from_secs(10);
const DISCOVERED_TTL: Duration = Duration::from_secs(60);
/// Sized to absorb an LXMF fragment burst (~40 × 244B) without unbounded
/// growth on a stuck peer. FIFO drop-oldest.
const PENDING_WRITE_CAP: usize = 128;
struct SendPtr(*mut AnyObject);
unsafe impl Send for SendPtr {}
unsafe impl Sync for SendPtr {}
@@ -66,14 +60,10 @@ static ONLINE_FLAGS: OnceLock<Mutex<HashMap<String, Arc<AtomicBool>>>> = OnceLoc
/// transient RPA-rotation drops from genuine peer failures.
static LAST_DISCONNECT_REASON: OnceLock<Mutex<HashMap<String, DisconnectReason>>> = OnceLock::new();
/// Drained by `peripheralIsReadyToSendWriteWithoutResponse:`.
static PENDING_WRITE: OnceLock<Mutex<HashMap<String, VecDeque<Vec<u8>>>>> = OnceLock::new();
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DisconnectReason {
/// `CBErrorPeripheralConnectionTimeout` — almost always an iPhone /
/// Pixel RPA rotating out from under our open link. The peer
/// re-advertises within ~1s.
/// Classification used for `CBErrorPeripheralConnectionTimeout`. The label
/// does not establish address rotation as the cause or guarantee rediscovery.
Rotation,
OtherError,
}
@@ -121,10 +111,6 @@ fn last_disconnect_reason() -> &'static Mutex<HashMap<String, DisconnectReason>>
LAST_DISCONNECT_REASON.get_or_init(|| Mutex::new(HashMap::new()))
}
fn pending_write() -> &'static Mutex<HashMap<String, VecDeque<Vec<u8>>>> {
PENDING_WRITE.get_or_init(|| Mutex::new(HashMap::new()))
}
pub fn take_last_disconnect_reason(address: &str) -> Option<DisconnectReason> {
last_disconnect_reason()
.lock()
@@ -132,9 +118,9 @@ pub fn take_last_disconnect_reason(address: &str) -> Option<DisconnectReason> {
.and_then(|mut g| g.remove(address))
}
/// Drop frees the retained ObjC objects. Disconnect goes via
/// [`disconnect_peer`] (`cancelPeripheralConnection:`); the delegate
/// callback removes the map entry, dropping the last `Arc`.
/// Owns retained Objective-C connection objects until the final `Arc` is
/// dropped. [`disconnect_peer`] removes the registered peer and requests
/// `cancelPeripheralConnection:`; other owners can outlive that request.
pub struct ConnectedPeer {
pub address: String,
pub protocol: PeerProtocol,
@@ -144,6 +130,7 @@ pub struct ConnectedPeer {
delegate: SendPtr,
rx_char: SendPtr,
tx_char: SendPtr,
pending_write: Mutex<PacketQueue>,
}
impl Drop for ConnectedPeer {
@@ -152,8 +139,13 @@ impl Drop for ConnectedPeer {
// 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() {
let _: () =
msg_send![self.peripheral.0, setDelegate: std::ptr::null::<AnyObject>()];
// A retired write task can outlive reconnect. Do not detach
// a replacement delegate on the same peripheral object.
let current: *mut AnyObject = msg_send![self.peripheral.0, delegate];
if current == self.delegate.0 {
let _: () =
msg_send![self.peripheral.0, setDelegate: std::ptr::null::<AnyObject>()];
}
}
for p in [
&self.delegate,
@@ -374,17 +366,33 @@ pub async fn connect_peer(
let mut g = online_flags().lock().expect("online_flags lock");
g.insert(address.clone(), online.clone());
}
// CB auto-negotiates the ATT MTU during connection setup and exposes the
// usable per-write payload via maximumWriteValueLengthForType:. Reading it
// (rather than assuming 244) both prevents silent truncation on a link that
// negotiated a smaller MTU and unlocks larger writes (iOS commonly 512).
// Clamp: floor at the ATT-23 minimum, ceil at our fragment TARGET_MTU.
const WRITE_WITHOUT_RESPONSE: usize = 1; // CBCharacteristicWriteWithoutResponse
let negotiated: usize =
unsafe { msg_send![peripheral.0, maximumWriteValueLengthForType: WRITE_WITHOUT_RESPONSE] };
let write_mtu = negotiated.clamp(20, crate::ble_peer::TARGET_MTU as usize);
tracing::info!(
target: "ble_trace",
step = "apple_connect.mtu",
address = %address,
negotiated,
write_mtu,
"Apple BLE central: negotiated write MTU"
);
let peer = Arc::new(ConnectedPeer {
address: address.clone(),
protocol,
// CB auto-negotiates ATT MTU with no public read-back API.
// 244 = ATT MTU 247 - 3-byte header (BLE 4.2+ baseline).
write_mtu: 244,
write_mtu,
online: online.clone(),
peripheral,
delegate,
rx_char,
tx_char,
pending_write: Mutex::new(PacketQueue::default()),
});
{
let mut g = connected_peers().lock().expect("connected_peers lock");
@@ -393,90 +401,53 @@ pub async fn connect_peer(
Ok(peer)
}
/// Queues into [`PENDING_WRITE`] when `canSendWriteWithoutResponse` is
/// false — without queueing, fragmented LXMF messages silently lose every
/// fragment past the first on a loaded radio.
/// Queue a single already-fragmented value. Full queues refuse the new value;
/// accepted values are never evicted. Packet producers should use the internal
/// complete-packet admission path so overload cannot admit a partial packet.
pub fn write_peer(address: &str, data: &[u8]) -> Result<(), String> {
let peer = {
let g = connected_peers().lock().expect("connected_peers lock");
g.get(address).cloned()
};
let peer = peer.ok_or_else(|| format!("peer {address} not connected"))?;
if !peer.online.load(Ordering::SeqCst) {
return Err(format!("peer {address} marked offline"));
let peer = connected_peers()
.lock()
.expect("connected_peers lock")
.get(address)
.cloned()
.ok_or_else(|| "peer not connected".to_string())?;
if enqueue_packet(&peer, vec![data.to_vec()])? {
Ok(())
} else {
Err("native write queue full".into())
}
// The flag can flip back to false at any time after returning true
// (per Apple's docs); the ready-to-send delegate drains the queue.
let ready: bool = unsafe { msg_send![peer.peripheral.0, canSendWriteWithoutResponse] };
if ready {
unsafe { issue_write(&peer, data) };
return Ok(());
}
let mut g = pending_write().lock().expect("pending_write lock");
let q = g.entry(address.to_owned()).or_default();
if q.len() >= PENDING_WRITE_CAP {
q.pop_front();
tracing::warn!(
target: "ble_trace",
step = "central.write_overflow_drop",
peer = %address,
cap = PENDING_WRITE_CAP,
"Apple BLE central: pending-write ring overflowed, dropping oldest"
);
}
q.push_back(data.to_vec());
tracing::debug!(
target: "ble_trace",
step = "central.write_queued",
peer = %address,
bytes = data.len(),
depth = q.len(),
"Apple BLE central: write queued (radio queue full)"
);
Ok(())
}
/// Requeues at front if canSend flips false mid-drain.
unsafe fn drain_pending_writes(address: &str) {
let peer = {
let g = connected_peers().lock().expect("connected_peers lock");
match g.get(address) {
Some(p) => p.clone(),
None => return,
}
};
pub(crate) fn write_packet(peer: &Arc<ConnectedPeer>, data: &[u8]) -> Result<bool, String> {
enqueue_packet(peer, crate::ble_peer::fragment_packet(data, peer.write_mtu))
}
fn enqueue_packet(peer: &ConnectedPeer, frames: Vec<Vec<u8>>) -> Result<bool, String> {
let mut q = peer.pending_write.lock().expect("pending_write lock");
if !peer.online.load(Ordering::SeqCst) {
return;
return Err("peer offline".into());
}
let mut drained = 0usize;
loop {
let entry = {
let mut g = pending_write().lock().expect("pending_write lock");
g.get_mut(address).and_then(|q| q.pop_front())
};
let Some(data) = entry else {
break;
};
if frames.iter().any(|frame| frame.len() > peer.write_mtu) {
return Err("frame exceeds native value limit".into());
}
let admitted = q.enqueue(frames);
drain_peer_queue(peer, &mut q);
q.report("apple_central", peer.write_mtu);
Ok(admitted)
}
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 {
let mut g = pending_write().lock().expect("pending_write lock");
g.entry(address.to_owned()).or_default().push_front(data);
break;
return false;
}
unsafe { issue_write(&peer, &data) };
drained += 1;
}
if drained > 0 {
tracing::debug!(
target: "ble_trace",
step = "central.write_drained",
peer = %address,
drained,
"Apple BLE central: pending writes drained"
);
}
unsafe { issue_write(peer, data) };
true
}) {}
}
/// Caller must have either confirmed `canSendWriteWithoutResponse` or be
@@ -485,7 +456,7 @@ unsafe fn drain_pending_writes(address: &str) {
/// # Safety
/// `peer.peripheral.0` and `peer.rx_char.0` must be retained, valid CB
/// pointers.
unsafe fn issue_write(peer: &Arc<ConnectedPeer>, data: &[u8]) {
unsafe fn issue_write(peer: &ConnectedPeer, data: &[u8]) {
unsafe {
let nsdata = nsdata_from_slice(data);
const WRITE_WITHOUT_RESPONSE: i64 = 1;
@@ -506,8 +477,8 @@ pub fn disconnect_peer(address: &str) {
return;
};
peer.online.store(false, Ordering::SeqCst);
if let Ok(mut g) = pending_write().lock() {
g.remove(address);
if let Ok(mut q) = peer.pending_write.lock() {
*q = PacketQueue::default();
}
if let Some(manager_ptr) = crate::ble_central_apple::central_manager_ptr() {
unsafe {
@@ -544,15 +515,19 @@ pub fn disconnect_all() {
}
}
/// Adopt a CBPeripheral handed back via `centralManager:willRestoreState:`.
/// Apple guarantees `peripheral.services` is populated and prior TX-char
/// subscriptions are preserved — only the delegate needs rebinding. On
/// success ownership of the +1 retain passes to `ConnectedPeer::drop`; on
/// Err the retain is released.
/// Adopt a restored peripheral using its cached service and characteristic
/// objects. This function rebinds the delegate; it does not rediscover services
/// or resubscribe to notifications.
///
/// For a nonempty address and non-null pointer, the supplied +1 retain is
/// consumed: success transfers it to the connection owner or releases it if
/// already registered, and service/characteristic failures release it. Invalid
/// arguments return early without releasing the pointer.
///
/// # Safety
/// `peripheral` must be a retained, non-null `CBPeripheral *` whose state
/// is `Connected (= 2)`.
/// `peripheral` must be a valid, retained `CBPeripheral *` in Connected state.
/// The caller must ensure its cached services and notification subscriptions
/// are usable; this function does not establish those conditions.
pub unsafe fn adopt_restored_peer(
address: String,
peripheral: *mut AnyObject,
@@ -633,12 +608,16 @@ pub unsafe fn adopt_restored_peer(
let peer = Arc::new(ConnectedPeer {
address: address.clone(),
protocol,
write_mtu: 244,
write_mtu: unsafe {
let value: usize = msg_send![peripheral, maximumWriteValueLengthForType: 1usize];
value.clamp(20, crate::ble_peer::TARGET_MTU as usize)
},
online,
peripheral: SendPtr(peripheral),
delegate,
rx_char,
tx_char,
pending_write: Mutex::new(PacketQueue::default()),
});
{
let mut g = connected_peers().lock().expect("connected_peers lock");
@@ -654,13 +633,17 @@ pub unsafe fn adopt_restored_peer(
Ok(())
}
/// CB keeps connections alive thanks to `bluetooth-central`
/// UIBackgroundMode + restore-identifier; this just logs inventory.
/// Log connected-peer and pending-write counts when the app resigns active.
/// This hook does not change connection state or guarantee background delivery.
pub fn on_app_will_resign_active() {
let connected = connected_peers().lock().map(|g| g.len()).unwrap_or(0);
let pending = pending_write()
let pending = connected_peers()
.lock()
.map(|g| g.values().map(|q| q.len()).sum::<usize>())
.map(|g| {
g.values()
.map(|p| p.pending_write.lock().map(|q| q.len()).unwrap_or(0))
.sum::<usize>()
})
.unwrap_or(0);
tracing::info!(
target: "ble_trace",
@@ -671,8 +654,8 @@ pub fn on_app_will_resign_active() {
);
}
/// Prune discovered pointers older than [`DISCOVERED_TTL`] — after a long
/// background those are RPA-rotated ghosts.
/// Prune discovered pointers older than the discovery TTL and log the
/// remaining discovery and connection counts.
pub fn on_app_did_become_active() {
prune_discovered();
let discovered_remaining = match discovered().lock() {
@@ -749,10 +732,10 @@ pub fn on_did_disconnect(address: &str, err: Option<String>) {
if let Some(peer) = removed {
peer.online.store(false, Ordering::SeqCst);
}
if let Ok(mut g) = online_flags().lock() {
if let Some(flag) = g.remove(address) {
flag.store(false, Ordering::SeqCst);
}
if let Ok(mut g) = online_flags().lock()
&& let Some(flag) = g.remove(address)
{
flag.store(false, Ordering::SeqCst);
}
let classified = classify_disconnect_reason(err.as_deref());
@@ -804,9 +787,14 @@ fn resolve_pending(address: &str, kind: CallbackKind, result: Result<(), String>
}
}
/// English-locale, case-insensitive substring match against rotation
/// English-locale, case-insensitive substring match against RPA-rotation
/// signatures: `CBErrorPeripheralConnectionTimeout` (constant or localized
/// "timed out unexpectedly") and "specified device has disconnected".
/// "timed out unexpectedly"), which is how a rotated-address peer presents.
///
/// "The specified device has disconnected" (CBErrorPeripheralDisconnected) is
/// deliberately NOT treated as rotation: it is the generic remote-initiated
/// disconnect, and mapping it to Rotation cleared the reconnect backoff on
/// every ordinary drop, letting a flapping peer churn without ever backing off.
fn classify_disconnect_reason(err: Option<&str>) -> DisconnectReason {
let Some(s) = err else {
return DisconnectReason::OtherError;
@@ -814,7 +802,6 @@ fn classify_disconnect_reason(err: Option<&str>) -> DisconnectReason {
let lower = s.to_ascii_lowercase();
if lower.contains("timed out unexpectedly")
|| lower.contains("cberrorperipheralconnectiontimeout")
|| lower.contains("specified device has disconnected")
{
DisconnectReason::Rotation
} else {
@@ -954,7 +941,18 @@ fn peripheral_delegate_class() -> &'static AnyClass {
if address.is_empty() {
return;
}
unsafe { drain_pending_writes(&address) };
let peer = connected_peers()
.lock()
.ok()
.and_then(|g| g.get(&address).cloned());
if let Some(peer) = peer {
// Old delegates cannot drain a replacement connection's queue.
if peer.peripheral.0 != peripheral || peer.delegate.0 != _this {
return;
}
let mut q = peer.pending_write.lock().expect("pending_write lock");
drain_peer_queue(&peer, &mut q);
}
}
unsafe {
@@ -1265,9 +1263,10 @@ mod tests {
}
#[test]
fn classify_rotation_via_specified_device_disconnected() {
fn classify_specified_device_disconnected_is_not_rotation() {
// Generic remote-initiated disconnect must NOT clear reconnect backoff.
let r = classify_disconnect_reason(Some("The specified device has disconnected from us."));
assert_eq!(r, DisconnectReason::Rotation);
assert_eq!(r, DisconnectReason::OtherError);
}
#[test]
@@ -1,5 +1,6 @@
//! BLE central (scan) lifecycle. `PlatformUnavailable` rewinds active states
//! to `StartingWaitingPlatform` so scanning resumes after a Bluetooth toggle.
//! BLE central scan lifecycle. `PlatformUnavailable` rewinds starting or
//! scanning states to `StartingWaitingPlatform`. A later `PlatformReady` can
//! resume scanning; stopping states are not rewound.
use std::sync::{Mutex, MutexGuard, PoisonError};
use std::time::Instant;
@@ -12,7 +13,8 @@ pub enum AdvertisedProtocol {
Columba,
}
/// `identifier` is platform-stable (Apple UUIDString, bluer D-Bus path, Android MAC).
/// `identifier` is a platform-provided scan identifier, such as an Apple UUID
/// or Bluetooth address. It is not a persistent authenticated peer identity.
#[derive(Debug, Clone)]
pub struct DiscoveryEvent {
pub identifier: String,
@@ -48,7 +50,7 @@ pub enum CentralState {
StoppingScan,
/// Cleanly torn down. Distinct from `Idle` for telemetry.
Stopped,
/// Bluetooth unsupported / permission denied; requires explicit `Reset`.
/// A fatal platform error was reported; requires explicit `Reset`.
Failed,
}
@@ -75,8 +77,8 @@ pub enum CentralEvent {
StartRequested,
/// Platform ready: adapter calls `scanForPeripheralsWithServices` here.
PlatformReady,
/// Active states rewind to `StartingWaitingPlatform` so recovery
/// resumes scanning.
/// Starting and scanning states rewind to `StartingWaitingPlatform`.
/// Stopping states reject this event.
PlatformUnavailable {
reason: String,
},
+187
View File
@@ -0,0 +1,187 @@
//! Private bounds for desktop GATT setup and Windows address resolution.
use std::{fmt::Display, future::Future, time::Duration};
const OPERATION_TIMEOUT: Duration = Duration::from_secs(10);
pub(super) async fn operation<T, E: Display>(
label: &str,
future: impl Future<Output = Result<T, E>>,
) -> Result<T, String> {
tokio::time::timeout(OPERATION_TIMEOUT, future)
.await
.map_err(|_| format!("{label}: timed out"))?
.map_err(|error| format!("{label}: {error}"))
}
/// Cancels an in-flight setup when its interface generation ends. The caller
/// retains the peripheral in the teardown registry until cleanup completes.
pub(super) async fn while_current<T>(
future: impl Future<Output = Result<T, String>>,
current: impl Fn() -> bool,
) -> Result<T, String> {
tokio::pin!(future);
let mut tick = tokio::time::interval(Duration::from_millis(50));
loop {
if !current() {
return Err("BLE connection cancelled".into());
}
tokio::select! {
biased;
_ = tick.tick() => {},
result = &mut future => {
return if current() { result } else { Err("BLE connection cancelled".into()) };
}
}
}
}
#[cfg(any(target_os = "windows", test))]
pub(super) fn known_address(value: &str) -> Option<btleplug::api::BDAddr> {
let address: btleplug::api::BDAddr = value.parse().ok()?;
// Neither sentinel can identify an explicitly selected device.
(!matches!(
address.to_string().as_str(),
"00:00:00:00:00:00" | "FF:FF:FF:FF:FF:FF"
))
.then_some(address)
}
#[cfg(any(target_os = "windows", test))]
pub(super) async fn resolve_address<T, E: Display, F: Future<Output = Result<T, E>>>(
cached: Option<T>,
address: &str,
add: impl FnOnce(btleplug::api::BDAddr) -> F,
) -> Result<T, String> {
if let Some(peripheral) = cached {
return Ok(peripheral);
}
let address = known_address(address).ok_or("No valid configured BLE address")?;
operation("Resolve BLE address", add(address)).await
}
/// Keep the existing desktop ceiling; only shrink writes when the negotiated
/// ATT MTU requires it. Unknown/invalid MTUs use BLE's mandatory baseline.
pub(super) fn write_payload(mtu: u16) -> usize {
if mtu < 23 {
20
} else {
usize::from(mtu - 3).min(182)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
#[tokio::test]
async fn cached_device_does_not_attempt_address_creation() {
let result = resolve_address(Some(7), "platform-id", |_| async {
panic!("must not add a cached peripheral");
#[allow(unreachable_code)]
Ok::<_, String>(8)
})
.await;
assert_eq!(result, Ok(7));
}
#[tokio::test]
async fn only_explicit_addresses_can_create_peripherals() {
for invalid in [
"",
"RNode One",
"1234",
"00:00:00:00:00:00",
"FF:FF:FF:FF:FF:FF",
"AE34CD04-9854-4E64-8870-D58631FBBCC4",
] {
assert!(
resolve_address::<(), String, _>(None, invalid, |_| async {
panic!("invalid target reached the platform");
#[allow(unreachable_code)]
Ok(())
})
.await
.is_err()
);
}
assert_eq!(
resolve_address(None, "aa:bb:cc:dd:ee:01", |address| async move {
Ok::<_, String>(address.to_string())
})
.await
.unwrap(),
"AA:BB:CC:DD:EE:01"
);
assert!(
resolve_address::<(), _, _>(None, "AA:BB:CC:DD:EE:01", |_| async {
Err("adapter unavailable")
})
.await
.unwrap_err()
.contains("adapter unavailable")
);
}
struct DropFlag(Arc<AtomicBool>);
impl Drop for DropFlag {
fn drop(&mut self) {
self.0.store(true, Ordering::SeqCst);
}
}
#[tokio::test(start_paused = true)]
async fn unavailable_device_is_bounded_and_releases_pending_work() {
let dropped = Arc::new(AtomicBool::new(false));
let guard = DropFlag(dropped.clone());
let result = resolve_address::<(), String, _>(None, "AA:BB:CC:DD:EE:01", |_| async move {
let _guard = guard;
std::future::pending().await
})
.await;
assert!(result.unwrap_err().contains("timed out"));
assert!(dropped.load(Ordering::SeqCst));
}
#[tokio::test(start_paused = true)]
async fn generation_change_cancels_pending_setup_before_timeout() {
let active = Arc::new(AtomicBool::new(true));
let stop = active.clone();
let dropped = Arc::new(AtomicBool::new(false));
let guard = DropFlag(dropped.clone());
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(75)).await;
stop.store(false, Ordering::SeqCst);
});
let start = tokio::time::Instant::now();
let result: Result<(), String> = while_current(
async move {
let _guard = guard;
std::future::pending().await
},
|| active.load(Ordering::SeqCst),
)
.await;
assert!(result.unwrap_err().contains("cancelled"));
assert!(start.elapsed() < Duration::from_secs(1));
assert!(dropped.load(Ordering::SeqCst));
}
#[test]
fn negotiated_mtu_never_exceeds_existing_write_ceiling() {
for (mtu, expected) in [
(0, 20),
(22, 20),
(23, 20),
(100, 97),
(185, 182),
(247, 182),
] {
assert_eq!(write_payload(mtu), expected);
}
}
}
File diff suppressed because it is too large. Load diff
+13 -27
View File
@@ -1,23 +1,11 @@
//! BLE peripheral lifecycle state machine. Platform adapters (Apple
//! `CBPeripheralManager`, Linux `bluer`, Android `BluetoothGattServer`,
//! Windows `GattServiceProvider`) drive it via [`PeripheralLifecycle::apply`].
//! BLE peripheral lifecycle state machine. Adapters report platform events
//! through [`PeripheralLifecycle::apply`] and perform side effects after the
//! transition returns.
//!
//! Two invariants this encodes that are easy to violate by hand:
//!
//! 1. **Teardown waits for platform confirmation.** iOS has no
//! `peripheralManagerDidStopAdvertising:` callback; the only reliable
//! "stopped" signal is polling `CBPeripheralManager.isAdvertising` until
//! `NO`. Calling `removeAllServices` while still advertising leaves
//! CoreBluetooth in a dirty state that breaks subsequent enables.
//!
//! 2. **Mid-session platform transitions rewind.** A `Resetting` →
//! `PoweredOff` → `PoweredOn` cycle (user toggling Bluetooth, OS stack
//! crash recovery) must drop back to `StartingWaitingPlatform` so the
//! next `PlatformReady` re-registers.
//!
//! Invalid transitions return an error; adapters log and continue rather
//! than panic — BLE backends occasionally deliver out-of-order or redundant
//! callbacks.
//! Teardown waits for advertising to stop before service removal. Starting
//! and advertising states rewind to `StartingWaitingPlatform` after
//! `PlatformUnavailable`; stopping states are not rewound. Invalid transitions
//! return an error rather than changing state.
use std::sync::{Mutex, MutexGuard, PoisonError};
@@ -45,7 +33,8 @@ pub enum PeripheralState {
}
impl PeripheralState {
/// True when the peripheral holds platform resources needing release on teardown.
/// True in starting, advertising, or stopping states. This classifies
/// lifecycle state; it does not inspect platform resource ownership.
pub fn is_active(self) -> bool {
!matches!(self, Self::Idle | Self::Stopped | Self::Failed)
}
@@ -72,19 +61,16 @@ pub enum LifecycleEvent {
StartRequested,
/// Platform ready for service registration + advertising.
PlatformReady,
/// Platform blocked (BT off, permission denied, adapter resetting).
/// Rewinds active states to `StartingWaitingPlatform` to preserve user
/// intent across recovery.
/// The platform became unavailable. Starting and advertising states rewind
/// to `StartingWaitingPlatform`; stopping states reject this event.
PlatformUnavailable {
reason: String,
},
ServicesAdded,
AdvertiseStarted,
StopRequested,
/// `stopAdvertising` completed. On iOS this comes from polling
/// `isAdvertising` since no delegate callback exists. Skipping this and
/// going straight to `removeAllServices` was the root cause of the
/// "disable doesn't fully tear down" bug.
/// `stopAdvertising` completed. The Apple adapter reports this after
/// checking `isAdvertising`; service removal follows this transition.
AdvertiseStopped,
ServicesRemoved,
FatalError {
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,354 @@
//! Pure connection-generation ownership for the btleplug RNode transport.
use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use bytes::Bytes;
use futures::{Stream, StreamExt};
const STOP_POLL: Duration = Duration::from_millis(100);
#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
pub(super) struct BleGenerationId(u64);
impl BleGenerationId {
pub(super) fn next(&mut self) -> Self {
self.0 = self.0.wrapping_add(1).max(1);
*self
}
pub(super) const fn get(self) -> u64 {
self.0
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum BleOperationStage {
Connect,
ConnectedCheck,
Discovery,
#[cfg_attr(
not(any(
target_os = "ios",
target_os = "macos",
target_os = "windows",
target_os = "android"
)),
allow(dead_code)
)]
PairingRead,
#[cfg_attr(
not(any(target_os = "ios", target_os = "macos", test)),
allow(dead_code)
)]
PairingSubscribe,
Subscribe,
NotificationAcquisition,
Detect,
Capability,
Configure,
ActiveWrite,
Disconnect,
}
impl BleOperationStage {
pub(super) const fn deadline(self) -> Duration {
match self {
Self::PairingRead | Self::PairingSubscribe => Duration::from_secs(60),
Self::ActiveWrite => Duration::from_secs(5),
Self::Disconnect => Duration::from_secs(3),
Self::Connect
| Self::ConnectedCheck
| Self::Discovery
| Self::Subscribe
| Self::NotificationAcquisition
| Self::Detect
| Self::Capability
| Self::Configure => Duration::from_secs(10),
}
}
}
impl fmt::Display for BleOperationStage {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::Connect => "connect",
Self::ConnectedCheck => "connected check",
Self::Discovery => "service discovery",
Self::PairingRead => "pairing read",
Self::PairingSubscribe => "pairing notification subscribe",
Self::Subscribe => "notification subscribe",
Self::NotificationAcquisition => "notification acquisition",
Self::Detect => "detect write",
Self::Capability => "capability write",
Self::Configure => "radio configuration write",
Self::ActiveWrite => "application write",
Self::Disconnect => "disconnect",
})
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) enum BleGenerationExit {
TargetDisconnected {
stage: BleOperationStage,
},
DeadlineElapsed {
stage: BleOperationStage,
},
StopRequested {
stage: BleOperationStage,
},
EventStreamEnded {
stage: BleOperationStage,
},
StageFailed {
stage: BleOperationStage,
reason: String,
},
}
impl fmt::Display for BleGenerationExit {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::TargetDisconnected { stage } => {
write!(formatter, "target disconnected during {stage}")
}
Self::DeadlineElapsed { stage } => write!(formatter, "{stage} timed out"),
Self::StopRequested { stage } => write!(formatter, "stop requested during {stage}"),
Self::EventStreamEnded { stage } => {
write!(formatter, "adapter event stream ended during {stage}")
}
Self::StageFailed { stage, reason } => write!(formatter, "{stage}: {reason}"),
}
}
}
/// Run one platform future while the exact connection generation continues to
/// own target-disconnect and stop observation. Unrelated central events are
/// consumed but never end the operation.
pub(super) async fn run_generation_operation<T, E, F, S, I, P>(
stage: BleOperationStage,
future: F,
events: &mut S,
running: &AtomicBool,
is_target_disconnect: P,
) -> Result<T, BleGenerationExit>
where
E: fmt::Display,
F: std::future::Future<Output = Result<T, E>>,
S: Stream<Item = I> + Unpin,
P: FnMut(&I) -> bool,
{
run_generation_operation_with_timeout(
stage,
stage.deadline(),
future,
events,
running,
is_target_disconnect,
)
.await
}
async fn run_generation_operation_with_timeout<T, E, F, S, I, P>(
stage: BleOperationStage,
timeout: Duration,
future: F,
events: &mut S,
running: &AtomicBool,
mut is_target_disconnect: P,
) -> Result<T, BleGenerationExit>
where
E: fmt::Display,
F: std::future::Future<Output = Result<T, E>>,
S: Stream<Item = I> + Unpin,
P: FnMut(&I) -> bool,
{
let deadline = tokio::time::Instant::now() + timeout;
tokio::pin!(future);
loop {
if !running.load(Ordering::SeqCst) {
return Err(BleGenerationExit::StopRequested { stage });
}
tokio::select! {
biased;
result = &mut future => return result.map_err(|error| BleGenerationExit::StageFailed {
stage,
reason: error.to_string(),
}),
event = events.next() => match event {
Some(event) if is_target_disconnect(&event) => {
return Err(BleGenerationExit::TargetDisconnected { stage });
}
Some(_) => continue,
None => return Err(BleGenerationExit::EventStreamEnded { stage }),
},
_ = tokio::time::sleep_until(deadline) => {
return Err(BleGenerationExit::DeadlineElapsed { stage });
}
_ = tokio::time::sleep(STOP_POLL) => {}
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) struct PendingOutbound {
payload: Bytes,
station_id: bool,
}
impl PendingOutbound {
pub(super) const fn new(payload: Bytes, station_id: bool) -> Self {
Self {
payload,
station_id,
}
}
pub(super) fn payload(&self) -> &Bytes {
&self.payload
}
pub(super) const fn is_station_id(&self) -> bool {
self.station_id
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::stream;
#[tokio::test]
async fn target_disconnect_preempts_platform_future_that_never_resolves() {
for stage in [
BleOperationStage::Connect,
BleOperationStage::ConnectedCheck,
BleOperationStage::Discovery,
BleOperationStage::PairingRead,
BleOperationStage::PairingSubscribe,
BleOperationStage::Subscribe,
BleOperationStage::NotificationAcquisition,
BleOperationStage::Detect,
BleOperationStage::Capability,
BleOperationStage::Configure,
BleOperationStage::ActiveWrite,
] {
let running = AtomicBool::new(true);
let mut events = stream::iter(["other", "target"]);
let outcome = run_generation_operation_with_timeout(
stage,
Duration::from_secs(1),
std::future::pending::<Result<(), &'static str>>(),
&mut events,
&running,
|event| *event == "target",
)
.await;
assert_eq!(
outcome,
Err(BleGenerationExit::TargetDisconnected { stage })
);
}
}
#[tokio::test]
async fn unrelated_disconnect_does_not_end_generation() {
let running = AtomicBool::new(true);
let mut events = stream::iter(["other"]).chain(stream::pending());
let outcome = run_generation_operation_with_timeout(
BleOperationStage::Subscribe,
Duration::from_secs(1),
async { Ok::<_, &'static str>(7) },
&mut events,
&running,
|event| *event == "target",
)
.await;
assert_eq!(outcome, Ok(7));
}
#[tokio::test]
async fn every_stage_has_an_independent_deadline() {
for stage in [
BleOperationStage::Connect,
BleOperationStage::ConnectedCheck,
BleOperationStage::Discovery,
BleOperationStage::PairingRead,
BleOperationStage::PairingSubscribe,
BleOperationStage::Subscribe,
BleOperationStage::NotificationAcquisition,
BleOperationStage::Detect,
BleOperationStage::Capability,
BleOperationStage::Configure,
BleOperationStage::ActiveWrite,
BleOperationStage::Disconnect,
] {
let running = AtomicBool::new(true);
let mut events = stream::pending::<&'static str>();
let outcome = run_generation_operation_with_timeout(
stage,
Duration::from_millis(2),
std::future::pending::<Result<(), &'static str>>(),
&mut events,
&running,
|_| false,
)
.await;
assert_eq!(outcome, Err(BleGenerationExit::DeadlineElapsed { stage }));
}
}
#[tokio::test]
async fn stop_preempts_pending_operation() {
let running = AtomicBool::new(false);
let mut events = stream::pending::<&'static str>();
let outcome = run_generation_operation_with_timeout(
BleOperationStage::ActiveWrite,
Duration::from_secs(1),
std::future::pending::<Result<(), &'static str>>(),
&mut events,
&running,
|_| false,
)
.await;
assert_eq!(
outcome,
Err(BleGenerationExit::StopRequested {
stage: BleOperationStage::ActiveWrite,
})
);
}
#[tokio::test]
async fn event_stream_closure_is_not_success() {
let running = AtomicBool::new(true);
let mut events = stream::empty::<&'static str>();
let outcome = run_generation_operation_with_timeout(
BleOperationStage::Connect,
Duration::from_secs(1),
std::future::pending::<Result<(), &'static str>>(),
&mut events,
&running,
|_| false,
)
.await;
assert_eq!(
outcome,
Err(BleGenerationExit::EventStreamEnded {
stage: BleOperationStage::Connect,
})
);
}
#[test]
fn generation_ids_are_monotonic_and_pending_payload_is_stable() {
let mut id = BleGenerationId::default();
assert!(id.next() < id.next());
let pending = PendingOutbound::new(Bytes::from_static(b"packet"), false);
assert_eq!(pending.payload(), &Bytes::from_static(b"packet"));
assert!(!pending.is_station_id());
}
}
+160
View File
@@ -0,0 +1,160 @@
//! Bounded native TX admission. A packet is admitted in full or refused before
//! any of its frames are sent. Callers serialize this queue and native writes
//! under the same lock, including readiness callbacks and connection retirement.
use std::collections::VecDeque;
const PACKET_CAPACITY: usize = 128;
const MAX_PACKET_FRAMES: usize = 64;
const MAX_PACKET_BYTES: usize = 4096;
#[derive(Default)]
pub(crate) struct PacketQueue {
packets: VecDeque<VecDeque<Vec<u8>>>,
accepted: u64,
rejected: u64,
sent_frames: u64,
sent_bytes: u64,
blocked: u64,
high_water: usize,
reported: (u64, u64),
}
impl PacketQueue {
pub(crate) fn enqueue(&mut self, frames: Vec<Vec<u8>>) -> bool {
if self.packets.len() >= PACKET_CAPACITY
|| frames.is_empty()
|| frames.len() > MAX_PACKET_FRAMES
|| frames.iter().map(Vec::len).sum::<usize>() > MAX_PACKET_BYTES
{
self.rejected = self.rejected.saturating_add(1);
return false;
}
self.packets.push_back(frames.into());
self.accepted = self.accepted.saturating_add(1);
self.high_water = self.high_water.max(self.packets.len());
true
}
/// Sends only the oldest frame. A refusal leaves it in place. Returns
/// true only when one frame was accepted by the native stack.
pub(crate) fn drain_one(&mut self, mut send: impl FnMut(&[u8]) -> bool) -> bool {
let Some(packet) = self.packets.front_mut() else {
return false;
};
let frame = packet.front().expect("admitted nonempty packet");
if !send(frame) {
self.blocked = self.blocked.saturating_add(1);
return false;
}
self.sent_bytes = self.sent_bytes.saturating_add(frame.len() as u64);
self.sent_frames = self.sent_frames.saturating_add(1);
packet.pop_front();
if packet.is_empty() {
self.packets.pop_front();
}
true
}
pub(crate) fn len(&self) -> usize {
self.packets.len()
}
pub(crate) fn report(&mut self, role: &'static str, value_limit: usize) {
// Closed schema: no addresses, identifiers, payloads or native errors.
// Sample admission milestones and exponentially spaced refusals.
if (self.accepted != self.reported.0
&& (self.accepted == 1 || self.accepted.is_multiple_of(64)))
|| (self.rejected != self.reported.1 && self.rejected.is_power_of_two())
{
self.reported = (self.accepted, self.rejected);
tracing::debug!(
target: "rns_interface::ble_peer::transfer",
role, value_limit, queued_packets = self.len(),
high_water = self.high_water, accepted_packets = self.accepted,
rejected_packets = self.rejected, sent_frames = self.sent_frames,
sent_bytes = self.sent_bytes, backpressure = self.blocked,
"BLE transmit queue counters"
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reports_admission_milestones_and_spaced_refusals() {
let mut q = PacketQueue::default();
assert!(q.enqueue(vec![vec![1]]));
q.report("test", 20);
assert_eq!(q.reported, (1, 0));
for _ in 1..63 {
assert!(q.enqueue(vec![vec![1]]));
q.report("test", 20);
}
assert_eq!(q.reported, (1, 0));
assert!(q.enqueue(vec![vec![1]]));
q.report("test", 20);
assert_eq!(q.reported, (64, 0));
for rejected in 1u64..=4 {
assert!(!q.enqueue(vec![]));
q.report("test", 20);
assert_eq!(q.reported.1, if rejected == 3 { 2 } else { rejected });
}
assert_eq!(q.len(), 64);
}
#[test]
fn backpressure_keeps_middle_frame_ahead_of_later_packets() {
let mut q = PacketQueue::default();
assert!(q.enqueue(vec![vec![0], vec![1], vec![2]]));
let mut sent = Vec::new();
assert!(q.drain_one(|f| {
sent.push(f[0]);
true
}));
assert!(!q.drain_one(|_| false));
assert!(q.enqueue(vec![vec![3], vec![4]]));
while q.drain_one(|f| {
sent.push(f[0]);
true
}) {}
assert_eq!(sent, [0, 1, 2, 3, 4]);
assert_eq!(q.len(), 0);
}
#[test]
fn overflow_refuses_entire_new_packet_without_evicting_old_frames() {
let mut q = PacketQueue::default();
for n in 0..PACKET_CAPACITY {
assert!(q.enqueue(vec![vec![n as u8], vec![0xff]]));
}
assert!(!q.enqueue(vec![vec![0xee]; 3]));
let mut sent = Vec::new();
while q.drain_one(|f| {
sent.push(f[0]);
true
}) {}
let expected: Vec<_> = (0..PACKET_CAPACITY).flat_map(|n| [n as u8, 0xff]).collect();
assert_eq!(sent, expected);
assert_eq!(q.rejected, 1);
}
#[test]
fn bounds_and_retirement_do_not_replay_partial_packets() {
let mut q = PacketQueue::default();
assert!(!q.enqueue(vec![]));
assert!(!q.enqueue(vec![vec![0]; MAX_PACKET_FRAMES + 1]));
assert!(!q.enqueue(vec![vec![0; MAX_PACKET_BYTES + 1]]));
assert!(q.enqueue(vec![vec![0], vec![1]]));
assert!(q.drain_one(|_| true));
q = PacketQueue::default(); // New connection owns a new queue.
assert!(!q.drain_one(|_| panic!("retired frame replayed")));
assert!(q.enqueue(vec![vec![9]]));
assert!(q.drain_one(|f| {
assert_eq!(f, [9]);
true
}));
}
}
+5 -3
View File
@@ -1,5 +1,6 @@
//! HDLC-like framing shared by TCP, Serial, I2P, Local, Pipe, Backbone.
//! Wire: `[FLAG][escaped_payload][FLAG]`. Encode ESC before FLAG; decode FLAG before ESC.
//! HDLC-like framing shared by TCP, Serial, I2P, Local, Pipe, and Backbone.
//! Wire: `[FLAG][escaped_payload][FLAG]`. Payload FLAG and ESC bytes are
//! prefixed with ESC and XORed with [`ESC_MASK`].
/// HDLC frame delimiter.
pub const FLAG: u8 = 0x7E;
@@ -17,7 +18,8 @@ const MAX_FRAME_SIZE: usize = 524288;
/// with headroom; larger frames grow the Vec normally.
const DEFRAME_BUF_CAPACITY: usize = 2048;
/// Append the escape-encoded form of `data` to `out`. No allocation if `out` has capacity.
/// Append the escape-encoded form of `data` to `out`. No allocation is needed
/// when `out` has enough spare capacity for the escaped output.
pub fn escape_into(data: &[u8], out: &mut Vec<u8>) {
let mut i = 0;
while i < data.len() {
+512 -115
View File
@@ -2,16 +2,21 @@
//! Handshake: HELLO → SESSION CREATE → STREAM CONNECT/ACCEPT;
//! stream then carries HDLC-framed packets.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use bytes::Bytes;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use rns_crypto::zeroize::Zeroizing;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;
use tokio::sync::mpsc;
use crate::hdlc;
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
use crate::traits::{
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, TunnelIdentity,
handoff_accepted_interface, open_client_connection,
};
use rns_transport::messages::{InboundPacket, TransportMessage};
pub const DEFAULT_SAM_ADDRESS: &str = "127.0.0.1";
@@ -34,6 +39,12 @@ pub const RECONNECT_WAIT_MAX: u64 = 300;
pub const SAM_VERSION: &str = "3.1";
/// The longest SAM reply line read: the line limit of Python's asyncio SAM
/// client, far past a SESSION STATUS that carries a private key.
const SAM_REPLY_MAX_BYTES: usize = 64 * 1024;
/// An I2P key file holds one base64 SAM private key of a few kilobytes.
const I2P_KEY_FILE_MAX_BYTES: usize = 16 * 1024;
#[derive(Debug, thiserror::Error)]
pub enum SamError {
#[error("SAM I/O error: {0}")]
@@ -76,23 +87,81 @@ pub fn sam_reply_has_token(pairs: &[(String, String)], token: &str) -> bool {
pairs.iter().any(|(k, v)| k == token && v.is_empty())
}
async fn read_sam_reply(
reader: &mut BufReader<tokio::net::tcp::OwnedReadHalf>,
) -> Result<String, SamError> {
let mut line = String::new();
let n = reader.read_line(&mut line).await?;
if n == 0 {
return Err(SamError::Io(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"SAM connection closed during handshake",
)));
}
Ok(line.trim_end().to_string())
/// The value of `key` in a reply, borrowed from it.
fn reply_value<'a>(reply: &'a str, key: &str) -> Option<&'a str> {
reply
.split_whitespace()
.find_map(|token| token.strip_prefix(key)?.strip_prefix('='))
}
async fn sam_hello(
/// Whether a reply holds `token` with no value.
fn reply_has_token(reply: &str, token: &str) -> bool {
reply
.split_whitespace()
.any(|word| word == token || word.strip_suffix('=') == Some(token))
}
/// A reply for an error message, with any private key left out.
fn without_destination(reply: &str) -> String {
reply
.split_whitespace()
.map(|token| {
if token.starts_with("DESTINATION=") {
"DESTINATION=<redacted>"
} else {
token
}
})
.collect::<Vec<_>>()
.join(" ")
}
/// Read one reply line into a buffer reserved once and wiped on drop, since a
/// SESSION STATUS reply carries the session's private key. Bytes are read one
/// at a time, so nothing past the line is consumed.
async fn read_sam_reply<R: AsyncRead + Unpin>(
reader: &mut R,
) -> Result<Zeroizing<String>, SamError> {
let mut line = Zeroizing::new(Vec::with_capacity(SAM_REPLY_MAX_BYTES));
loop {
match reader.read_u8().await {
Ok(b'\n') => break,
Ok(_) if line.len() == SAM_REPLY_MAX_BYTES => {
return Err(SamError::UnexpectedReply(format!(
"reply longer than {SAM_REPLY_MAX_BYTES} bytes"
)));
}
Ok(byte) => line.push(byte),
Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof && !line.is_empty() => break,
Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
return Err(SamError::Io(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"SAM connection closed during handshake",
)));
}
Err(e) => return Err(e.into()),
}
}
let end = line
.iter()
.rposition(|byte| !byte.is_ascii_whitespace())
.map_or(0, |last| last + 1);
line.truncate(end);
match String::from_utf8(std::mem::take(&mut *line)) {
Ok(text) => Ok(Zeroizing::new(text)),
Err(error) => {
drop(Zeroizing::new(error.into_bytes()));
Err(SamError::Io(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"SAM reply is not UTF-8",
)))
}
}
}
async fn sam_hello<R: AsyncRead + Unpin>(
writer: &mut tokio::net::tcp::OwnedWriteHalf,
reader: &mut BufReader<tokio::net::tcp::OwnedReadHalf>,
reader: &mut R,
) -> Result<(), SamError> {
let hello_msg = format!("HELLO VERSION MIN={} MAX={}\n", SAM_VERSION, SAM_VERSION);
writer.write_all(hello_msg.as_bytes()).await?;
@@ -104,7 +173,7 @@ async fn sam_hello(
if !sam_reply_has_token(&pairs, "HELLO") || !sam_reply_has_token(&pairs, "REPLY") {
return Err(SamError::HandshakeFailed(format!(
"expected HELLO REPLY, got: {}",
reply
reply.as_str()
)));
}
@@ -116,43 +185,58 @@ async fn sam_hello(
))),
None => Err(SamError::HandshakeFailed(format!(
"no RESULT in HELLO reply: {}",
reply
reply.as_str()
))),
}
}
/// Returns the destination (base64). `private_key=None` = transient.
async fn sam_session_create(
/// Returns the session's private key (base64), wiped on drop.
/// `private_key=None` = transient.
async fn sam_session_create<R: AsyncRead + Unpin>(
writer: &mut tokio::net::tcp::OwnedWriteHalf,
reader: &mut BufReader<tokio::net::tcp::OwnedReadHalf>,
reader: &mut R,
session_id: &str,
private_key: Option<&str>,
) -> Result<String, SamError> {
let dest_param = match private_key {
Some(key) => key.to_string(),
None => "TRANSIENT".to_string(),
transient_signature_type: Option<u8>,
) -> Result<Zeroizing<String>, SamError> {
let transient;
let destination = match (private_key, transient_signature_type) {
(Some(key), _) => key,
(None, Some(signature_type)) => {
transient = format!("TRANSIENT SIGNATURE_TYPE={signature_type}");
&transient
}
(None, None) => "TRANSIENT",
};
let create_msg = format!(
"SESSION CREATE STYLE=STREAM ID={} DESTINATION={}\n",
session_id, dest_param
);
// Sized up front: the command carries the private key.
let mut create_msg = Zeroizing::new(String::with_capacity(
64 + session_id.len() + destination.len(),
));
for part in [
"SESSION CREATE STYLE=STREAM ID=",
session_id,
" DESTINATION=",
destination,
"\n",
] {
create_msg.push_str(part);
}
writer.write_all(create_msg.as_bytes()).await?;
writer.flush().await?;
let reply = read_sam_reply(reader).await?;
let pairs = parse_sam_reply(&reply);
if !sam_reply_has_token(&pairs, "SESSION") || !sam_reply_has_token(&pairs, "STATUS") {
if !reply_has_token(&reply, "SESSION") || !reply_has_token(&reply, "STATUS") {
return Err(SamError::SessionFailed(format!(
"expected SESSION STATUS, got: {}",
reply
without_destination(&reply)
)));
}
match sam_reply_get(&pairs, "RESULT") {
match reply_value(&reply, "RESULT") {
Some("OK") => {}
Some(other) => {
let msg_detail = sam_reply_get(&pairs, "MESSAGE").unwrap_or("no details");
let msg_detail = reply_value(&reply, "MESSAGE").unwrap_or("no details");
return Err(SamError::SessionFailed(format!(
"SESSION RESULT={}: {}",
other, msg_detail
@@ -161,13 +245,13 @@ async fn sam_session_create(
None => {
return Err(SamError::SessionFailed(format!(
"no RESULT in SESSION STATUS: {}",
reply
without_destination(&reply)
)));
}
}
match sam_reply_get(&pairs, "DESTINATION") {
Some(dest) => Ok(dest.to_string()),
match reply_value(&reply, "DESTINATION") {
Some(dest) => Ok(Zeroizing::new(dest.to_string())),
None => Err(SamError::SessionFailed(
"SESSION STATUS OK but no DESTINATION returned".to_string(),
)),
@@ -195,7 +279,7 @@ async fn sam_stream_connect(
if !sam_reply_has_token(&pairs, "STREAM") || !sam_reply_has_token(&pairs, "STATUS") {
return Err(SamError::StreamFailed(format!(
"expected STREAM STATUS, got: {}",
reply
reply.as_str()
)));
}
@@ -210,7 +294,7 @@ async fn sam_stream_connect(
}
None => Err(SamError::StreamFailed(format!(
"no RESULT in STREAM STATUS: {}",
reply
reply.as_str()
))),
}
}
@@ -232,7 +316,7 @@ async fn sam_stream_accept(
if !sam_reply_has_token(&pairs, "STREAM") || !sam_reply_has_token(&pairs, "STATUS") {
return Err(SamError::AcceptFailed(format!(
"expected STREAM STATUS, got: {}",
reply
reply.as_str()
)));
}
@@ -248,7 +332,7 @@ async fn sam_stream_accept(
None => {
return Err(SamError::AcceptFailed(format!(
"no RESULT in STREAM STATUS: {}",
reply
reply.as_str()
)));
}
}
@@ -262,6 +346,14 @@ async fn connect_to_sam(sam_host: &str, sam_port: u16) -> Result<TcpStream, SamE
let addr = format!("{}:{}", sam_host, sam_port);
let stream = TcpStream::connect(&addr).await.map_err(SamError::Io)?;
let _ = stream.set_nodelay(true);
// Python i2p_tunneled tuning: longer probes/timeout to absorb I2P latency.
crate::socket_tuning::set_keepalive_tuned(
&stream,
std::time::Duration::from_secs(I2P_PROBE_AFTER),
std::time::Duration::from_secs(I2P_PROBE_INTERVAL),
I2P_PROBES as u32,
std::time::Duration::from_secs(I2P_TCP_USER_TIMEOUT as u64),
);
Ok(stream)
}
@@ -272,15 +364,40 @@ fn generate_session_id() -> String {
format!("reticulum_{:016x}", id)
}
#[derive(Debug, Clone)]
#[derive(Clone)]
pub struct I2PServerConfig {
pub name: String,
pub sam_host: String,
pub sam_port: u16,
/// Base64 private key for a persistent destination; `None` = transient.
/// Base64 private key for the server's destination, used before `key_path`.
pub keyfile: Option<String>,
/// Optional path for the server destination's private key, used when
/// `keyfile` is absent. A missing or empty file is populated after session
/// creation. Read failures leave the file untouched and use a transient
/// destination; write failures can likewise change the next session's address.
pub key_path: Option<std::path::PathBuf>,
pub reconnect_delay: u64,
pub mode: InterfaceMode,
/// Receives the server's b32 address (Python `I2PInterface.b32`) whenever
/// SAM creates its session.
pub b32: Option<tokio::sync::watch::Sender<Option<String>>>,
}
// The key is the destination's secret; debug output names only its presence.
impl std::fmt::Debug for I2PServerConfig {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("I2PServerConfig")
.field("name", &self.name)
.field("sam_host", &self.sam_host)
.field("sam_port", &self.sam_port)
.field("keyfile", &self.keyfile.as_ref().map(|_| "<redacted>"))
.field("key_path", &self.key_path)
.field("reconnect_delay", &self.reconnect_delay)
.field("mode", &self.mode)
.field("b32", &self.b32)
.finish()
}
}
impl I2PServerConfig {
@@ -290,23 +407,115 @@ impl I2PServerConfig {
sam_host: DEFAULT_SAM_ADDRESS.to_string(),
sam_port: DEFAULT_SAM_PORT,
keyfile: None,
key_path: None,
reconnect_delay: RECONNECT_WAIT,
mode: InterfaceMode::Full,
b32: None,
}
}
}
/// i2plib's signature type for new destinations, EdDSA-SHA512-Ed25519
/// (RNS/vendor/i2plib/sam.py:91-93).
const NEW_DESTINATION_SIGNATURE_TYPE: u8 = 7;
/// The stored key, `None` when there is none yet, read into buffers that are
/// wiped on drop. A file that cannot be read is an error, so it is never
/// replaced.
fn read_private_key(path: &std::path::Path) -> std::io::Result<Option<Zeroizing<String>>> {
let data = match rns_identity::persistence::read_secret_file(path, I2P_KEY_FILE_MAX_BYTES) {
Ok(data) => data,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error),
};
let key = std::str::from_utf8(&data)
.map_err(|_| {
std::io::Error::new(std::io::ErrorKind::InvalidData, "I2P key file is not UTF-8")
})?
.trim();
Ok((!key.is_empty()).then(|| Zeroizing::new(key.to_string())))
}
/// Keep a session's private key readable by its owner only, replaced
/// atomically, as the other private keys are.
fn store_private_key(path: &std::path::Path, key: &str) -> std::io::Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
rns_identity::persistence::atomic_write(path, key.as_bytes())
}
/// The b32 address of the destination in a SAM private key: the hash of its
/// first 387 bytes plus its certificate (i2plib `Destination.base32`,
/// RNS/vendor/i2plib/sam.py:113-129).
pub fn destination_b32(private_key: &str) -> Option<String> {
let key = i2p_base64_decode(private_key)?;
let certificate = usize::from(u16::from_be_bytes(key.get(385..387)?.try_into().ok()?));
let hash = rns_crypto::sha::sha256(key.get(..387 + certificate)?);
Some(base32_lowercase(&hash))
}
/// Base64 with I2P's `-~` alphabet (i2plib `i2p_b64decode`), into a buffer
/// sized up front and wiped on drop: the input is usually a private key.
fn i2p_base64_decode(text: &str) -> Option<Zeroizing<Vec<u8>>> {
let mut bytes = Zeroizing::new(Vec::with_capacity(text.len() * 3 / 4));
let (mut buffer, mut bits) = (0u32, 0u32);
for c in text.trim_end_matches('=').bytes() {
let value = match c {
b'A'..=b'Z' => c - b'A',
b'a'..=b'z' => c - b'a' + 26,
b'0'..=b'9' => c - b'0' + 52,
b'-' => 62,
b'~' => 63,
_ => return None,
};
buffer = buffer << 6 | u32::from(value);
bits += 6;
if bits >= 8 {
bits -= 8;
bytes.push((buffer >> bits) as u8);
buffer &= (1 << bits) - 1;
}
}
Some(bytes)
}
/// RFC 4648 base32, lowercase and unpadded.
fn base32_lowercase(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
let mut text = String::with_capacity(bytes.len().div_ceil(5) * 8);
let (mut buffer, mut bits) = (0u32, 0u32);
for byte in bytes {
buffer = buffer << 8 | u32::from(*byte);
bits += 8;
while bits >= 5 {
bits -= 5;
text.push(char::from(ALPHABET[(buffer >> bits) as usize & 31]));
}
buffer &= (1 << bits) - 1;
}
if bits > 0 {
text.push(char::from(ALPHABET[(buffer << (5 - bits)) as usize & 31]));
}
text
}
#[derive(Debug, Clone)]
pub struct I2PClientConfig {
pub name: String,
pub sam_host: String,
pub sam_port: u16,
/// Peer I2P destination (base64).
/// Peer destination passed verbatim as SAM STREAM CONNECT's `DESTINATION`
/// value. This library does not perform a separate name lookup.
pub peer_destination: String,
/// Reconnect attempt cap; `None` = unlimited.
/// Consecutive failure cap, including the initial connection attempt. A
/// successful connection resets the count. `None` means unlimited retries.
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.
pub tunnel_identity: Option<TunnelIdentity>,
}
impl I2PClientConfig {
@@ -319,8 +528,14 @@ impl I2PClientConfig {
max_reconnect_tries: None,
reconnect_delay: RECONNECT_WAIT,
mode: InterfaceMode::Full,
tunnel_identity: None,
}
}
/// Python `str(I2PInterfacePeer)` (I2PInterface.py:714-715).
pub fn python_name(&self) -> String {
format!("I2PInterfacePeer[{}]", self.name)
}
}
/// Connect via SAM streaming session, run HDLC-framed I/O; exponential reconnect.
@@ -329,6 +544,8 @@ pub async fn spawn_i2p_client(
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let online = Arc::new(AtomicBool::new(false));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
@@ -343,11 +560,14 @@ pub async fn spawn_i2p_client(
let task_rxb = shared_rxb.clone();
let task_txb = shared_txb.clone();
let python_name = config.python_name();
let read_task = tokio::spawn(async move {
let mut tries: usize = 0;
let mut backoff = config.reconnect_delay;
let mut pacer = ReconnectPacer::new(config.reconnect_delay, config.max_reconnect_tries);
// Every attempt after the first follows a failure or an outage.
let mut attempted = false;
loop {
let after_outage = std::mem::replace(&mut attempted, true);
let session_id = generate_session_id();
let session_stream = match connect_to_sam(&config.sam_host, config.sam_port).await {
@@ -358,38 +578,44 @@ pub async fn spawn_i2p_client(
error = %e,
"I2P client: failed to connect to SAM bridge"
);
if check_max_tries(&config.max_reconnect_tries, &mut tries) {
if pacer.give_up() {
tracing::warn!(name = %config.name, "I2P client: max reconnect tries reached");
let _ = transport_tx
.send(TransportMessage::DeregisterInterface { id })
.await;
return;
}
tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
pacer.wait().await;
continue;
}
};
let (session_reader, mut session_writer) = session_stream.into_split();
let mut session_buf_reader = BufReader::new(session_reader);
// Read unbuffered: a read buffer would keep SAM's reply, private key included.
let (mut session_reader, mut session_writer) = session_stream.into_split();
if let Err(e) = sam_hello(&mut session_writer, &mut session_buf_reader).await {
if let Err(e) = sam_hello(&mut session_writer, &mut session_reader).await {
tracing::warn!(
name = %config.name,
error = %e,
"I2P client: SAM HELLO failed"
);
if check_max_tries(&config.max_reconnect_tries, &mut tries) {
if pacer.give_up() {
tracing::warn!(name = %config.name, "I2P client: max reconnect tries reached");
let _ = transport_tx
.send(TransportMessage::DeregisterInterface { id })
.await;
return;
}
tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
pacer.wait().await;
continue;
}
let _our_dest = match sam_session_create(
&mut session_writer,
&mut session_buf_reader,
&mut session_reader,
&session_id,
None,
None,
)
.await
{
@@ -407,11 +633,14 @@ pub async fn spawn_i2p_client(
error = %e,
"I2P client: SESSION CREATE failed"
);
if check_max_tries(&config.max_reconnect_tries, &mut tries) {
if pacer.give_up() {
tracing::warn!(name = %config.name, "I2P client: max reconnect tries reached");
let _ = transport_tx
.send(TransportMessage::DeregisterInterface { id })
.await;
return;
}
tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
pacer.wait().await;
continue;
}
};
@@ -425,11 +654,14 @@ pub async fn spawn_i2p_client(
error = %e,
"I2P client: failed to open stream connection to SAM"
);
if check_max_tries(&config.max_reconnect_tries, &mut tries) {
if pacer.give_up() {
tracing::warn!(name = %config.name, "I2P client: max reconnect tries reached");
let _ = transport_tx
.send(TransportMessage::DeregisterInterface { id })
.await;
return;
}
tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
pacer.wait().await;
continue;
}
};
@@ -443,11 +675,14 @@ pub async fn spawn_i2p_client(
error = %e,
"I2P client: SAM HELLO on stream socket failed"
);
if check_max_tries(&config.max_reconnect_tries, &mut tries) {
if pacer.give_up() {
tracing::warn!(name = %config.name, "I2P client: max reconnect tries reached");
let _ = transport_tx
.send(TransportMessage::DeregisterInterface { id })
.await;
return;
}
tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
pacer.wait().await;
continue;
}
@@ -465,11 +700,14 @@ pub async fn spawn_i2p_client(
error = %e,
"I2P client: STREAM CONNECT failed"
);
if check_max_tries(&config.max_reconnect_tries, &mut tries) {
if pacer.give_up() {
tracing::warn!(name = %config.name, "I2P client: max reconnect tries reached");
let _ = transport_tx
.send(TransportMessage::DeregisterInterface { id })
.await;
return;
}
tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
pacer.wait().await;
continue;
}
@@ -479,9 +717,14 @@ pub async fn spawn_i2p_client(
"I2P client: stream connected"
);
online_task.store(true, Ordering::SeqCst);
tries = 0;
backoff = config.reconnect_delay;
pacer.reset();
// Python synthesizes on every connection (I2PInterface.py:503,
// :533).
let synthesis = config
.tunnel_identity
.as_ref()
.and_then(|identity| identity.synthesis(&python_name));
open_client_connection(&rx, after_outage, &transport_tx, synthesis, &online_task).await;
// BufReader may have prefetched past the handshake; flush its tail first.
let buffered = stream_buf_reader.buffer().to_vec();
@@ -526,25 +769,26 @@ pub async fn spawn_i2p_client(
write_handle.abort();
let _ = write_handle.await;
if let Some(max) = config.max_reconnect_tries {
tries += 1;
if tries >= max {
tracing::warn!(name = %config.name, "I2P client: max reconnect tries reached");
return;
}
if pacer.give_up() {
tracing::warn!(name = %config.name, "I2P client: max reconnect tries reached");
let _ = transport_tx
.send(TransportMessage::DeregisterInterface { id })
.await;
return;
}
tracing::info!(
name = %config.name,
delay = backoff,
delay = pacer.backoff,
"I2P client: reconnecting"
);
tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
pacer.wait().await;
}
});
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 1064, false),
parent_id: None,
name,
mode,
@@ -559,19 +803,24 @@ pub async fn spawn_i2p_client(
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: None,
tx,
read_task,
})
}
/// Accept SAM streams; each becomes a sub-interface via `handle_tx`. Session
/// is recreated if the control socket drops.
/// Accept SAM streams; each becomes a sub-interface via `handle_tx`.
/// The session is recreated after an accept-connection or SAM handshake
/// failure. The session control socket is not monitored independently.
pub async fn spawn_i2p_server(
config: I2PServerConfig,
id: InterfaceId,
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let online = Arc::new(AtomicBool::new(false));
let name = config.name.clone();
let mode = config.mode;
@@ -599,21 +848,40 @@ pub async fn spawn_i2p_server(
}
};
let (session_reader, mut session_writer) = session_stream.into_split();
let mut session_buf_reader = BufReader::new(session_reader);
// Read unbuffered: a read buffer would keep SAM's reply, private key included.
let (mut session_reader, mut session_writer) = session_stream.into_split();
if let Err(e) = sam_hello(&mut session_writer, &mut session_buf_reader).await {
if let Err(e) = sam_hello(&mut session_writer, &mut session_reader).await {
tracing::warn!(name = %config.name, error = %e, "I2P server: SAM HELLO failed");
tokio::time::sleep(std::time::Duration::from_secs(config.reconnect_delay)).await;
continue;
}
let private_key = config.keyfile.as_deref();
let (private_key, store_key) = match (&config.keyfile, config.key_path.as_deref()) {
(Some(key), _) => (Some(Zeroizing::new(key.clone())), false),
(None, None) => (None, false),
(None, Some(path)) => match read_private_key(path) {
Ok(key) => {
let missing = key.is_none();
(key, missing)
}
Err(error) => {
tracing::warn!(
name = %config.name,
path = %path.display(),
%error,
"I2P server: cannot read its private key; this session's address is transient"
);
(None, false)
}
},
};
let our_dest = match sam_session_create(
&mut session_writer,
&mut session_buf_reader,
&mut session_reader,
&session_id,
private_key,
private_key.as_deref().map(String::as_str),
Some(NEW_DESTINATION_SIGNATURE_TYPE),
)
.await
{
@@ -636,6 +904,20 @@ pub async fn spawn_i2p_server(
dest_len = our_dest.len(),
"I2P server: session created, accepting streams"
);
if store_key
&& let Some(path) = config.key_path.as_deref()
&& let Err(error) = store_private_key(path, &our_dest)
{
tracing::warn!(
name = %config.name,
path = %path.display(),
%error,
"I2P server: failed to store its private key; its address changes with the next session"
);
}
if let Some(b32) = &config.b32 {
b32.send_replace(destination_b32(&our_dest));
}
online_task.store(true, Ordering::SeqCst);
// Each STREAM ACCEPT needs its own SAM TCP connection.
@@ -722,7 +1004,9 @@ pub async fn spawn_i2p_server(
let c_online_r = c_online.clone();
let c_rxb_r = c_rxb.clone();
let transport_tx2 = transport_tx.clone();
let transport_tx2 =
InterfaceTransportSender::new(client_id, transport_tx.actor_sender());
let child_owner = transport_tx2.owner();
let peer_name = client_name.clone();
let c_read_task = tokio::spawn(async move {
i2p_read_loop(
@@ -739,7 +1023,9 @@ pub async fn spawn_i2p_server(
let handle = InterfaceHandle {
id: client_id,
parent_id: Some(0),
owner: child_owner,
packet_capacity: InterfacePacketCapacity::new(500, 1064, false),
parent_id: Some(id),
name: client_name,
mode: config.mode,
direction: InterfaceDirection {
@@ -753,11 +1039,15 @@ pub async fn spawn_i2p_server(
online: c_online,
rxb: Some(c_rxb),
txb: Some(c_txb),
inspection: None,
tx: c_tx,
read_task: c_read_task,
};
if handle_tx.send(handle).await.is_err() {
if handoff_accepted_interface(&handle_tx, handle)
.await
.is_err()
{
tracing::warn!("I2P server: handle registry channel closed");
online_task.store(false, Ordering::SeqCst);
return;
@@ -775,7 +1065,9 @@ pub async fn spawn_i2p_server(
});
Ok(InterfaceHandle {
id: 0,
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 1064, false),
parent_id: None,
name,
mode,
@@ -790,6 +1082,7 @@ pub async fn spawn_i2p_server(
online,
rxb: Some(Arc::new(AtomicU64::new(0))),
txb: Some(Arc::new(AtomicU64::new(0))),
inspection: None,
tx,
read_task,
})
@@ -803,7 +1096,7 @@ async fn i2p_read_loop(
mut reader: tokio::net::tcp::OwnedReadHalf,
initial_data: &[u8],
interface_id: InterfaceId,
transport_tx: &mpsc::Sender<TransportMessage>,
transport_tx: &InterfaceTransportSender,
online: &AtomicBool,
rxb: &AtomicU64,
) {
@@ -866,13 +1159,51 @@ async fn i2p_read_loop(
online.store(false, Ordering::SeqCst);
}
/// Increments `tries` (when bounded) and returns `true` if the cap was hit.
fn check_max_tries(max: &Option<usize>, tries: &mut usize) -> bool {
if let Some(limit) = max {
*tries += 1;
*tries >= *limit
} else {
false
/// Reconnect pacing for the SAM client loop: bounded tries + exponential
/// backoff, reset on every successful connect.
struct ReconnectPacer {
tries: usize,
backoff: u64,
initial: u64,
max_tries: Option<usize>,
}
impl ReconnectPacer {
fn new(initial: u64, max_tries: Option<usize>) -> Self {
Self {
tries: 0,
backoff: initial,
initial,
max_tries,
}
}
/// Count a failure; `true` means the bounded try cap was hit.
fn give_up(&mut self) -> bool {
if let Some(limit) = self.max_tries {
self.tries += 1;
self.tries >= limit
} else {
false
}
}
/// Current delay, advancing the doubling (capped) for the next failure.
fn next_backoff(&mut self) -> u64 {
let current = self.backoff;
self.backoff = (self.backoff * 2).min(RECONNECT_WAIT_MAX);
current
}
/// Sleep the current backoff, then double it (capped).
async fn wait(&mut self) {
let delay = self.next_backoff();
tokio::time::sleep(std::time::Duration::from_secs(delay)).await;
}
fn reset(&mut self) {
self.tries = 0;
self.backoff = self.initial;
}
}
@@ -880,6 +1211,16 @@ fn check_max_tries(max: &Option<usize>, tries: &mut usize) -> bool {
mod tests {
use super::*;
#[test]
fn peer_python_name_matches_python() {
// Python 1.5.5 `str()` output for this interface.
let peer = "abcdefghijklmnop.b32.i2p";
assert_eq!(
I2PClientConfig::new(&format!("Golden I2P to {peer}"), peer).python_name(),
"I2PInterfacePeer[Golden I2P to abcdefghijklmnop.b32.i2p]"
);
}
#[test]
fn test_i2p_client_config() {
let cfg = I2PClientConfig::new("i2p0", "ABCDEF1234.b32.i2p");
@@ -988,6 +1329,49 @@ mod tests {
assert!(!sam_reply_has_token(&pairs, "NONEXISTENT"));
}
fn i2p_base64(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 64] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-~";
let mut text = String::new();
for chunk in bytes.chunks(3) {
let bits = chunk.iter().enumerate().fold(0u32, |bits, (n, byte)| {
bits | u32::from(*byte) << (16 - 8 * n)
});
for n in 0..=chunk.len() {
text.push(char::from(ALPHABET[(bits >> (18 - 6 * n)) as usize & 63]));
}
text.extend(std::iter::repeat_n('=', 3 - chunk.len()));
}
text
}
fn private_key(certificate: &[u8], secret: u8) -> Vec<u8> {
let mut key: Vec<u8> = (0..384).map(|n| n as u8).collect();
key.extend_from_slice(certificate);
key.extend(std::iter::repeat_n(secret, 288));
key
}
/// Only the destination, keys plus certificate, names the address
/// (i2plib sam.py:113-129); the golden is checked against i2plib in tests.
#[test]
fn the_b32_address_hashes_only_the_destination() {
let ed25519 = [5, 0, 4, 0, 7, 0, 0];
let b32 = destination_b32(&i2p_base64(&private_key(&ed25519, 0x42))).unwrap();
assert_eq!(b32.len(), 52);
assert!(b32.bytes().all(|c| matches!(c, b'a'..=b'z' | b'2'..=b'7')));
assert_eq!(
destination_b32(&i2p_base64(&private_key(&ed25519, 0x24))).as_ref(),
Some(&b32)
);
assert_ne!(
destination_b32(&i2p_base64(&private_key(&[0, 0, 0], 0x42))).as_ref(),
Some(&b32)
);
assert_eq!(destination_b32("not+base64"), None);
assert_eq!(destination_b32(&i2p_base64(&[0; 300])), None);
}
#[test]
fn test_generate_session_id() {
let id1 = generate_session_id();
@@ -1000,24 +1384,37 @@ mod tests {
}
#[test]
fn test_check_max_tries_unlimited() {
let max = None;
let mut tries = 0;
assert!(!check_max_tries(&max, &mut tries));
assert_eq!(tries, 0);
fn test_pacer_unlimited_never_gives_up() {
let mut pacer = ReconnectPacer::new(15, None);
for _ in 0..100 {
assert!(!pacer.give_up());
}
assert_eq!(pacer.tries, 0);
}
#[test]
fn test_check_max_tries_limited() {
let max = Some(3);
let mut tries = 0;
fn test_pacer_bounded_gives_up_at_cap() {
let mut pacer = ReconnectPacer::new(15, Some(3));
assert!(!pacer.give_up());
assert!(!pacer.give_up());
assert!(pacer.give_up());
assert_eq!(pacer.tries, 3);
}
assert!(!check_max_tries(&max, &mut tries));
assert_eq!(tries, 1);
assert!(!check_max_tries(&max, &mut tries));
assert_eq!(tries, 2);
assert!(check_max_tries(&max, &mut tries));
assert_eq!(tries, 3);
#[test]
fn test_pacer_backoff_doubles_capped_and_resets() {
let mut pacer = ReconnectPacer::new(15, Some(10));
assert_eq!(pacer.next_backoff(), 15);
assert_eq!(pacer.backoff, 30);
for _ in 0..10 {
pacer.next_backoff();
}
assert_eq!(pacer.backoff, RECONNECT_WAIT_MAX);
let _ = pacer.give_up();
pacer.reset();
assert_eq!(pacer.tries, 0);
assert_eq!(pacer.backoff, 15);
}
#[test]
+43 -74
View File
@@ -1,4 +1,4 @@
//! KISS TNC framing — used by KISS, AX.25-KISS, RNode, RNodeMulti, TCP/I2P.
//! KISS TNC framing for KISS, AX.25-KISS, RNode, RNodeMulti, and optionally TCP.
//! Wire: `[FEND][CMD][escaped_payload][FEND]`.
pub const FEND: u8 = 0xC0;
@@ -121,87 +121,31 @@ pub fn frame_with_command(cmd: u8, data: &[u8]) -> Vec<u8> {
out
}
/// Classic KISS deframer: high nibble of the command byte is a TNC port, so
/// frames are returned as `(command & CMD_MASK, data)`. Thin wrapper over
/// [`RawKissDeframer`], which owns the framing state machine.
pub struct KissDeframer {
buffer: Vec<u8>,
in_frame: bool,
command: u8,
/// Reusable scratch for unescape output.
unescape_scratch: Vec<u8>,
inner: RawKissDeframer,
}
impl KissDeframer {
pub fn new() -> Self {
Self {
buffer: Vec::with_capacity(DEFRAME_BUF_CAPACITY),
in_frame: false,
command: CMD_UNKNOWN,
unescape_scratch: Vec::with_capacity(DEFRAME_BUF_CAPACITY),
inner: RawKissDeframer::new(),
}
}
/// Returns complete frames as (command, data) pairs.
pub fn feed(&mut self, data: &[u8]) -> Vec<(u8, Vec<u8>)> {
let mut frames = Vec::new();
let mut i = 0;
while i < data.len() {
match data[i..].iter().position(|&b| b == FEND) {
Some(rel) => {
let hit = i + rel;
if self.in_frame {
self.append_in_frame(&data[i..hit]);
if !self.buffer.is_empty() {
self.unescape_scratch.clear();
unescape_into(&self.buffer, &mut self.unescape_scratch);
let frame_data = std::mem::replace(
&mut self.unescape_scratch,
Vec::with_capacity(DEFRAME_BUF_CAPACITY),
);
frames.push((self.command & CMD_MASK, frame_data));
}
self.buffer.clear();
}
self.in_frame = true;
self.command = CMD_UNKNOWN;
i = hit + 1;
}
None => {
if self.in_frame {
self.append_in_frame(&data[i..]);
}
return frames;
}
}
let mut frames = self.inner.feed(data);
for frame in &mut frames {
frame.0 &= CMD_MASK;
}
frames
}
/// Append `chunk` to the in-frame buffer. The first byte after a FEND is
/// the command byte (consumed separately); subsequent bytes are payload
/// up to `MAX_FRAME_SIZE`. Overflow drops the in-progress frame and waits
/// for the next FEND to resync — matching the previous byte-loop.
fn append_in_frame(&mut self, chunk: &[u8]) {
let mut chunk = chunk;
if self.command == CMD_UNKNOWN {
if let Some((&first, rest)) = chunk.split_first() {
self.command = first;
chunk = rest;
} else {
return;
}
}
if self.buffer.len() + chunk.len() > MAX_FRAME_SIZE {
self.buffer.clear();
self.in_frame = false;
self.command = CMD_UNKNOWN;
return;
}
self.buffer.extend_from_slice(chunk);
}
pub fn reset(&mut self) {
self.buffer.clear();
self.in_frame = false;
self.command = CMD_UNKNOWN;
self.inner.reset();
}
}
@@ -220,7 +164,8 @@ impl Default for KissDeframer {
pub struct RawKissDeframer {
buffer: Vec<u8>,
in_frame: bool,
command: u8,
command: Option<u8>,
/// Reusable scratch for unescape output.
unescape_scratch: Vec<u8>,
}
@@ -229,7 +174,7 @@ impl RawKissDeframer {
Self {
buffer: Vec::with_capacity(DEFRAME_BUF_CAPACITY),
in_frame: false,
command: CMD_UNKNOWN,
command: None,
unescape_scratch: Vec::with_capacity(DEFRAME_BUF_CAPACITY),
}
}
@@ -251,12 +196,14 @@ impl RawKissDeframer {
&mut self.unescape_scratch,
Vec::with_capacity(DEFRAME_BUF_CAPACITY),
);
frames.push((self.command, frame_data));
if let Some(command) = self.command {
frames.push((command, frame_data));
}
}
self.buffer.clear();
}
self.in_frame = true;
self.command = CMD_UNKNOWN;
self.command = None;
i = hit + 1;
}
None => {
@@ -270,11 +217,15 @@ impl RawKissDeframer {
frames
}
/// Append `chunk` to the in-frame buffer. The first byte after a FEND is
/// the command byte (consumed separately); subsequent bytes are payload
/// up to `MAX_FRAME_SIZE`. Overflow drops the in-progress frame and waits
/// for the next FEND to resync — matching the previous byte-loop.
fn append_in_frame(&mut self, chunk: &[u8]) {
let mut chunk = chunk;
if self.command == CMD_UNKNOWN {
if self.command.is_none() {
if let Some((&first, rest)) = chunk.split_first() {
self.command = first;
self.command = Some(first);
chunk = rest;
} else {
return;
@@ -283,7 +234,7 @@ impl RawKissDeframer {
if self.buffer.len() + chunk.len() > MAX_FRAME_SIZE {
self.buffer.clear();
self.in_frame = false;
self.command = CMD_UNKNOWN;
self.command = None;
return;
}
self.buffer.extend_from_slice(chunk);
@@ -292,7 +243,7 @@ impl RawKissDeframer {
pub fn reset(&mut self) {
self.buffer.clear();
self.in_frame = false;
self.command = CMD_UNKNOWN;
self.command = None;
}
}
@@ -377,6 +328,24 @@ mod tests {
assert_eq!(frames[0].0, CMD_DATA);
}
#[test]
fn extended_fe_command_survives_every_chunk_boundary() {
let expected = vec![(0xfe, vec![1, FEND, FESC, 2])];
let frame = frame_with_command(0xfe, &expected[0].1);
for split in 0..=frame.len() {
let mut decoder = RawKissDeframer::new();
let mut got = decoder.feed(&frame[..split]);
got.extend(decoder.feed(&frame[split..]));
assert_eq!(got, expected, "split {split}");
}
let mut decoder = RawKissDeframer::new();
let got: Vec<_> = frame
.iter()
.flat_map(|byte| decoder.feed(&[*byte]))
.collect();
assert_eq!(got, expected);
}
#[test]
fn test_raw_deframer_preserves_extended_commands() {
let mut deframer = RawKissDeframer::new();
+183 -52
View File
@@ -1,5 +1,6 @@
//! Serial port + KISS framing; CMD_DATA + CMD_READY flow control.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;
@@ -28,6 +29,16 @@ pub struct KissInterfaceConfig {
pub txtail: Option<u8>,
/// Honour CMD_READY from TNC.
pub flow_control: bool,
/// Station-ID delay in seconds, armed by data transmission. Both this field
/// and `id_callsign` must be set to enable automatic beacons.
///
/// In this implementation, callsigns shorter than 15 bytes are padded for
/// transmission but compared with the unpadded value when resetting the timer.
/// After becoming due, such a beacon can repeat on each one-second idle poll,
/// subject to flow control and successful writes. Set either option to `None`
/// to disable automatic beaconing.
pub id_interval: Option<u64>,
pub id_callsign: Option<Vec<u8>>,
}
impl KissInterfaceConfig {
@@ -45,25 +56,47 @@ impl KissInterfaceConfig {
txdelay: None,
txtail: None,
flow_control: false,
id_interval: None,
id_callsign: None,
}
}
}
/// Beacon frame payload: callsign zero-padded to the 15-byte minimum
/// (Python `KISSInterface.read_loop`).
pub fn beacon_frame_payload(id_callsign: &[u8]) -> Vec<u8> {
let mut frame = id_callsign.to_vec();
while frame.len() < 15 {
frame.push(0x00);
}
frame
}
pub async fn spawn_kiss_interface(
config: KissInterfaceConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let port = serialport::new(&config.port, config.baud_rate)
.data_bits(config.data_bits)
.parity(config.parity)
.stop_bits(config.stop_bits)
.timeout(Duration::from_millis(KISS_READ_TIMEOUT_MS))
.open()
.map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("kiss serial open: {}", e))
})?;
let port = crate::serial::open_port(
serialport::new(&config.port, config.baud_rate)
.data_bits(config.data_bits)
.parity(config.parity)
.stop_bits(config.stop_bits)
.timeout(Duration::from_millis(KISS_READ_TIMEOUT_MS)),
)
.map_err(|e| crate::traits::InterfaceError::SendFailed(format!("kiss serial open: {}", e)))?;
spawn_kiss_with_port(config, id, transport_tx, port).await
}
async fn spawn_kiss_with_port(
config: KissInterfaceConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
port: Box<dyn serialport::SerialPort>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
tracing::info!(
name = %config.name,
port = %config.port,
@@ -75,6 +108,7 @@ pub async fn spawn_kiss_interface(
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let (tx, mut rx) = mpsc::channel::<Bytes>(256);
let background = crate::background_announce::register(&tx)?;
let name = config.name.clone();
let mode = config.mode;
let flow_control = config.flow_control;
@@ -113,18 +147,69 @@ pub async fn spawn_kiss_interface(
let online_w = online.clone();
let ready_w = ready.clone();
let txb_w = shared_txb.clone();
let beacon = config
.id_interval
.zip(config.id_callsign.clone())
.map(|(interval, callsign)| (Duration::from_secs(interval), Bytes::from(callsign)));
tokio::spawn(async move {
let mut port_w = port_write;
while let Some(data) = rx.recv().await {
txb_w.fetch_add(data.len() as u64, std::sync::atomic::Ordering::Relaxed);
// Flow control: bounded wait so a stuck TNC can't hang transmit.
if flow_control {
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
while !ready_w.load(Ordering::SeqCst) {
if tokio::time::Instant::now() >= deadline {
tracing::warn!("KISS flow control timeout, proceeding anyway");
break;
// Python first_tx semantics: armed by the first data TX after a
// beacon; cleared when the beacon goes out.
let mut first_tx: Option<tokio::time::Instant> = None;
loop {
let background_packet = if rx.is_empty() && online_w.load(Ordering::SeqCst) {
background.try_start_when(rns_transport::now_f64(), || {
!flow_control
|| ready_w
.compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
.is_ok()
})
} else {
None
};
let data = if let Some(packet) = &background_packet {
packet.raw().clone()
} else if let Some((interval, ref callsign)) = beacon {
match tokio::time::timeout(Duration::from_secs(1), rx.recv()).await {
Ok(Some(data)) => data,
Ok(None) => break,
Err(_) => {
let due = first_tx.is_some_and(|t| t.elapsed() >= interval);
if !due {
continue;
}
tracing::debug!("KISS transmitting station-ID beacon");
Bytes::from(beacon_frame_payload(callsign))
}
}
} else {
match tokio::time::timeout(Duration::from_millis(100), rx.recv()).await {
Ok(Some(data)) => data,
Ok(None) => break,
Err(_) => continue,
}
};
// Python KISSInterface.py:267-271 compares the unpadded callsign,
// so a padded (<15 byte) beacon re-arms the timer and beacons
// repeat every id_interval once anything has been sent. Kept
// bug-for-bug for parity.
let is_beacon = beacon
.as_ref()
.is_some_and(|(_, callsign)| data == *callsign);
if is_beacon {
first_tx = None;
} else if first_tx.is_none() {
first_tx = Some(tokio::time::Instant::now());
}
txb_w.fetch_add(data.len() as u64, std::sync::atomic::Ordering::Relaxed);
// READY is one packet permit. A timeout must never synthesize it.
if flow_control && background_packet.is_none() {
while ready_w
.compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
.is_err()
{
tokio::time::sleep(Duration::from_millis(10)).await;
if !online_w.load(Ordering::SeqCst) {
return;
@@ -132,25 +217,13 @@ pub async fn spawn_kiss_interface(
}
}
let framed = kiss::frame(&data);
let online_ref = online_w.clone();
let result = tokio::task::spawn_blocking(move || {
use std::io::Write;
port_w.write_all(&framed)?;
port_w.flush()?;
Ok::<_, std::io::Error>(port_w)
})
.await;
match result {
Ok(Ok(p)) => {
match crate::serial_io::blocking_write_all(port_w, framed).await {
Ok(p) => {
port_w = p;
}
Ok(Err(e)) => {
tracing::warn!(error = %e, "KISS write error");
online_ref.store(false, Ordering::SeqCst);
break;
}
Err(e) => {
tracing::warn!(error = %e, "KISS write task panicked");
tracing::warn!(error = %e, "KISS write error");
online_w.store(false, Ordering::SeqCst);
break;
}
}
@@ -169,18 +242,8 @@ pub async fn spawn_kiss_interface(
if !online_r.load(Ordering::SeqCst) {
break;
}
let result = tokio::task::spawn_blocking(move || {
use std::io::Read;
match port_r.read(&mut buf) {
Ok(n) => Ok((port_r, buf, n)),
Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok((port_r, buf, 0)),
Err(e) => Err((port_r, e)),
}
})
.await;
match result {
Ok(Ok((p, b, n))) => {
match crate::serial_io::poll_read(port_r, buf).await {
Ok((p, b, n)) => {
port_r = p;
buf = b;
if n > 0 {
@@ -217,13 +280,8 @@ pub async fn spawn_kiss_interface(
}
}
}
Ok(Err((_p, e))) => {
tracing::warn!(error = %e, "KISS read error");
online_r.store(false, Ordering::SeqCst);
return;
}
Err(e) => {
tracing::warn!(error = %e, "KISS read task panicked");
tracing::warn!(error = %e, "KISS read error");
online_r.store(false, Ordering::SeqCst);
return;
}
@@ -233,6 +291,8 @@ pub async fn spawn_kiss_interface(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 564, false),
parent_id: None,
name,
mode,
@@ -247,6 +307,7 @@ pub async fn spawn_kiss_interface(
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: None,
tx,
read_task,
})
@@ -262,6 +323,20 @@ mod tests {
assert_eq!(cfg.baud_rate, 9600);
assert!(!cfg.flow_control);
assert_eq!(cfg.mode, InterfaceMode::Full);
assert!(cfg.id_interval.is_none() && cfg.id_callsign.is_none());
}
/// Python KISSInterface.py:350-353 — beacon payload is the callsign
/// zero-padded to 15 bytes; longer callsigns pass through unchanged.
#[test]
fn test_beacon_frame_payload_padding() {
let short = beacon_frame_payload(b"MYCALL-0");
assert_eq!(short.len(), 15);
assert_eq!(&short[..8], b"MYCALL-0");
assert!(short[8..].iter().all(|&b| b == 0));
let long = beacon_frame_payload(b"AVERYLONGCALLSIGN");
assert_eq!(long, b"AVERYLONGCALLSIGN");
}
#[test]
@@ -290,4 +365,60 @@ mod tests {
let cfg = KissInterfaceConfig::new("kiss0", "/dev/ttyS0", 9600);
assert_eq!(cfg.mode, InterfaceMode::Full);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn background_actor_kiss_pty_preserves_control_and_one_packet_ready() {
use serialport::SerialPort;
use std::io::{Read, Write};
let (mut master, slave) = serialport::TTYPort::pair().unwrap();
let name = slave.name().unwrap();
master.set_timeout(Duration::from_millis(300)).unwrap();
let (inbound, mut received) = mpsc::channel(4);
let mut config = KissInterfaceConfig::new("arbitrary TNC", &name, 9600);
config.flow_control = true;
// macOS pseudo terminals cannot accept the hardware baud ioctl;
// inject the already-open pair into the same production driver.
let driver = spawn_kiss_with_port(config, 1, inbound, Box::new(slave))
.await
.unwrap();
driver.owner.mark_registered();
let mut revoke = kiss::frame_with_command(kiss::CMD_READY, &[0]);
revoke.extend(kiss::frame(b"read barrier"));
master.write_all(&revoke).unwrap();
received.recv().await.unwrap();
let (actor, control, raw) = crate::background_announce::scheduled_actor(driver.tx.clone());
tokio::time::sleep(Duration::from_millis(300)).await;
let mut probe = [0; 2048];
assert!(
master.read(&mut probe).is_err(),
"no timeout may synthesize READY"
);
driver
.tx
.send(Bytes::from_static(b"local control"))
.await
.unwrap();
master
.write_all(&kiss::frame_with_command(kiss::CMD_READY, &[1]))
.unwrap();
let expected = kiss::frame(b"local control");
let mut actual = vec![0; expected.len()];
master.read_exact(&mut actual).unwrap();
assert_eq!(actual, expected);
assert!(
master.read(&mut probe).is_err(),
"one READY cannot write two packets"
);
master
.write_all(&kiss::frame_with_command(kiss::CMD_READY, &[1]))
.unwrap();
let expected = kiss::frame(&raw);
let mut actual = vec![0; expected.len()];
master.read_exact(&mut actual).unwrap();
assert_eq!(actual, expected);
driver.online.store(false, Ordering::SeqCst);
control.send(TransportMessage::Shutdown).await.unwrap();
actor.await.unwrap();
driver.read_task.await.unwrap();
}
}
+26 -3
View File
@@ -1,9 +1,14 @@
//! Network interface implementations for Reticulum.
//! Each module provides a spawn function returning a Tokio task driving a
//! concrete transport; [`traits::Interface`] is the common abstraction.
//! Network interface implementations and framing helpers for Reticulum.
//! Transport drivers expose [`traits::InterfaceHandle`] for registration with
//! the transport actor; helper modules provide codecs, settings, and lifecycle
//! state. Serial, BLE, and Android USB APIs have feature or platform gates.
#[cfg(target_os = "android")]
pub mod android_usb;
#[cfg(any(target_os = "android", test))]
mod android_usb_lifecycle;
#[cfg(any(target_os = "android", test))]
mod android_usb_setup;
pub mod auto;
pub mod ax25kiss;
pub mod backbone;
@@ -13,12 +18,16 @@ pub mod ble_central_apple;
pub mod ble_central_apple_connect;
#[cfg(feature = "ble")]
pub mod ble_central_lifecycle;
#[cfg(all(feature = "ble", any(target_os = "windows", target_os = "linux", test)))]
mod ble_connect;
#[cfg(feature = "ble")]
pub mod ble_peer;
#[cfg(feature = "ble")]
pub mod ble_peer_lifecycle;
#[cfg(feature = "ble")]
pub mod ble_rnode;
#[cfg(all(feature = "ble", any(target_os = "ios", target_os = "macos", test)))]
mod ble_tx_queue;
pub mod hdlc;
pub mod i2p;
pub mod kiss;
@@ -28,12 +37,26 @@ pub mod local;
pub mod pipe;
pub mod rnode;
pub mod rnode_admin;
pub mod rnode_capabilities;
#[cfg(any(
feature = "serial",
feature = "rnode-tcp",
feature = "ble",
target_os = "android",
test
))]
mod rnode_capability_preflight;
#[cfg(feature = "serial")]
pub mod rnode_multi;
pub mod rnode_protocol;
#[cfg(feature = "serial")]
pub mod serial;
#[cfg(feature = "serial")]
mod serial_io;
pub mod socket_tuning;
pub mod tcp;
pub mod traits;
pub mod udp;
pub mod weave;
mod background_announce;
+554 -203
View File
@@ -1,6 +1,8 @@
//! Shared-instance IPC. Unix domain sockets where available, TCP on
//! 127.0.0.1 as fallback. HDLC-framed.
//! Shared-instance IPC with HDLC framing. Uses Unix domain sockets on Unix
//! and TCP on non-Unix platforms. TCP defaults to loopback; a `tcp://` value
//! in `socket_path` overrides that endpoint.
use rns_transport::messages::{InterfaceOwner, InterfacePacketCapacity, InterfaceTransportSender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -9,25 +11,31 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::mpsc;
use crate::hdlc;
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
use crate::traits::{
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
};
use rns_transport::messages::{InboundPacket, TransportMessage};
pub const LOCAL_MTU: u32 = 262_144;
/// Default filesystem socket path for non-Linux fallback use.
/// Default filesystem socket path for local IPC.
pub const DEFAULT_SOCKET_PATH: &str = "/tmp/rns_reticulum.sock";
/// On Android `/tmp` isn't writable; falls back to caller's data directory.
/// Return `data_dir/cache/rns_reticulum.sock` on Android when `data_dir` is
/// provided; otherwise return [`DEFAULT_SOCKET_PATH`]. This helper creates no
/// directories and does not check whether the returned path is writable.
pub fn socket_path(data_dir: Option<&std::path::Path>) -> std::path::PathBuf {
if cfg!(target_os = "android") {
if let Some(dir) = data_dir {
return dir.join("cache").join("rns_reticulum.sock");
}
if cfg!(target_os = "android")
&& let Some(dir) = data_dir
{
return dir.join("cache").join("rns_reticulum.sock");
}
std::path::PathBuf::from(DEFAULT_SOCKET_PATH)
}
pub const FALLBACK_TCP_PORT: u16 = 37428;
#[cfg(unix)]
const LOCAL_RECONNECT_WAIT_SECS: u64 = 8;
pub fn socket_path_for(instance_name: &str) -> String {
format!("/tmp/rns_{}.sock", instance_name)
@@ -57,7 +65,8 @@ fn display_socket_path(path: &str) -> String {
#[derive(Debug, Clone)]
pub struct LocalServerConfig {
/// Unix socket path (ignored on non-Unix).
/// Unix socket path. On non-Unix platforms, a nonempty `tcp://host:port`
/// value selects the TCP endpoint; other values use the loopback default.
pub socket_path: String,
pub name: String,
}
@@ -89,7 +98,7 @@ impl Default for LocalClientConfig {
async fn local_read_loop<R: AsyncReadExt + Unpin>(
mut reader: R,
interface_id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
transport_tx: InterfaceTransportSender,
online: Arc<AtomicBool>,
rxb: Arc<AtomicU64>,
) {
@@ -148,6 +157,179 @@ async fn local_write_loop<W: AsyncWriteExt + Unpin>(
online.store(false, Ordering::SeqCst);
}
#[cfg(unix)]
enum LocalClientConnectionEnd {
Disconnected,
Detached,
}
/// Drive both halves of one initiating local-client connection in a single
/// task. Keeping the persistent outbound receiver here lets the Unix client
/// retain one stable `InterfaceHandle` while replacing only the socket after a
/// shared-instance restart.
#[cfg(unix)]
async fn run_local_client_connection<R, W>(
mut reader: R,
mut writer: W,
rx: &mut mpsc::Receiver<Bytes>,
interface_id: InterfaceId,
transport_tx: &InterfaceTransportSender,
rxb: &AtomicU64,
txb: &AtomicU64,
) -> LocalClientConnectionEnd
where
R: AsyncReadExt + Unpin,
W: AsyncWriteExt + Unpin,
{
let mut buf = [0u8; 8192];
let mut deframer = hdlc::HdlcDeframer::new();
loop {
tokio::select! {
read = reader.read(&mut buf) => {
match read {
Ok(0) => {
tracing::info!(interface_id, "local client read: EOF");
return LocalClientConnectionEnd::Disconnected;
}
Ok(n) => {
rxb.fetch_add(n as u64, Ordering::Relaxed);
for frame in deframer.feed(&buf[..n]) {
if frame.is_empty() {
continue;
}
let msg = TransportMessage::Inbound(InboundPacket {
raw: Bytes::from(frame),
interface_id,
rssi: None,
snr: None,
q: None,
});
if transport_tx.send(msg).await.is_err() {
tracing::warn!(interface_id, "transport channel closed");
return LocalClientConnectionEnd::Detached;
}
}
}
Err(error) => {
tracing::warn!(interface_id, %error, "local client read error");
return LocalClientConnectionEnd::Disconnected;
}
}
}
outbound = rx.recv() => {
let Some(data) = outbound else {
return LocalClientConnectionEnd::Detached;
};
let framed = hdlc::frame(&data);
if let Err(error) = writer.write_all(&framed).await {
tracing::warn!(interface_id, %error, "local client write error");
return LocalClientConnectionEnd::Disconnected;
}
txb.fetch_add(framed.len() as u64, Ordering::Relaxed);
}
}
}
}
/// Per-stream wiring shared by both platform variants: write loop, read task,
/// and the connection's `InterfaceHandle`. `dereg_on_disconnect` is set for
/// accepted server-side clients so transport drops them immediately on EOF.
fn wire_local_stream<R, W>(
id: InterfaceId,
name: String,
parent_id: Option<InterfaceId>,
reader: R,
writer: W,
transport_tx: mpsc::Sender<TransportMessage>,
dereg_on_disconnect: bool,
) -> InterfaceHandle
where
R: AsyncReadExt + Unpin + Send + 'static,
W: AsyncWriteExt + Unpin + Send + 'static,
{
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let online = Arc::new(AtomicBool::new(true));
let rxb = Arc::new(AtomicU64::new(0));
let txb = Arc::new(AtomicU64::new(0));
let (tx, rx) = mpsc::channel::<Bytes>(256);
tokio::spawn(local_write_loop(writer, rx, online.clone(), txb.clone()));
let online_r = online.clone();
let rxb_r = rxb.clone();
let task_name = name.clone();
let dereg_tx = transport_tx.clone();
let read_task = tokio::spawn(async move {
local_read_loop(reader, id, transport_tx, online_r, rxb_r).await;
if dereg_on_disconnect {
tracing::info!(name = %task_name, "local client disconnected");
// Proactively notify so transport drops immediately.
let _ = dereg_tx
.send(TransportMessage::DeregisterInterface { id })
.await;
}
});
InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(262144, 262144, true),
parent_id,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online,
rxb: Some(rxb),
txb: Some(txb),
inspection: None,
tx,
read_task,
}
}
/// Handle for the listener pseudo-interface: inbound-only, no per-byte
/// counters of its own.
fn server_listener_handle(
id: InterfaceId,
name: String,
online: Arc<AtomicBool>,
tx: mpsc::Sender<Bytes>,
read_task: tokio::task::JoinHandle<()>,
owner: InterfaceOwner,
) -> InterfaceHandle {
InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(262144, 262144, true),
parent_id: None,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
outbound: false,
forward: false,
repeat: false,
},
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online,
rxb: Some(Arc::new(AtomicU64::new(0))),
txb: Some(Arc::new(AtomicU64::new(0))),
inspection: None,
tx,
read_task,
}
}
#[cfg(unix)]
mod platform {
use super::*;
@@ -218,10 +400,12 @@ mod platform {
pub async fn spawn_local_server_impl(
config: LocalServerConfig,
id: InterfaceId,
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let owner = InterfaceOwner::new();
let listener = bind_unix_listener(&config.socket_path)?;
tracing::info!(name = %config.name, path = %display_socket_path(&config.socket_path), "local server listening");
@@ -238,51 +422,20 @@ mod platform {
let client_name = format!("{}/client_{}", config.name, client_id);
tracing::info!(name = %client_name, "local client connected");
let c_online = Arc::new(AtomicBool::new(true));
let c_rxb = Arc::new(AtomicU64::new(0));
let c_txb = Arc::new(AtomicU64::new(0));
let (c_tx, c_rx) = mpsc::channel::<Bytes>(256);
let (reader, writer) = stream.into_split();
let c_online2 = c_online.clone();
let c_txb2 = c_txb.clone();
tokio::spawn(local_write_loop(writer, c_rx, c_online2, c_txb2));
let c_online3 = c_online.clone();
let c_rxb2 = c_rxb.clone();
let transport_tx2 = transport_tx.clone();
let dereg_tx = transport_tx.clone();
let cname = client_name.clone();
let read_handle = tokio::spawn(async move {
local_read_loop(reader, client_id, transport_tx2, c_online3, c_rxb2)
.await;
tracing::info!(name = %cname, "local client disconnected");
// Proactively notify so transport drops immediately.
let _ = dereg_tx
.send(TransportMessage::DeregisterInterface { id: client_id })
.await;
});
let handle = InterfaceHandle {
id: client_id,
parent_id: Some(0),
name: client_name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online: c_online,
rxb: Some(c_rxb),
txb: Some(c_txb),
tx: c_tx,
read_task: read_handle,
};
if handle_tx.send(handle).await.is_err() {
let handle = wire_local_stream(
client_id,
client_name,
Some(id),
reader,
writer,
transport_tx.clone(),
true,
);
if handoff_accepted_interface(&handle_tx, handle)
.await
.is_err()
{
tracing::warn!("local handle registry closed");
break;
}
@@ -296,28 +449,9 @@ mod platform {
online2.store(false, Ordering::SeqCst);
});
let server_rxb = Arc::new(AtomicU64::new(0));
let server_txb = Arc::new(AtomicU64::new(0));
Ok(InterfaceHandle {
id: 0,
parent_id: None,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
outbound: false,
forward: false,
repeat: false,
},
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online,
rxb: Some(server_rxb),
txb: Some(server_txb),
tx,
read_task,
})
Ok(server_listener_handle(
id, name, online, tx, read_task, owner,
))
}
pub async fn spawn_local_client_impl(
@@ -325,30 +459,88 @@ mod platform {
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let stream = connect_unix_stream(&config.socket_path).await?;
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let initial_stream = connect_unix_stream(&config.socket_path).await?;
tracing::info!(name = %config.name, path = %display_socket_path(&config.socket_path), "local client connected");
let online = Arc::new(AtomicBool::new(true));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let (tx, rx) = mpsc::channel::<Bytes>(256);
let (reader, writer) = stream.into_split();
let rxb = Arc::new(AtomicU64::new(0));
let txb = Arc::new(AtomicU64::new(0));
let (tx, mut rx) = mpsc::channel::<Bytes>(256);
let online_w = online.clone();
let task_txb = shared_txb.clone();
tokio::spawn(local_write_loop(writer, rx, online_w, task_txb));
let online_r = online.clone();
let task_rxb = shared_rxb.clone();
let name = config.name.clone();
let task_online = online.clone();
let task_rxb = rxb.clone();
let task_txb = txb.clone();
let task_name = config.name.clone();
let task_socket_path = config.socket_path.clone();
let read_task = tokio::spawn(async move {
local_read_loop(reader, id, transport_tx, online_r, task_rxb).await;
let mut stream = initial_stream;
loop {
let (reader, writer) = stream.into_split();
let end = run_local_client_connection(
reader,
writer,
&mut rx,
id,
&transport_tx,
&task_rxb,
&task_txb,
)
.await;
task_online.store(false, Ordering::SeqCst);
if matches!(end, LocalClientConnectionEnd::Detached)
|| transport_tx.is_closed()
|| rx.is_closed()
{
return;
}
tracing::warn!(
name = %task_name,
path = %display_socket_path(&task_socket_path),
wait_seconds = LOCAL_RECONNECT_WAIT_SECS,
"local shared-instance connection lost; reconnecting"
);
loop {
tokio::time::sleep(std::time::Duration::from_secs(LOCAL_RECONNECT_WAIT_SECS))
.await;
if transport_tx.is_closed() || rx.is_closed() {
return;
}
match connect_unix_stream(&task_socket_path).await {
Ok(connected) => {
stream = connected;
// Python drops traffic while offline (LocalInterface.py:218).
while rx.try_recv().is_ok() {}
task_online.store(true, Ordering::SeqCst);
tracing::info!(
name = %task_name,
path = %display_socket_path(&task_socket_path),
"local shared-instance client reconnected"
);
break;
}
Err(error) => {
tracing::debug!(
name = %task_name,
path = %display_socket_path(&task_socket_path),
%error,
"local shared-instance reconnect failed"
);
}
}
}
}
});
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(262144, 262144, true),
parent_id: None,
name,
name: config.name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
@@ -359,8 +551,9 @@ mod platform {
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
rxb: Some(rxb),
txb: Some(txb),
inspection: None,
tx,
read_task,
})
@@ -385,11 +578,13 @@ mod platform {
pub async fn spawn_local_server_impl(
config: LocalServerConfig,
id: InterfaceId,
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let addr = fallback_tcp_addr(&config.socket_path);
let owner = InterfaceOwner::new();
let listener = TcpListener::bind(&addr).await?;
let local_addr = listener.local_addr()?;
tracing::info!(name = %config.name, addr = %local_addr, "local server (TCP fallback) listening");
@@ -407,51 +602,20 @@ mod platform {
let client_name = format!("{}/client_{}", config.name, client_id);
tracing::info!(name = %client_name, peer = %peer, "local client connected (TCP)");
let c_online = Arc::new(AtomicBool::new(true));
let c_rxb = Arc::new(AtomicU64::new(0));
let c_txb = Arc::new(AtomicU64::new(0));
let (c_tx, c_rx) = mpsc::channel::<Bytes>(256);
let (reader, writer) = stream.into_split();
let c_online2 = c_online.clone();
let c_txb2 = c_txb.clone();
tokio::spawn(local_write_loop(writer, c_rx, c_online2, c_txb2));
let c_online3 = c_online.clone();
let c_rxb2 = c_rxb.clone();
let transport_tx2 = transport_tx.clone();
let dereg_tx = transport_tx.clone();
let cname = client_name.clone();
let read_handle = tokio::spawn(async move {
local_read_loop(reader, client_id, transport_tx2, c_online3, c_rxb2)
.await;
tracing::info!(name = %cname, "local client disconnected");
// See unix variant — notify proactively to avoid zombies.
let _ = dereg_tx
.send(TransportMessage::DeregisterInterface { id: client_id })
.await;
});
let handle = InterfaceHandle {
id: client_id,
parent_id: Some(0),
name: client_name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online: c_online,
rxb: Some(c_rxb),
txb: Some(c_txb),
tx: c_tx,
read_task: read_handle,
};
if handle_tx.send(handle).await.is_err() {
let handle = wire_local_stream(
client_id,
client_name,
Some(id),
reader,
writer,
transport_tx.clone(),
true,
);
if handoff_accepted_interface(&handle_tx, handle)
.await
.is_err()
{
tracing::warn!("local handle registry closed");
break;
}
@@ -465,28 +629,9 @@ mod platform {
online2.store(false, Ordering::SeqCst);
});
let server_rxb = Arc::new(AtomicU64::new(0));
let server_txb = Arc::new(AtomicU64::new(0));
Ok(InterfaceHandle {
id: 0,
parent_id: None,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
outbound: false,
forward: false,
repeat: false,
},
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online,
rxb: Some(server_rxb),
txb: Some(server_txb),
tx,
read_task,
})
Ok(server_listener_handle(
id, name, online, tx, read_task, owner,
))
}
pub async fn spawn_local_client_impl(
@@ -498,42 +643,16 @@ mod platform {
let stream = TcpStream::connect(&addr).await?;
tracing::info!(name = %config.name, addr = %addr, "local client connected (TCP fallback)");
let online = Arc::new(AtomicBool::new(true));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let (tx, rx) = mpsc::channel::<Bytes>(256);
let (reader, writer) = stream.into_split();
let online_w = online.clone();
let task_txb = shared_txb.clone();
tokio::spawn(local_write_loop(writer, rx, online_w, task_txb));
let online_r = online.clone();
let task_rxb = shared_rxb.clone();
let name = config.name.clone();
let read_task = tokio::spawn(async move {
local_read_loop(reader, id, transport_tx, online_r, task_rxb).await;
});
Ok(InterfaceHandle {
Ok(wire_local_stream(
id,
parent_id: None,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
tx,
read_task,
})
config.name.clone(),
None,
reader,
writer,
transport_tx,
false,
))
}
}
@@ -545,11 +664,12 @@ mod platform {
)]
pub async fn spawn_local_server(
config: LocalServerConfig,
id: InterfaceId,
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
platform::spawn_local_server_impl(config, id_gen, transport_tx, handle_tx).await
platform::spawn_local_server_impl(config, id, id_gen, transport_tx, handle_tx).await
}
#[tracing::instrument(
@@ -585,6 +705,7 @@ mod tests {
#[cfg(not(unix))]
{
let _ = prefix;
let listener =
std::net::TcpListener::bind("127.0.0.1:0").expect("reserve local test port");
let port = listener.local_addr().expect("read local test port").port();
@@ -593,6 +714,24 @@ mod tests {
}
}
/// The client's real reconnect wait, plus one missed attempt on a loaded host.
#[cfg(unix)]
const RECONNECT_DEADLINE: std::time::Duration =
std::time::Duration::from_secs(2 * LOCAL_RECONNECT_WAIT_SECS);
/// The server hands off an accepted client before that client has
/// necessarily published itself online, so wait for the flag itself.
#[cfg(unix)]
async fn wait_until_online(online: &AtomicBool) {
tokio::time::timeout(std::time::Duration::from_secs(3), async {
while !online.load(Ordering::SeqCst) {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.expect("stable client handle must return online after reconnect");
}
#[test]
fn test_local_mtu() {
assert_eq!(LOCAL_MTU, 262_144);
@@ -631,9 +770,12 @@ mod tests {
name: "test-local-server".to_string(),
};
let server_handle = spawn_local_server(server_cfg, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
let server_handle =
spawn_local_server(server_cfg, 499, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
server_handle.owner.mark_registered();
assert_eq!(server_handle.id, 499);
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
@@ -645,12 +787,21 @@ mod tests {
let client_handle = spawn_local_client(client_cfg, 42, transport_tx.clone())
.await
.unwrap();
client_handle.owner.mark_registered();
let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for accepted handle")
.expect("handle channel closed");
accepted.owner.mark_registered();
assert_ne!(accepted.owner, server_handle.owner);
assert_ne!(accepted.owner, client_handle.owner);
assert_eq!(accepted.parent_id, Some(server_handle.id));
assert_eq!(
accepted.packet_capacity,
InterfacePacketCapacity::new(262144, 262144, true)
);
let payload = Bytes::from_static(b"local ipc test");
client_handle.tx.send(payload.clone()).await.unwrap();
@@ -659,7 +810,7 @@ mod tests {
.expect("timeout")
.expect("channel closed");
match msg {
match crate::traits::test_event_for_handle(msg, &accepted) {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, payload);
assert_eq!(pkt.interface_id, accepted.id);
@@ -675,7 +826,7 @@ mod tests {
.expect("timeout")
.expect("channel closed");
match msg2 {
match crate::traits::test_event_for_handle(msg2, &client_handle) {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, reply);
assert_eq!(pkt.interface_id, 42);
@@ -702,9 +853,11 @@ mod tests {
socket_path: socket_path.clone(),
name: "dereg-server".to_string(),
};
let server_handle = spawn_local_server(server_cfg, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
let server_handle =
spawn_local_server(server_cfg, 599, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
server_handle.owner.mark_registered();
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
@@ -715,11 +868,13 @@ mod tests {
let client_handle = spawn_local_client(client_cfg, 77, transport_tx.clone())
.await
.unwrap();
client_handle.owner.mark_registered();
let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for accepted handle")
.expect("handle channel closed");
accepted.owner.mark_registered();
let server_side_client_id = accepted.id;
// Abort client; server's per-client read_loop sees EOF and exits.
@@ -731,7 +886,9 @@ mod tests {
while tokio::time::Instant::now() < deadline {
match tokio::time::timeout(std::time::Duration::from_millis(500), transport_rx.recv())
.await
{
.map(|message| {
message.map(|event| crate::traits::test_event_for_handle(event, &accepted))
}) {
Ok(Some(TransportMessage::DeregisterInterface { id }))
if id == server_side_client_id =>
{
@@ -752,4 +909,198 @@ mod tests {
server_handle.read_task.abort();
let _ = std::fs::remove_file(&socket_path);
}
#[cfg(unix)]
#[tokio::test]
async fn test_local_client_reconnects_after_server_restart() {
let (transport_tx, mut transport_rx) = mpsc::channel::<TransportMessage>(64);
let (handle_tx, mut handle_rx) = mpsc::channel::<InterfaceHandle>(8);
let id_gen = Arc::new(AtomicU64::new(900));
let socket_path = unique_test_socket_path("reticulum_reconnect_test");
let server_config = || LocalServerConfig {
socket_path: socket_path.clone(),
name: "restartable-local-server".to_string(),
};
let server_handle = spawn_local_server(
server_config(),
699,
id_gen.clone(),
transport_tx.clone(),
handle_tx.clone(),
)
.await
.unwrap();
server_handle.owner.mark_registered();
let client_handle = spawn_local_client(
LocalClientConfig {
socket_path: socket_path.clone(),
name: "persistent-local-client".to_string(),
},
88,
transport_tx.clone(),
)
.await
.unwrap();
client_handle.owner.mark_registered();
let first_accepted =
tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for first accepted client")
.expect("handle channel closed");
first_accepted.owner.mark_registered();
server_handle.read_task.abort();
first_accepted.read_task.abort();
drop(first_accepted.tx);
tokio::time::timeout(std::time::Duration::from_secs(3), async {
while client_handle.online.load(Ordering::SeqCst) {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.expect("client did not observe server shutdown");
let restarted_server = spawn_local_server(
server_config(),
699,
id_gen,
transport_tx.clone(),
handle_tx,
)
.await
.unwrap();
restarted_server.owner.mark_registered();
let second_accepted = tokio::time::timeout(RECONNECT_DEADLINE, handle_rx.recv())
.await
.expect("client did not reconnect to restarted server")
.expect("handle channel closed");
second_accepted.owner.mark_registered();
wait_until_online(&client_handle.online).await;
let payload = Bytes::from_static(b"after shared restart");
second_accepted.tx.send(payload.clone()).await.unwrap();
let inbound = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv())
.await
.expect("timeout waiting for post-restart frame")
.expect("transport channel closed");
match crate::traits::test_event_for_handle(inbound, &client_handle) {
TransportMessage::Inbound(packet) => {
assert_eq!(packet.interface_id, 88);
assert_eq!(packet.raw, payload);
}
other => panic!("unexpected post-restart message: {other:?}"),
}
restarted_server.read_task.abort();
second_accepted.read_task.abort();
drop(second_accepted.tx);
client_handle.read_task.abort();
let _ = std::fs::remove_file(&socket_path);
}
/// Python's `LocalClientInterface` drops outgoing traffic while offline
/// (LocalInterface.py:218), so nothing queued during an outage reaches
/// the restarted shared instance.
#[cfg(unix)]
#[tokio::test]
async fn test_local_client_drops_traffic_queued_while_disconnected() {
let (transport_tx, mut transport_rx) = mpsc::channel::<TransportMessage>(64);
let (handle_tx, mut handle_rx) = mpsc::channel::<InterfaceHandle>(8);
let id_gen = Arc::new(AtomicU64::new(950));
let socket_path = unique_test_socket_path("reticulum_offline_queue_test");
let server_config = || LocalServerConfig {
socket_path: socket_path.clone(),
name: "restartable-local-server".to_string(),
};
let server_handle = spawn_local_server(
server_config(),
698,
id_gen.clone(),
transport_tx.clone(),
handle_tx.clone(),
)
.await
.unwrap();
server_handle.owner.mark_registered();
let client_handle = spawn_local_client(
LocalClientConfig {
socket_path: socket_path.clone(),
name: "offline-local-client".to_string(),
},
89,
transport_tx.clone(),
)
.await
.unwrap();
client_handle.owner.mark_registered();
let first_accepted =
tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for first accepted client")
.expect("handle channel closed");
server_handle.read_task.abort();
first_accepted.read_task.abort();
drop(first_accepted.tx);
tokio::time::timeout(std::time::Duration::from_secs(3), async {
while client_handle.online.load(Ordering::SeqCst) {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.expect("client did not observe server shutdown");
client_handle
.tx
.send(Bytes::from_static(b"queued while offline"))
.await
.unwrap();
let restarted_server = spawn_local_server(
server_config(),
698,
id_gen,
transport_tx.clone(),
handle_tx,
)
.await
.unwrap();
restarted_server.owner.mark_registered();
let second_accepted = tokio::time::timeout(RECONNECT_DEADLINE, handle_rx.recv())
.await
.expect("client did not reconnect to restarted server")
.expect("handle channel closed");
second_accepted.owner.mark_registered();
// Online is published only after the offline queue is dropped.
wait_until_online(&client_handle.online).await;
let after = Bytes::from_static(b"after reconnect");
client_handle.tx.send(after.clone()).await.unwrap();
let first_frame = tokio::time::timeout(std::time::Duration::from_secs(3), async {
loop {
match transport_rx.recv().await.expect("transport channel closed") {
TransportMessage::InterfaceEvent {
interface_id,
message,
..
} if interface_id == second_accepted.id => {
if let TransportMessage::Inbound(packet) = *message {
return packet.raw;
}
}
_ => {}
}
}
})
.await
.expect("the reconnected client's traffic reaches the shared instance");
assert_eq!(
first_frame, after,
"traffic queued while disconnected is dropped"
);
restarted_server.read_task.abort();
second_accepted.read_task.abort();
client_handle.read_task.abort();
let _ = std::fs::remove_file(&socket_path);
}
}
+12 -2
View File
@@ -1,5 +1,9 @@
//! HDLC-framed data over a subprocess's stdin/stdout; respawns on exit.
//! HDLC-framed data over a subprocess's stdin/stdout. The task retries failed
//! spawns and respawns after stdout EOF or a read error. The command is split
//! on whitespace and executed directly: shell quoting, expansion, and
//! pipelines are not interpreted.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -20,7 +24,8 @@ pub const DEFAULT_RESPAWN_DELAY: f64 = 5.0;
pub struct PipeInterfaceConfig {
pub name: String,
pub command: String,
/// Seconds before respawning after subprocess exit.
/// Seconds before respawning. Must be finite, non-negative, and representable
/// as a `Duration`; this field is not validated before the task starts.
pub respawn_delay: f64,
pub mode: InterfaceMode,
}
@@ -41,6 +46,8 @@ pub async fn spawn_pipe_interface(
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let online = Arc::new(AtomicBool::new(true));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
@@ -189,6 +196,8 @@ pub async fn spawn_pipe_interface(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 1064, false),
parent_id: None,
name,
mode,
@@ -203,6 +212,7 @@ pub async fn spawn_pipe_interface(
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: None,
tx,
read_task,
})
File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -1,4 +1,6 @@
//! Extended-KISS admin codec shared by RNode runtime and `rnodeconf`.
//! Extended-KISS administrative frame codecs and command builders used by
//! `rnodeconf`. These helpers construct or decode bytes; they perform no
//! transport I/O or device authorization.
use std::net::Ipv4Addr;
@@ -0,0 +1,976 @@
//! Read-only RNode capability parsing without retaining device identity bytes.
//!
//! This module checks the EEPROM information lock and MD5 identity-prefix
//! checksum, then returns product/model codes and limits from a static code
//! table. It ignores device signatures: checksum validation is not device
//! authentication. The value retains no source image, identity, signature,
//! configuration, or raw EEPROM fields. Code-table limits are not a hardware
//! measurement or permission to transmit.
use md5::{Digest, Md5};
use crate::rnode::{RNodeConfigValidationError, RNodeRadioSettings};
const PRODUCT_ADDRESS: usize = 0x00;
const MODEL_ADDRESS: usize = 0x01;
const IDENTITY_CHECKSUM_INPUT_END: usize = 0x0B;
const CHECKSUM_ADDRESS: usize = 0x0B;
const CHECKSUM_END: usize = 0x1B;
const INFO_LOCK_ADDRESS: usize = 0x9B;
const REQUIRED_EEPROM_LEN: usize = INFO_LOCK_ADDRESS + 1;
const INFO_LOCK_BYTE: u8 = 0x73;
/// A validated, privacy-bounded RNode capability description.
///
/// The value owns no EEPROM bytes and contains no stable device identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct RNodeCapabilities {
product_code: u8,
model_code: u8,
radio: RNodeRadioCapabilities,
}
impl RNodeCapabilities {
/// The RNode product code stored in the validated identity prefix.
pub const fn product_code(self) -> u8 {
self.product_code
}
/// A reviewed display name for the product code, when one is known.
///
/// This is a static code-table lookup; no label is read from or retained
/// from the EEPROM image.
pub const fn product_name(self) -> Option<&'static str> {
rnode_product_name(self.product_code)
}
/// The exact, unnormalised RNode model code stored in the identity prefix.
pub const fn model_code(self) -> u8 {
self.model_code
}
/// Reviewed radio limits for the model, or [`RNodeRadioCapabilities::Unknown`].
pub const fn radio(self) -> RNodeRadioCapabilities {
self.radio
}
}
/// Whether a validated model has a reviewed radio capability profile.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RNodeRadioCapabilities {
/// The model maps to a reviewed, internally consistent numeric profile.
Known(RNodeKnownRadioCapabilities),
/// The model is unknown, ambiguous, or deliberately quarantined.
Unknown,
}
/// Reviewed numeric limits for a known RNode radio model.
///
/// For a dual-radio product, these limits describe the reviewed generic/main
/// RNode radio profile. They do not claim to span every band supported by each
/// physically present secondary radio.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct RNodeKnownRadioCapabilities {
family: RNodeRadioFamily,
min_frequency_hz: u32,
max_frequency_hz: u32,
max_tx_power_dbm: u8,
}
impl RNodeKnownRadioCapabilities {
/// The radio family associated with the model.
pub const fn family(self) -> RNodeRadioFamily {
self.family
}
/// The inclusive lower frequency bound in hertz.
pub const fn min_frequency_hz(self) -> u32 {
self.min_frequency_hz
}
/// The inclusive upper frequency bound in hertz.
pub const fn max_frequency_hz(self) -> u32 {
self.max_frequency_hz
}
/// The inclusive maximum transmit power in dBm.
pub const fn max_tx_power_dbm(self) -> u8 {
self.max_tx_power_dbm
}
/// Whether `frequency_hz` lies within the inclusive reviewed bounds.
pub const fn supports_frequency(self, frequency_hz: u32) -> bool {
frequency_hz >= self.min_frequency_hz && frequency_hz <= self.max_frequency_hz
}
/// Whether `tx_power_dbm` is at or below the inclusive reviewed maximum.
pub const fn supports_tx_power(self, tx_power_dbm: u8) -> bool {
tx_power_dbm <= self.max_tx_power_dbm
}
}
/// Radio families represented by reviewed RNode model profiles.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RNodeRadioFamily {
Sx1262,
Sx1268,
Sx1276,
Sx1278,
Sx1280,
/// A dual-radio product.
///
/// Its numeric capability bounds describe the reviewed generic/main radio
/// profile, not every band of the physically present secondary radio.
Sx1262AndSx1280,
}
/// Why a capability image could not be accepted.
///
/// Errors intentionally contain no EEPROM contents, hashes, or identity
/// values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum RNodeCapabilityParseError {
#[error("RNode EEPROM image is too short (need {required} bytes, got {actual})")]
TooShort { required: usize, actual: usize },
#[error("RNode identity information is not locked")]
InfoNotLocked,
#[error("RNode identity checksum is invalid")]
ChecksumMismatch,
}
/// Model-specific classification for a validated RNode capability image.
///
/// `Verified` means the exact model has a reviewed capability profile.
/// `Unverified` means the exact stored model is unknown or quarantined, so no
/// model profile was inferred. `Unprovisioned` means the device presented no
/// locked EEPROM identity at all, so no product or model claim exists and only
/// generic validation was applied. A `Verified` classification alone does not
/// admit radio settings; use [`admit_rnode_radio_settings`] for that.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RNodeRadioAdmission {
Verified { product_code: u8, model_code: u8 },
Unverified { product_code: u8, model_code: u8 },
Unprovisioned,
}
impl RNodeRadioAdmission {
/// Validated EEPROM product code, when a locked identity supplied one.
pub const fn product_code(self) -> Option<u8> {
match self {
Self::Verified { product_code, .. } | Self::Unverified { product_code, .. } => {
Some(product_code)
}
Self::Unprovisioned => None,
}
}
/// Exact, unnormalised EEPROM model code, when a locked identity supplied one.
pub const fn model_code(self) -> Option<u8> {
match self {
Self::Verified { model_code, .. } | Self::Unverified { model_code, .. } => {
Some(model_code)
}
Self::Unprovisioned => None,
}
}
/// Whether a reviewed model-specific profile was available.
pub const fn is_verified(self) -> bool {
matches!(self, Self::Verified { .. })
}
}
/// Typed failure from model-specific RNode radio admission.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum RNodeRadioAdmissionError {
#[error("generic RNode radio settings are invalid: {0}")]
GenericValidation(#[source] RNodeConfigValidationError),
#[error("frequency {requested_hz} Hz is outside verified model range {min_hz}..={max_hz} Hz")]
FrequencyOutOfRange {
requested_hz: u32,
min_hz: u32,
max_hz: u32,
},
#[error("TX power {requested_dbm} dBm exceeds verified model maximum {max_dbm} dBm")]
TxPowerExceedsMaximum { requested_dbm: u8, max_dbm: u8 },
}
/// Bounded classification of a full-length RNode EEPROM image.
///
/// `Provisioned` carries capabilities from a locked, checksummed identity
/// prefix. `Unprovisioned` means the info lock at `0x9b` is absent, so product,
/// model, and checksum bytes are not consulted. Neither state authenticates a
/// device signature.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RNodeEepromImage {
Provisioned(RNodeCapabilities),
Unprovisioned,
}
/// Classify an EEPROM image, admitting unprovisioned devices as a typed state.
///
/// The image must span the information lock at `0x9b`. An unlocked image is
/// [`RNodeEepromImage::Unprovisioned`] without reading product, model, or
/// checksum bytes. A locked image must match the MD5 checksum over stored
/// bytes `0x00..0x0b`; model aliases are not normalised first. Signature bytes
/// are ignored, so this check does not authenticate the device.
pub fn classify_rnode_eeprom_image(
eeprom: &[u8],
) -> Result<RNodeEepromImage, RNodeCapabilityParseError> {
if eeprom.len() < REQUIRED_EEPROM_LEN {
return Err(RNodeCapabilityParseError::TooShort {
required: REQUIRED_EEPROM_LEN,
actual: eeprom.len(),
});
}
if eeprom[INFO_LOCK_ADDRESS] != INFO_LOCK_BYTE {
return Ok(RNodeEepromImage::Unprovisioned);
}
let calculated: [u8; 16] = Md5::digest(&eeprom[..IDENTITY_CHECKSUM_INPUT_END]).into();
if calculated != eeprom[CHECKSUM_ADDRESS..CHECKSUM_END] {
return Err(RNodeCapabilityParseError::ChecksumMismatch);
}
let product_code = eeprom[PRODUCT_ADDRESS];
let model_code = eeprom[MODEL_ADDRESS];
let radio = rnode_model_capabilities(model_code);
Ok(RNodeEepromImage::Provisioned(RNodeCapabilities {
product_code,
model_code,
radio,
}))
}
/// Validate an EEPROM image and retain only non-identifying capability data.
///
/// Strict form of [`classify_rnode_eeprom_image`] for callers that require a
/// provisioned identity (for example rnodeconf mutation preflights): an
/// unlocked image is an [`RNodeCapabilityParseError::InfoNotLocked`] error
/// here rather than a typed classification.
pub fn parse_rnode_capabilities(
eeprom: &[u8],
) -> Result<RNodeCapabilities, RNodeCapabilityParseError> {
match classify_rnode_eeprom_image(eeprom)? {
RNodeEepromImage::Provisioned(capabilities) => Ok(capabilities),
RNodeEepromImage::Unprovisioned => Err(RNodeCapabilityParseError::InfoNotLocked),
}
}
/// Classify a validated model without admitting radio settings.
///
/// `capabilities` can only be obtained from a successfully validated EEPROM
/// image. Unknown, aliased, ambiguous, and quarantined model codes return
/// [`RNodeRadioAdmission::Unverified`] without normalisation or an inferred
/// profile.
pub fn classify_rnode_radio_capabilities(capabilities: RNodeCapabilities) -> RNodeRadioAdmission {
let product_code = capabilities.product_code();
let model_code = capabilities.model_code();
match capabilities.radio() {
RNodeRadioCapabilities::Known(_) => RNodeRadioAdmission::Verified {
product_code,
model_code,
},
RNodeRadioCapabilities::Unknown => RNodeRadioAdmission::Unverified {
product_code,
model_code,
},
}
}
/// Apply the sole lower-layer RF admission policy to validated capabilities.
///
/// Generic RNode validation runs first. Known exact model codes then enforce
/// their inclusive frequency range and maximum TX power. Unknown, aliased,
/// ambiguous, and quarantined model codes continue as an explicit
/// [`RNodeRadioAdmission::Unverified`] result without normalisation or an
/// inferred profile.
pub fn admit_rnode_radio_settings(
capabilities: RNodeCapabilities,
settings: RNodeRadioSettings,
) -> Result<RNodeRadioAdmission, RNodeRadioAdmissionError> {
settings
.validate()
.map_err(RNodeRadioAdmissionError::GenericValidation)?;
if let RNodeRadioCapabilities::Known(radio) = capabilities.radio() {
if !radio.supports_frequency(settings.frequency) {
return Err(RNodeRadioAdmissionError::FrequencyOutOfRange {
requested_hz: settings.frequency,
min_hz: radio.min_frequency_hz(),
max_hz: radio.max_frequency_hz(),
});
}
if !radio.supports_tx_power(settings.tx_power) {
return Err(RNodeRadioAdmissionError::TxPowerExceedsMaximum {
requested_dbm: settings.tx_power,
max_dbm: radio.max_tx_power_dbm(),
});
}
}
Ok(classify_rnode_radio_capabilities(capabilities))
}
/// Admit radio settings for a device that presented no locked EEPROM identity.
///
/// Only generic RNode validation applies. No model-specific profile is
/// inferred, as with unknown and quarantined model codes.
pub fn admit_unprovisioned_rnode_radio_settings(
settings: RNodeRadioSettings,
) -> Result<RNodeRadioAdmission, RNodeRadioAdmissionError> {
settings
.validate()
.map_err(RNodeRadioAdmissionError::GenericValidation)?;
Ok(RNodeRadioAdmission::Unprovisioned)
}
/// Return the reviewed display name for an RNode product code.
///
/// Unknown product codes return `None`. Names are static code-table values and
/// are never read from device-controlled EEPROM data.
pub const fn rnode_product_name(product_code: u8) -> Option<&'static str> {
Some(match product_code {
0x03 => "RNode",
0x10 => "RAK4631",
0x15 => "LilyGO T-Echo",
0x20 => "openCom XL",
0xB0 => "LilyGO LoRa32 v2.0",
0xB1 => "LilyGO LoRa32 v2.1",
0xB2 => "LilyGO LoRa32 v1.0",
0xC0 => "Heltec LoRa32 v2",
0xC1 => "Heltec LoRa32 v3",
0xC2 => "Heltec Mesh Node T114",
0xC3 => "Heltec LoRa32 v4",
0xD0 => "LilyGO T-Deck",
0xE0 => "LilyGO T-Beam",
0xEA => "LilyGO T-Beam Supreme",
0xEB => "Seeed XIAO ESP32S3 Wio-SX1262",
0xF0 => "Hombrew RNode",
_ => return None,
})
}
/// Return the reviewed radio capabilities for an exact RNode model code.
///
/// Unknown, ambiguous, and quarantined model codes return
/// [`RNodeRadioCapabilities::Unknown`]. In particular, EEPROM aliases are not
/// normalised by this lookup. Model codes `0xA6`, `0xAA`, and `0xC8` remain
/// quarantined because the trusted Rust sources do not establish a single,
/// internally consistent numeric capability profile for them.
pub fn rnode_model_capabilities(model_code: u8) -> RNodeRadioCapabilities {
KNOWN_RADIOS
.iter()
.find_map(|(candidate, profile)| (*candidate == model_code).then_some(*profile))
.map(RNodeRadioCapabilities::Known)
.unwrap_or(RNodeRadioCapabilities::Unknown)
}
const fn known(
family: RNodeRadioFamily,
min_frequency_hz: u32,
max_frequency_hz: u32,
max_tx_power_dbm: u8,
) -> RNodeKnownRadioCapabilities {
RNodeKnownRadioCapabilities {
family,
min_frequency_hz,
max_frequency_hz,
max_tx_power_dbm,
}
}
// Reviewed numeric profiles owned by this lower-core module. Firmware
// filenames and human labels intentionally do not cross this boundary.
// Models with aliases, contradictory ranges, ambiguous evidence, or explicitly
// unknown limits are absent and therefore resolve to Unknown.
const KNOWN_RADIOS: &[(u8, RNodeKnownRadioCapabilities)] = &[
(
0xA4,
known(RNodeRadioFamily::Sx1278, 410_000_000, 525_000_000, 14),
),
(
0xA9,
known(RNodeRadioFamily::Sx1276, 820_000_000, 1_020_000_000, 17),
),
(
0xA1,
known(RNodeRadioFamily::Sx1268, 410_000_000, 525_000_000, 22),
),
(
0xA5,
known(RNodeRadioFamily::Sx1278, 410_000_000, 525_000_000, 17),
),
(
0xAC,
known(RNodeRadioFamily::Sx1280, 2_400_000_000, 2_500_000_000, 20),
),
(
0xA2,
known(RNodeRadioFamily::Sx1278, 410_000_000, 525_000_000, 17),
),
(
0xA7,
known(RNodeRadioFamily::Sx1276, 820_000_000, 1_020_000_000, 17),
),
(
0xA3,
known(RNodeRadioFamily::Sx1278, 410_000_000, 525_000_000, 17),
),
(
0xA8,
known(RNodeRadioFamily::Sx1276, 820_000_000, 1_020_000_000, 17),
),
(
0xB3,
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
),
(
0xB8,
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
),
(
0xB4,
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
),
(
0xB9,
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
),
(
0xBA,
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
),
(
0xBB,
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
),
(
0xC4,
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
),
(
0xC9,
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
),
(
0xC5,
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
),
(
0xCA,
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
),
(
0xC6,
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
),
(
0xC7,
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
),
(
0xE4,
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
),
(
0xE9,
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
),
(
0xD4,
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
),
(
0xD9,
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
),
(
0xDB,
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
),
(
0xDC,
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
),
(
0xE3,
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
),
(
0xE8,
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
),
(
0x11,
known(RNodeRadioFamily::Sx1262, 430_000_000, 510_000_000, 22),
),
(
0x12,
known(RNodeRadioFamily::Sx1262, 779_000_000, 928_000_000, 22),
),
(
0x13,
known(
RNodeRadioFamily::Sx1262AndSx1280,
430_000_000,
510_000_000,
22,
),
),
(
0x14,
known(
RNodeRadioFamily::Sx1262AndSx1280,
779_000_000,
928_000_000,
22,
),
),
(
0x17,
known(RNodeRadioFamily::Sx1262, 779_000_000, 928_000_000, 22),
),
(
0x21,
known(
RNodeRadioFamily::Sx1262AndSx1280,
820_000_000,
960_000_000,
22,
),
),
(
0xDE,
known(RNodeRadioFamily::Sx1262, 420_000_000, 520_000_000, 22),
),
(
0xDD,
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
),
];
#[cfg(test)]
mod tests {
use super::*;
const PRODUCT: u8 = 0x03;
const QUARANTINED_MODELS: &[u8] = &[0x04, 0x09, 0x16, 0xA6, 0xAA, 0xC8, 0xFE, 0xFF];
fn image(model: u8) -> [u8; REQUIRED_EEPROM_LEN] {
let mut bytes = [0xA5; REQUIRED_EEPROM_LEN];
bytes[PRODUCT_ADDRESS] = PRODUCT;
bytes[MODEL_ADDRESS] = model;
bytes[0x02] = 0x07;
bytes[0x03..0x07].copy_from_slice(&0x1122_3344_u32.to_be_bytes());
bytes[0x07..0x0B].copy_from_slice(&0x5566_7788_u32.to_be_bytes());
let checksum: [u8; 16] = Md5::digest(&bytes[..IDENTITY_CHECKSUM_INPUT_END]).into();
bytes[CHECKSUM_ADDRESS..CHECKSUM_END].copy_from_slice(&checksum);
bytes[INFO_LOCK_ADDRESS] = INFO_LOCK_BYTE;
bytes
}
fn settings(frequency: u32, tx_power: u8) -> RNodeRadioSettings {
RNodeRadioSettings::new(frequency, 125_000, 7, 5, tx_power)
}
#[test]
fn requires_every_byte_through_info_lock() {
let short = &image(0xA4)[..REQUIRED_EEPROM_LEN - 1];
assert_eq!(
parse_rnode_capabilities(short),
Err(RNodeCapabilityParseError::TooShort {
required: 156,
actual: 155,
})
);
let exact = image(0xA4);
assert!(parse_rnode_capabilities(&exact).is_ok());
}
#[test]
fn rejects_unlocked_identity_information_before_checksum_validation() {
let mut bytes = image(0xA4);
bytes[INFO_LOCK_ADDRESS] = 0x00;
bytes[CHECKSUM_ADDRESS] ^= 0xFF;
assert_eq!(
parse_rnode_capabilities(&bytes),
Err(RNodeCapabilityParseError::InfoNotLocked)
);
}
#[test]
fn unlocked_images_classify_unprovisioned_without_reading_identity() {
// Both fresh-erase (0xFF) and zeroed lock bytes count as unlocked, and
// neither the checksum nor the identity bytes may be consulted.
for lock in [0x00, 0xFF] {
let mut bytes = image(0x11);
bytes[INFO_LOCK_ADDRESS] = lock;
for byte in &mut bytes[CHECKSUM_ADDRESS..CHECKSUM_END] {
*byte = 0xA5;
}
assert_eq!(
classify_rnode_eeprom_image(&bytes),
Ok(RNodeEepromImage::Unprovisioned),
"lock byte {lock:#04x} must classify unprovisioned"
);
}
}
#[test]
fn classification_preserves_strict_short_and_checksum_failures() {
let short = &image(0xA4)[..REQUIRED_EEPROM_LEN - 1];
assert_eq!(
classify_rnode_eeprom_image(short),
Err(RNodeCapabilityParseError::TooShort {
required: 156,
actual: 155,
})
);
let mut corrupt = image(0xA4);
corrupt[CHECKSUM_ADDRESS] ^= 0x01;
assert_eq!(
classify_rnode_eeprom_image(&corrupt),
Err(RNodeCapabilityParseError::ChecksumMismatch)
);
assert_eq!(
classify_rnode_eeprom_image(&image(0x11)),
Ok(RNodeEepromImage::Provisioned(
parse_rnode_capabilities(&image(0x11)).expect("valid image")
))
);
}
#[test]
fn unprovisioned_admission_applies_generic_validation_only() {
assert_eq!(
admit_unprovisioned_rnode_radio_settings(settings(868_000_000, 37)),
Ok(RNodeRadioAdmission::Unprovisioned)
);
assert!(matches!(
admit_unprovisioned_rnode_radio_settings(settings(1, 14)),
Err(RNodeRadioAdmissionError::GenericValidation(_))
));
}
#[test]
fn admission_codes_are_present_only_for_locked_identities() {
let verified = RNodeRadioAdmission::Verified {
product_code: PRODUCT,
model_code: 0x11,
};
assert_eq!(verified.product_code(), Some(PRODUCT));
assert_eq!(verified.model_code(), Some(0x11));
assert!(verified.is_verified());
assert_eq!(RNodeRadioAdmission::Unprovisioned.product_code(), None);
assert_eq!(RNodeRadioAdmission::Unprovisioned.model_code(), None);
assert!(!RNodeRadioAdmission::Unprovisioned.is_verified());
}
#[test]
fn checksum_covers_exact_identity_prefix_without_model_normalisation() {
let mut bytes = image(0x04);
let parsed = parse_rnode_capabilities(&bytes).expect("raw model checksum should validate");
assert_eq!(parsed.model_code(), 0x04);
assert_eq!(parsed.radio(), RNodeRadioCapabilities::Unknown);
// Replacing the raw alias with its nominal model invalidates the exact
// stored checksum; the parser must not normalise it first.
bytes[MODEL_ADDRESS] = 0xB4;
assert_eq!(
parse_rnode_capabilities(&bytes),
Err(RNodeCapabilityParseError::ChecksumMismatch)
);
}
#[test]
fn rejects_any_identity_prefix_checksum_mismatch() {
for address in 0..IDENTITY_CHECKSUM_INPUT_END {
let mut bytes = image(0xA4);
bytes[address] ^= 0x01;
assert_eq!(
parse_rnode_capabilities(&bytes),
Err(RNodeCapabilityParseError::ChecksumMismatch),
"identity byte {address:#04x} was not covered"
);
}
}
#[test]
fn returns_only_reviewed_codes_and_known_numeric_bounds() {
let parsed = parse_rnode_capabilities(&image(0xAC)).expect("valid known model");
assert_eq!(parsed.product_code(), PRODUCT);
assert_eq!(parsed.product_name(), Some("RNode"));
assert_eq!(parsed.model_code(), 0xAC);
assert_eq!(
parsed.radio(),
RNodeRadioCapabilities::Known(known(
RNodeRadioFamily::Sx1280,
2_400_000_000,
2_500_000_000,
20,
))
);
let low_band = parse_rnode_capabilities(&image(0x11)).expect("valid known model");
assert_eq!(
low_band.radio(),
RNodeRadioCapabilities::Known(known(
RNodeRadioFamily::Sx1262,
430_000_000,
510_000_000,
22,
))
);
}
#[test]
fn capability_support_helpers_include_both_boundaries() {
let parsed = parse_rnode_capabilities(&image(0x11)).expect("valid known model");
let RNodeRadioCapabilities::Known(radio) = parsed.radio() else {
panic!("model 0x11 must have a reviewed profile");
};
assert!(radio.supports_frequency(430_000_000));
assert!(radio.supports_frequency(510_000_000));
assert!(!radio.supports_frequency(429_999_999));
assert!(!radio.supports_frequency(510_000_001));
assert!(radio.supports_tx_power(0));
assert!(radio.supports_tx_power(22));
assert!(!radio.supports_tx_power(23));
}
#[test]
fn known_model_admission_includes_frequency_and_power_boundaries() {
let capabilities = parse_rnode_capabilities(&image(0x11)).expect("valid known model");
assert_eq!(
admit_rnode_radio_settings(capabilities, settings(430_000_000, 0)),
Ok(RNodeRadioAdmission::Verified {
product_code: PRODUCT,
model_code: 0x11,
})
);
assert_eq!(
admit_rnode_radio_settings(capabilities, settings(510_000_000, 22)),
Ok(RNodeRadioAdmission::Verified {
product_code: PRODUCT,
model_code: 0x11,
})
);
assert_eq!(
classify_rnode_radio_capabilities(capabilities),
RNodeRadioAdmission::Verified {
product_code: PRODUCT,
model_code: 0x11,
}
);
}
#[test]
fn known_model_admission_returns_typed_frequency_and_power_mismatches() {
let capabilities = parse_rnode_capabilities(&image(0x11)).expect("valid known model");
for (frequency, expected) in [
(
429_999_999,
RNodeRadioAdmissionError::FrequencyOutOfRange {
requested_hz: 429_999_999,
min_hz: 430_000_000,
max_hz: 510_000_000,
},
),
(
510_000_001,
RNodeRadioAdmissionError::FrequencyOutOfRange {
requested_hz: 510_000_001,
min_hz: 430_000_000,
max_hz: 510_000_000,
},
),
] {
assert_eq!(
admit_rnode_radio_settings(capabilities, settings(frequency, 22)),
Err(expected)
);
}
let error = admit_rnode_radio_settings(capabilities, settings(430_000_000, 23));
assert_eq!(
error,
Err(RNodeRadioAdmissionError::TxPowerExceedsMaximum {
requested_dbm: 23,
max_dbm: 22,
})
);
}
#[test]
fn unknown_and_quarantined_admission_is_explicitly_unverified() {
for model in std::iter::once(0x00).chain(QUARANTINED_MODELS.iter().copied()) {
let capabilities =
parse_rnode_capabilities(&image(model)).expect("valid identity image");
assert_eq!(
classify_rnode_radio_capabilities(capabilities),
RNodeRadioAdmission::Unverified {
product_code: PRODUCT,
model_code: model,
},
"model {model:#04x} classification must remain unverified"
);
assert_eq!(
admit_rnode_radio_settings(capabilities, settings(868_000_000, 37)),
Ok(RNodeRadioAdmission::Unverified {
product_code: PRODUCT,
model_code: model,
}),
"model {model:#04x} must remain unverified"
);
}
}
#[test]
fn generic_validation_precedes_known_and_unverified_model_policy() {
for model in [0x11, 0xA6] {
let capabilities = parse_rnode_capabilities(&image(model)).expect("valid identity");
let error = admit_rnode_radio_settings(capabilities, settings(1, 23))
.expect_err("model policy must not bypass generic validation");
assert!(
matches!(error, RNodeRadioAdmissionError::GenericValidation(_)),
"model {model:#04x} did not fail generic validation first: {error:?}"
);
}
}
#[test]
fn product_names_are_closed_static_lookups() {
const PRODUCTS: &[(u8, &str)] = &[
(0x03, "RNode"),
(0x10, "RAK4631"),
(0x15, "LilyGO T-Echo"),
(0x20, "openCom XL"),
(0xB0, "LilyGO LoRa32 v2.0"),
(0xB1, "LilyGO LoRa32 v2.1"),
(0xB2, "LilyGO LoRa32 v1.0"),
(0xC0, "Heltec LoRa32 v2"),
(0xC1, "Heltec LoRa32 v3"),
(0xC2, "Heltec Mesh Node T114"),
(0xC3, "Heltec LoRa32 v4"),
(0xD0, "LilyGO T-Deck"),
(0xE0, "LilyGO T-Beam"),
(0xEA, "LilyGO T-Beam Supreme"),
(0xEB, "Seeed XIAO ESP32S3 Wio-SX1262"),
(0xF0, "Hombrew RNode"),
];
for (index, (code, name)) in PRODUCTS.iter().enumerate() {
assert_eq!(rnode_product_name(*code), Some(*name));
assert!(
!PRODUCTS[..index].iter().any(|(earlier, _)| earlier == code),
"duplicate product code {code:#04x}"
);
}
assert_eq!(rnode_product_name(0x00), None);
assert_eq!(rnode_product_name(0xFF), None);
}
#[test]
fn unknown_and_quarantined_models_never_invent_limits() {
for model in std::iter::once(0x00).chain(QUARANTINED_MODELS.iter().copied()) {
let parsed = parse_rnode_capabilities(&image(model)).expect("valid identity image");
assert_eq!(parsed.model_code(), model);
assert_eq!(
parsed.radio(),
RNodeRadioCapabilities::Unknown,
"model {model:#04x} must remain unknown"
);
}
}
#[test]
fn direct_model_lookup_is_closed_and_does_not_normalise_quarantine() {
assert_eq!(
rnode_model_capabilities(0xA4),
RNodeRadioCapabilities::Known(known(
RNodeRadioFamily::Sx1278,
410_000_000,
525_000_000,
14,
))
);
for model in std::iter::once(0x00).chain(QUARANTINED_MODELS.iter().copied()) {
assert_eq!(
rnode_model_capabilities(model),
RNodeRadioCapabilities::Unknown,
"model {model:#04x} must remain unknown"
);
}
}
#[test]
fn signature_and_other_ignored_bytes_do_not_affect_result() {
let baseline_image = image(0xA4);
let baseline = parse_rnode_capabilities(&baseline_image).expect("valid image");
let mut mutated = baseline_image;
for (index, byte) in mutated[CHECKSUM_END..INFO_LOCK_ADDRESS]
.iter_mut()
.enumerate()
{
*byte = index as u8;
}
assert_eq!(
parse_rnode_capabilities(&mutated),
Ok(baseline),
"signature and non-capability bytes must be ignored"
);
}
#[test]
fn known_model_table_is_unique_valid_and_excludes_quarantine() {
assert_eq!(KNOWN_RADIOS.len(), 37);
for (index, (model, profile)) in KNOWN_RADIOS.iter().enumerate() {
assert!(
!QUARANTINED_MODELS.contains(model),
"quarantined model {model:#04x} entered the known table"
);
assert!(
profile.min_frequency_hz() < profile.max_frequency_hz(),
"model {model:#04x} has inverted frequency limits"
);
assert!(
profile.max_tx_power_dbm() > 0,
"model {model:#04x} has a non-positive maximum TX power"
);
assert!(
!KNOWN_RADIOS[..index]
.iter()
.any(|(earlier, _)| earlier == model),
"duplicate model {model:#04x}"
);
assert_eq!(
rnode_model_capabilities(*model),
RNodeRadioCapabilities::Known(*profile),
"model {model:#04x} did not round-trip through lookup"
);
}
}
}
@@ -0,0 +1,497 @@
//! Bounded, transport-independent RNode capability preflight state.
//!
//! Transport owners retain their stream, writer, clock, and cancellation
//! policy. This module owns only strict framing, bounded admission state, and
//! privacy-safe errors so serial/TCP, BLE, and USB can share one policy without
//! sharing transport lifecycle machinery.
use crate::kiss;
use crate::rnode::{CMD_ERROR, CMD_ROM_READ, RNodeCapabilityAdmissionError, RNodeRadioSettings};
use crate::rnode_capabilities::{
RNodeEepromImage, RNodeRadioAdmission, admit_rnode_radio_settings,
admit_unprovisioned_rnode_radio_settings, classify_rnode_eeprom_image,
};
use crate::rnode_protocol::{
RNodeFrameRejection, RNodeProtocolEffect, RNodeProtocolState, RNodeProtocolTarget,
};
#[cfg(all(not(test), any(feature = "serial", feature = "rnode-tcp")))]
pub(crate) const RNODE_CAPABILITY_PREFLIGHT_DEADLINE: std::time::Duration =
std::time::Duration::from_secs(5);
#[cfg(all(test, any(feature = "serial", feature = "rnode-tcp")))]
pub(crate) const RNODE_CAPABILITY_PREFLIGHT_DEADLINE: std::time::Duration =
std::time::Duration::from_secs(1);
pub(crate) const RNODE_CAPABILITY_READ_BUFFER_BYTES: usize = 1024;
const RNODE_CAPABILITY_MAX_READS: usize = 128;
const RNODE_CAPABILITY_MAX_INPUT_BYTES: usize = 4 * 1024;
const RNODE_CAPABILITY_MAX_FRAMES: usize = 128;
pub(crate) fn build_rnode_capability_request() -> Vec<u8> {
kiss::frame_with_command(CMD_ROM_READ, &[0])
}
pub(crate) struct RNodeCapabilityPreflight {
deframer: kiss::RawKissDeframer,
protocol_state: RNodeProtocolState,
settings: RNodeRadioSettings,
admission: Option<RNodeRadioAdmission>,
read_count: usize,
input_bytes: usize,
frame_count: usize,
}
impl RNodeCapabilityPreflight {
pub(crate) fn new(settings: RNodeRadioSettings) -> Self {
Self {
deframer: kiss::RawKissDeframer::new(),
protocol_state: RNodeProtocolState::new(RNodeProtocolTarget::new(
settings.frequency,
settings.bandwidth,
settings.spreading_factor,
settings.coding_rate,
settings.tx_power,
)),
settings,
admission: None,
read_count: 0,
input_bytes: 0,
frame_count: 0,
}
}
/// Consume one bounded transport read.
///
/// `CMD_DATA` and EEPROM payloads never leave this state machine. Unknown
/// non-data controls are ignored after strict deframing; supported generic
/// controls are reduced into the generation-private protocol state.
pub(crate) fn observe_read(
&mut self,
bytes: &[u8],
) -> Result<Option<RNodeRadioAdmission>, RNodeCapabilityAdmissionError> {
self.read_count = self.read_count.saturating_add(1);
if self.read_count > RNODE_CAPABILITY_MAX_READS {
return Err(RNodeCapabilityAdmissionError::ReadLimitExceeded {
limit: RNODE_CAPABILITY_MAX_READS,
});
}
if bytes.len() > RNODE_CAPABILITY_READ_BUFFER_BYTES {
return Err(RNodeCapabilityAdmissionError::InputLimitExceeded {
limit: RNODE_CAPABILITY_READ_BUFFER_BYTES,
});
}
self.input_bytes = self.input_bytes.saturating_add(bytes.len());
if self.input_bytes > RNODE_CAPABILITY_MAX_INPUT_BYTES {
return Err(RNodeCapabilityAdmissionError::InputLimitExceeded {
limit: RNODE_CAPABILITY_MAX_INPUT_BYTES,
});
}
for (command, payload) in self.deframer.feed(bytes) {
self.frame_count = self.frame_count.saturating_add(1);
if self.frame_count > RNODE_CAPABILITY_MAX_FRAMES {
return Err(RNodeCapabilityAdmissionError::FrameLimitExceeded {
limit: RNODE_CAPABILITY_MAX_FRAMES,
});
}
if command == kiss::CMD_DATA {
continue;
}
if command == CMD_ROM_READ {
if self.admission.is_some() {
return Err(RNodeCapabilityAdmissionError::DuplicateEepromResponse);
}
let admission = match classify_rnode_eeprom_image(&payload)
.map_err(RNodeCapabilityAdmissionError::CapabilityImage)?
{
RNodeEepromImage::Provisioned(capabilities) => {
admit_rnode_radio_settings(capabilities, self.settings)
.map_err(RNodeCapabilityAdmissionError::RadioSettings)?
}
RNodeEepromImage::Unprovisioned => {
admit_unprovisioned_rnode_radio_settings(self.settings)
.map_err(RNodeCapabilityAdmissionError::RadioSettings)?
}
};
self.admission = Some(admission);
continue;
}
if command == CMD_ERROR {
return Err(RNodeCapabilityAdmissionError::DeviceError);
}
match self.protocol_state.apply_frame(command, &payload) {
RNodeProtocolEffect::Rejected(RNodeFrameRejection::UnknownCommand) => {}
RNodeProtocolEffect::Rejected(rejection) => {
return Err(RNodeCapabilityAdmissionError::MalformedProtocolFrame {
rejection,
});
}
RNodeProtocolEffect::RadioInitialisationFault => {
unreachable!("CMD_ERROR is rejected before protocol reduction")
}
RNodeProtocolEffect::EvidenceChanged(_)
| RNodeProtocolEffect::FlowPermissionChanged(_)
| RNodeProtocolEffect::Reset
| RNodeProtocolEffect::NoChange => {}
}
}
let evidence = self.protocol_state.evidence();
if self.protocol_state.detection_observed() && !evidence.detected {
return Err(RNodeCapabilityAdmissionError::DetectionRejected);
}
if evidence
.firmware
.is_some_and(|firmware| !firmware.is_supported())
{
return Err(RNodeCapabilityAdmissionError::UnsupportedFirmware);
}
Ok((evidence.detected && evidence.firmware.is_some())
.then_some(self.admission)
.flatten())
}
/// Return the only preflight evidence that may seed active readiness.
///
/// Configuration, radio, and flow frames observed before the runtime sends
/// its admitted init sequence may be stale. They remain reduced privately
/// during preflight but never cross the admission boundary.
pub(crate) fn into_protocol_state(self) -> RNodeProtocolState {
let target = self.protocol_state.target();
let evidence = self.protocol_state.evidence();
let mut admitted = RNodeProtocolState::with_effective_settings(target);
if evidence.detected {
admitted.apply_frame(crate::rnode::CMD_DETECT, &[crate::rnode::DETECT_RESP]);
}
if let Some(firmware) = evidence.firmware {
admitted.apply_frame(
crate::rnode::CMD_FW_VERSION,
&[firmware.major, firmware.minor],
);
}
admitted
}
}
#[cfg(test)]
mod tests {
use md5::{Digest, Md5};
use super::*;
use crate::rnode::{
CMD_DETECT, CMD_FW_VERSION, DETECT_RESP, REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN,
};
fn settings(frequency: u32, tx_power: u8) -> RNodeRadioSettings {
RNodeRadioSettings::new(frequency, 125_000, 7, 5, tx_power)
}
fn eeprom(model: u8) -> Vec<u8> {
let mut bytes = vec![0xFF; 1024];
bytes[0] = 0x03;
bytes[1] = model;
bytes[2..11].copy_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8, 9]);
let checksum: [u8; 16] = Md5::digest(&bytes[..11]).into();
bytes[11..27].copy_from_slice(&checksum);
// Exercise both extended-KISS escape forms outside the validated
// identity prefix.
bytes[100] = kiss::FEND;
bytes[101] = kiss::FESC;
bytes[0x9B] = 0x73;
bytes
}
fn observe_chunked(
preflight: &mut RNodeCapabilityPreflight,
bytes: &[u8],
) -> Result<Option<RNodeRadioAdmission>, RNodeCapabilityAdmissionError> {
let mut admission = None;
for chunk in bytes.chunks(257) {
admission = preflight.observe_read(chunk)?.or(admission);
}
Ok(admission)
}
fn admitted_frames(model: u8) -> Vec<u8> {
let mut frames = Vec::new();
kiss::frame_with_command_into(CMD_DETECT, &[DETECT_RESP], &mut frames);
kiss::frame_with_command_into(
CMD_FW_VERSION,
&[REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN],
&mut frames,
);
kiss::frame_with_command_into(CMD_ROM_READ, &eeprom(model), &mut frames);
frames
}
fn unlocked_eeprom(model: u8) -> Vec<u8> {
let mut bytes = eeprom(model);
bytes[0x9B] = 0xFF;
// Corrupt the checksum region too: unlocked images must admit without
// consulting it.
for byte in &mut bytes[11..27] {
*byte = 0x5A;
}
bytes
}
fn unprovisioned_frames(model: u8) -> Vec<u8> {
let mut frames = Vec::new();
kiss::frame_with_command_into(CMD_DETECT, &[DETECT_RESP], &mut frames);
kiss::frame_with_command_into(
CMD_FW_VERSION,
&[REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN],
&mut frames,
);
kiss::frame_with_command_into(CMD_ROM_READ, &unlocked_eeprom(model), &mut frames);
frames
}
#[test]
fn unlocked_eeprom_admits_unprovisioned_and_never_consults_model_bounds() {
// Model 0xB4 at 868 MHz is a typed FrequencyOutOfRange when locked
// (see known_model_mismatch_and_bounds_are_typed); unlocked, the model
// byte is unattested and must impose nothing.
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
let result = observe_chunked(&mut preflight, &unprovisioned_frames(0xB4)).unwrap();
assert_eq!(result, Some(RNodeRadioAdmission::Unprovisioned));
let seed = preflight.into_protocol_state();
assert!(seed.evidence().detected);
assert!(seed.evidence().firmware.is_some());
}
#[test]
fn unlocked_eeprom_still_fails_generic_radio_validation() {
let mut preflight = RNodeCapabilityPreflight::new(settings(1, 14));
assert!(matches!(
observe_chunked(&mut preflight, &unprovisioned_frames(0xB8)),
Err(RNodeCapabilityAdmissionError::RadioSettings(
crate::rnode_capabilities::RNodeRadioAdmissionError::GenericValidation(_)
))
));
}
#[test]
fn unlocked_then_duplicate_rom_response_remains_fatal() {
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert_eq!(
observe_chunked(&mut preflight, &unprovisioned_frames(0xB8)).unwrap(),
Some(RNodeRadioAdmission::Unprovisioned)
);
assert_eq!(
observe_chunked(
&mut preflight,
&kiss::frame_with_command(CMD_ROM_READ, &unlocked_eeprom(0xB8)),
),
Err(RNodeCapabilityAdmissionError::DuplicateEepromResponse)
);
}
#[test]
fn capability_request_is_one_standalone_rom_read_zero_frame() {
assert_eq!(
build_rnode_capability_request(),
kiss::frame_with_command(CMD_ROM_READ, &[0])
);
}
#[test]
fn fragmented_and_escaped_eeprom_admits_verified_model() {
let bytes = admitted_frames(0xB8);
assert!(bytes.contains(&kiss::FESC));
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
let result = observe_chunked(&mut preflight, &bytes).unwrap();
assert!(matches!(result, Some(RNodeRadioAdmission::Verified { .. })));
assert!(preflight.into_protocol_state().evidence().detected);
}
#[test]
fn validated_unknown_model_is_explicitly_unverified() {
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert!(matches!(
observe_chunked(&mut preflight, &admitted_frames(0xFE)).unwrap(),
Some(RNodeRadioAdmission::Unverified {
model_code: 0xFE,
..
})
));
}
#[test]
fn data_and_wrong_commands_do_not_satisfy_or_escape_preflight() {
let mut bytes = Vec::new();
kiss::frame_with_command_into(kiss::CMD_DATA, b"private packet", &mut bytes);
kiss::frame_with_command_into(crate::rnode::CMD_PLATFORM, &[0x80], &mut bytes);
kiss::frame_with_command_into(CMD_ROM_READ.wrapping_add(1), &eeprom(0xB8), &mut bytes);
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert_eq!(observe_chunked(&mut preflight, &bytes).unwrap(), None);
}
#[test]
fn malformed_control_device_error_and_invalid_image_fail_closed() {
let mut malformed = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
let malformed_frame = kiss::frame_with_command(CMD_FW_VERSION, &[1]);
assert!(matches!(
malformed.observe_read(&malformed_frame),
Err(RNodeCapabilityAdmissionError::MalformedProtocolFrame { .. })
));
let mut device_error = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert_eq!(
device_error.observe_read(&kiss::frame_with_command(CMD_ERROR, &[0x7F])),
Err(RNodeCapabilityAdmissionError::DeviceError)
);
let mut invalid = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert!(matches!(
invalid.observe_read(&kiss::frame_with_command(CMD_ROM_READ, &[0; 8])),
Err(RNodeCapabilityAdmissionError::CapabilityImage(_))
));
}
#[test]
fn known_model_mismatch_and_bounds_are_typed() {
let mut mismatch = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
let result = observe_chunked(&mut mismatch, &admitted_frames(0xB4));
assert!(matches!(
result,
Err(RNodeCapabilityAdmissionError::RadioSettings(
crate::rnode_capabilities::RNodeRadioAdmissionError::FrequencyOutOfRange { .. }
))
));
let mut bounded = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
for _ in 0..RNODE_CAPABILITY_MAX_READS {
assert_eq!(bounded.observe_read(&[]).unwrap(), None);
}
assert_eq!(
bounded.observe_read(&[]),
Err(RNodeCapabilityAdmissionError::ReadLimitExceeded {
limit: RNODE_CAPABILITY_MAX_READS
})
);
}
#[test]
fn negative_detection_unsupported_firmware_and_duplicate_rom_are_typed() {
let mut detection = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert_eq!(
detection.observe_read(&kiss::frame_with_command(CMD_DETECT, &[0])),
Err(RNodeCapabilityAdmissionError::DetectionRejected)
);
let mut firmware = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert_eq!(
firmware.observe_read(&kiss::frame_with_command(
CMD_FW_VERSION,
&[REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN - 1],
)),
Err(RNodeCapabilityAdmissionError::UnsupportedFirmware)
);
let mut duplicate = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert_eq!(
observe_chunked(
&mut duplicate,
&kiss::frame_with_command(CMD_ROM_READ, &eeprom(0xB8)),
)
.unwrap(),
None
);
assert_eq!(
observe_chunked(
&mut duplicate,
&kiss::frame_with_command(CMD_ROM_READ, &eeprom(0xB8)),
),
Err(RNodeCapabilityAdmissionError::DuplicateEepromResponse)
);
}
#[test]
fn cumulative_input_and_frame_limits_fail_closed() {
let mut input = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
let chunk = vec![0; RNODE_CAPABILITY_READ_BUFFER_BYTES];
for _ in 0..(RNODE_CAPABILITY_MAX_INPUT_BYTES / chunk.len()) {
assert_eq!(input.observe_read(&chunk).unwrap(), None);
}
assert_eq!(
input.observe_read(&[0]),
Err(RNodeCapabilityAdmissionError::InputLimitExceeded {
limit: RNODE_CAPABILITY_MAX_INPUT_BYTES
})
);
let mut frame_bytes = Vec::new();
for _ in 0..=RNODE_CAPABILITY_MAX_FRAMES {
kiss::frame_with_command_into(crate::rnode::CMD_PLATFORM, &[0], &mut frame_bytes);
}
let mut frames = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert_eq!(
frames.observe_read(&frame_bytes),
Err(RNodeCapabilityAdmissionError::FrameLimitExceeded {
limit: RNODE_CAPABILITY_MAX_FRAMES
})
);
}
#[test]
fn partial_frame_never_admits_and_is_not_replayed() {
let bytes = admitted_frames(0xB8);
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert_eq!(
observe_chunked(&mut preflight, &bytes[..bytes.len() - 1]).unwrap(),
None
);
drop(preflight);
let mut fresh = kiss::RawKissDeframer::new();
assert!(fresh.feed(&bytes[bytes.len() - 1..]).is_empty());
}
#[test]
fn stale_pre_init_radio_evidence_cannot_make_admitted_seed_ready() {
let settings = settings(868_000_000, 14);
let mut bytes = Vec::new();
kiss::frame_with_command_into(
crate::rnode::CMD_FREQUENCY,
&settings.frequency.to_be_bytes(),
&mut bytes,
);
kiss::frame_with_command_into(
crate::rnode::CMD_BANDWIDTH,
&settings.bandwidth.to_be_bytes(),
&mut bytes,
);
kiss::frame_with_command_into(
crate::rnode::CMD_SF,
&[settings.spreading_factor],
&mut bytes,
);
kiss::frame_with_command_into(crate::rnode::CMD_CR, &[settings.coding_rate], &mut bytes);
kiss::frame_with_command_into(crate::rnode::CMD_TXPOWER, &[settings.tx_power], &mut bytes);
kiss::frame_with_command_into(
crate::rnode::CMD_RADIO_STATE,
&[crate::rnode::RADIO_STATE_ON],
&mut bytes,
);
bytes.extend_from_slice(&admitted_frames(0xB8));
let mut preflight = RNodeCapabilityPreflight::new(settings);
assert!(observe_chunked(&mut preflight, &bytes).unwrap().is_some());
let seed = preflight.into_protocol_state();
assert!(seed.evidence().detected);
assert!(seed.evidence().firmware.is_some());
assert_eq!(seed.evidence().frequency, None);
assert_eq!(seed.evidence().radio_state, None);
assert!(matches!(
seed.readiness(),
crate::rnode_protocol::RNodeReadiness::Blocked(
crate::rnode_protocol::RNodeReadinessBlocker::Missing(
crate::rnode_protocol::RNodeReadinessEvidence::Frequency
)
)
));
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+84 -44
View File
@@ -1,6 +1,7 @@
//! HDLC-framed data over a serial port. Uses `serialport` with
//! `spawn_blocking` because no mature async driver exists yet.
//! HDLC-framed data over a serial port. Requires feature `serial`. Blocking
//! `serialport` reads and writes run through Tokio's `spawn_blocking`.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;
@@ -16,6 +17,18 @@ pub const DEFAULT_BAUD: u32 = 9600;
const SERIAL_READ_TIMEOUT_MS: u64 = 100;
/// Open with DTR and RTS asserted, as POSIX `open()` and pyserial do. Windows
/// otherwise leaves both low, and TinyUSB CDC (nRF52 RNodes) sends nothing
/// until DTR is up. DTR rises first: RTS alone resets ESP32 auto-reset wiring.
pub fn open_port(
builder: serialport::SerialPortBuilder,
) -> serialport::Result<Box<dyn serialport::SerialPort>> {
let mut port = builder.dtr_on_open(true).open()?;
// Best effort, like `dtr_on_open`: some adapters have no RTS line.
let _ = port.write_request_to_send(true);
Ok(port)
}
#[derive(Debug, Clone)]
pub struct SerialConfig {
pub name: String,
@@ -46,18 +59,51 @@ impl SerialConfig {
}
}
/// Map Python-style serial config values (`databits`/`parity`/`stopbits`)
/// to serialport enums. Parity accepts `e`/`even` and `o`/`odd`
/// (case-insensitive); anything else is none, matching the reference.
pub fn serial_params_from(
data_bits: u8,
parity: &str,
stop_bits: u8,
) -> (
serialport::DataBits,
serialport::Parity,
serialport::StopBits,
) {
let data = match data_bits {
5 => serialport::DataBits::Five,
6 => serialport::DataBits::Six,
7 => serialport::DataBits::Seven,
_ => serialport::DataBits::Eight,
};
let parity = match parity.to_ascii_lowercase().as_str() {
"e" | "even" => serialport::Parity::Even,
"o" | "odd" => serialport::Parity::Odd,
_ => serialport::Parity::None,
};
let stop = match stop_bits {
2 => serialport::StopBits::Two,
_ => serialport::StopBits::One,
};
(data, parity, stop)
}
pub async fn spawn_serial_interface(
config: SerialConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let port = serialport::new(&config.port, config.baud_rate)
.data_bits(config.data_bits)
.parity(config.parity)
.stop_bits(config.stop_bits)
.timeout(Duration::from_millis(SERIAL_READ_TIMEOUT_MS))
.open()
.map_err(|e| crate::traits::InterfaceError::SendFailed(format!("serial open: {}", e)))?;
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let port = open_port(
serialport::new(&config.port, config.baud_rate)
.data_bits(config.data_bits)
.parity(config.parity)
.stop_bits(config.stop_bits)
.timeout(Duration::from_millis(SERIAL_READ_TIMEOUT_MS)),
)
.map_err(|e| crate::traits::InterfaceError::SendFailed(format!("serial open: {}", e)))?;
tracing::info!(
name = %config.name,
@@ -70,6 +116,7 @@ pub async fn spawn_serial_interface(
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let (tx, mut rx) = mpsc::channel::<Bytes>(256);
let background = crate::background_announce::register(&tx)?;
let name = config.name.clone();
let mode = config.mode;
@@ -81,28 +128,33 @@ pub async fn spawn_serial_interface(
let txb_w = shared_txb.clone();
tokio::spawn(async move {
let mut port_w = port_write;
while let Some(data) = rx.recv().await {
loop {
if !online_w.load(Ordering::SeqCst) {
break;
}
let background_packet = if rx.is_empty() {
background.try_start(rns_transport::now_f64())
} else {
None
};
let data = if let Some(packet) = &background_packet {
packet.raw().clone()
} else {
match tokio::time::timeout(Duration::from_millis(100), rx.recv()).await {
Ok(Some(data)) => data,
Ok(None) => break,
Err(_) => continue,
}
};
txb_w.fetch_add(data.len() as u64, std::sync::atomic::Ordering::Relaxed);
let framed = hdlc::frame(&data);
let online_ref = online_w.clone();
let result = tokio::task::spawn_blocking(move || {
use std::io::Write;
port_w.write_all(&framed)?;
port_w.flush()?;
Ok::<_, std::io::Error>(port_w)
})
.await;
match result {
Ok(Ok(p)) => {
match crate::serial_io::blocking_write_all(port_w, framed).await {
Ok(p) => {
port_w = p;
}
Ok(Err(e)) => {
tracing::warn!(error = %e, "serial write error");
online_ref.store(false, Ordering::SeqCst);
break;
}
Err(e) => {
tracing::warn!(error = %e, "serial write task panicked");
tracing::warn!(error = %e, "serial write error");
online_w.store(false, Ordering::SeqCst);
break;
}
}
@@ -120,18 +172,8 @@ pub async fn spawn_serial_interface(
if !online_r.load(Ordering::SeqCst) {
break;
}
let result = tokio::task::spawn_blocking(move || {
use std::io::Read;
match port_r.read(&mut buf) {
Ok(n) => Ok((port_r, buf, n)),
Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok((port_r, buf, 0)),
Err(e) => Err((port_r, e)),
}
})
.await;
match result {
Ok(Ok((p, b, n))) => {
match crate::serial_io::poll_read(port_r, buf).await {
Ok((p, b, n)) => {
port_r = p;
buf = b;
if n > 0 {
@@ -155,13 +197,8 @@ pub async fn spawn_serial_interface(
}
}
}
Ok(Err((_p, e))) => {
tracing::warn!(error = %e, "serial read error");
online_r.store(false, Ordering::SeqCst);
return;
}
Err(e) => {
tracing::warn!(error = %e, "serial read task panicked");
tracing::warn!(error = %e, "serial read error");
online_r.store(false, Ordering::SeqCst);
return;
}
@@ -171,6 +208,8 @@ pub async fn spawn_serial_interface(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 564, false),
parent_id: None,
name,
mode,
@@ -185,6 +224,7 @@ pub async fn spawn_serial_interface(
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: None,
tx,
read_task,
})
+43
View File
@@ -0,0 +1,43 @@
//! Blocking-I/O shuttles shared by the serial-family interfaces (Serial,
//! KISS, AX.25 KISS, RNodeMulti). No mature async serial driver exists, so
//! each read/write moves the port through `spawn_blocking` and back.
/// One bounded blocking read. Serial idle timeouts surface as `n == 0` so
/// the caller's loop can re-check its exit flag. A panicked blocking task
/// folds into an `io::Error`.
#[cfg(feature = "serial")]
pub(crate) async fn poll_read<P>(
mut port: P,
mut buf: [u8; 1024],
) -> Result<(P, [u8; 1024], usize), std::io::Error>
where
P: std::io::Read + Send + 'static,
{
let result = tokio::task::spawn_blocking(move || match port.read(&mut buf) {
Ok(n) => Ok((port, buf, n)),
Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok((port, buf, 0)),
Err(e) => Err(e),
})
.await;
match result {
Ok(read_result) => read_result,
Err(join_err) => Err(std::io::Error::other(join_err)),
}
}
/// One blocking `write_all` + `flush`, returning the port for the next call.
pub(crate) async fn blocking_write_all<P>(mut port: P, data: Vec<u8>) -> Result<P, std::io::Error>
where
P: std::io::Write + Send + 'static,
{
let result = tokio::task::spawn_blocking(move || {
port.write_all(&data)?;
port.flush()?;
Ok::<_, std::io::Error>(port)
})
.await;
match result {
Ok(write_result) => write_result,
Err(join_err) => Err(std::io::Error::other(join_err)),
}
}
+96 -141
View File
@@ -1,109 +1,80 @@
//! Shared TCP socket tuning for [`crate::tcp`] and [`crate::backbone`].
//! `set_keepalive`: portable SO_KEEPALIVE. `set_keepalive_tuned`: adds Linux
//! TCP_KEEPIDLE/INTVL/CNT + TCP_USER_TIMEOUT.
//! `iface_addr_for`: kernel iface name → IpAddr for Backbone `device =` key.
//! Shared TCP socket tuning for [`crate::tcp`], [`crate::backbone`],
//! [`crate::i2p`], and [`crate::rnode`] (TCP transport).
//!
//! The helpers accept Tokio and standard-library streams through their raw
//! socket handles. Keepalive settings are applied where the platform supports
//! them; TCP_USER_TIMEOUT is set on Linux, Android, and Fuchsia. Tuning is
//! best effort. Interface-address helpers resolve local device names.
use std::net::IpAddr;
use std::time::Duration;
use tokio::net::TcpStream;
/// Enable portable `SO_KEEPALIVE`; for tuned, use [`set_keepalive_tuned`].
/// Borrow the raw fd/socket as a `socket2::Socket` without taking ownership
/// (`ManuallyDrop` keeps the destructor from closing it).
#[cfg(unix)]
pub fn set_keepalive(stream: &TcpStream) -> std::io::Result<()> {
use std::os::fd::{AsRawFd, FromRawFd};
let raw_fd = stream.as_ref().as_raw_fd();
fn with_socket2<S: std::os::fd::AsRawFd, R>(
stream: &S,
f: impl FnOnce(&socket2::Socket) -> R,
) -> R {
use std::os::fd::FromRawFd;
// SAFETY: we borrow the fd without taking ownership (ManuallyDrop ensures
// the socket2::Socket destructor does not close the fd).
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
sock.set_keepalive(true)?;
Ok(())
let sock =
std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(stream.as_raw_fd()) });
f(&sock)
}
#[cfg(windows)]
pub fn set_keepalive(stream: &TcpStream) -> std::io::Result<()> {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_ref().as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
sock.set_keepalive(true)?;
Ok(())
fn with_socket2<S: std::os::windows::io::AsRawSocket, R>(
stream: &S,
f: impl FnOnce(&socket2::Socket) -> R,
) -> R {
use std::os::windows::io::FromRawSocket;
// SAFETY: same borrow-without-ownership contract as the unix variant.
let sock = std::mem::ManuallyDrop::new(unsafe {
socket2::Socket::from_raw_socket(stream.as_raw_socket())
});
f(&sock)
}
/// Enable portable `SO_KEEPALIVE` on a blocking std TCP stream.
/// Platform bound for streams the tuning helpers accept: anything exposing
/// the raw socket handle (tokio `TcpStream`, std `TcpStream`, …).
#[cfg(unix)]
pub fn set_keepalive_std(stream: &std::net::TcpStream) -> std::io::Result<()> {
use std::os::fd::{AsRawFd, FromRawFd};
let raw_fd = stream.as_raw_fd();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
sock.set_keepalive(true)?;
Ok(())
}
#[cfg(windows)]
pub fn set_keepalive_std(stream: &std::net::TcpStream) -> std::io::Result<()> {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
sock.set_keepalive(true)?;
Ok(())
}
/// Tuned keepalive: idle/interval/retries + Linux TCP_USER_TIMEOUT. Best-effort.
pub trait RawStream: std::os::fd::AsRawFd {}
#[cfg(unix)]
pub fn set_keepalive_tuned(
stream: &TcpStream,
idle: Duration,
intvl: Duration,
retries: u32,
user_timeout: Duration,
) {
use std::os::fd::{AsRawFd, FromRawFd};
let raw_fd = stream.as_ref().as_raw_fd();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
}
impl<T: std::os::fd::AsRawFd> RawStream for T {}
#[cfg(windows)]
pub fn set_keepalive_tuned(
stream: &TcpStream,
idle: Duration,
intvl: Duration,
retries: u32,
user_timeout: Duration,
) {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_ref().as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
}
/// Tuned keepalive for blocking std TCP streams. Best-effort.
#[cfg(unix)]
pub fn set_keepalive_tuned_std(
stream: &std::net::TcpStream,
idle: Duration,
intvl: Duration,
retries: u32,
user_timeout: Duration,
) {
use std::os::fd::{AsRawFd, FromRawFd};
let raw_fd = stream.as_raw_fd();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
}
pub trait RawStream: std::os::windows::io::AsRawSocket {}
#[cfg(windows)]
pub fn set_keepalive_tuned_std(
stream: &std::net::TcpStream,
impl<T: std::os::windows::io::AsRawSocket> RawStream for T {}
/// Enable portable `SO_KEEPALIVE`; for tuned, use [`set_keepalive_tuned`].
pub fn set_keepalive<S: RawStream>(stream: &S) -> std::io::Result<()> {
with_socket2(stream, |sock| sock.set_keepalive(true))
}
/// Request keepalive idle time, interval, and retry count where supported,
/// plus TCP_USER_TIMEOUT on Linux, Android, and Fuchsia. Best effort.
pub fn set_keepalive_tuned<S: RawStream>(
stream: &S,
idle: Duration,
intvl: Duration,
retries: u32,
user_timeout: Duration,
) {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
with_socket2(stream, |sock| {
apply_tuned_keepalive(sock, idle, intvl, retries, user_timeout)
});
}
/// Request TCP send and receive buffer sizes. The kernel may adjust them;
/// errors are ignored.
pub fn set_socket_buffers<S: RawStream>(stream: &S, size: usize) {
with_socket2(stream, |sock| {
let _ = sock.set_recv_buffer_size(size);
let _ = sock.set_send_buffer_size(size);
});
}
fn apply_tuned_keepalive(
@@ -136,46 +107,29 @@ fn apply_tuned_keepalive(
let _ = user_timeout;
}
/// Raise TCP send/recv buffers; best-effort.
#[cfg(unix)]
pub fn set_socket_buffers(stream: &TcpStream, size: usize) {
use std::os::fd::{AsRawFd, FromRawFd};
let raw_fd = stream.as_ref().as_raw_fd();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
let _ = sock.set_recv_buffer_size(size);
let _ = sock.set_send_buffer_size(size);
/// Resolve interface name to its IPv4 broadcast address; `None` if the
/// interface is missing or has no broadcast-capable IPv4. Python UDP
/// `device =` semantics (`get_broadcast_for_if`).
pub fn iface_broadcast_for(name: &str) -> Option<std::net::Ipv4Addr> {
let ifaces = match if_addrs::get_if_addrs() {
Ok(v) => v,
Err(e) => {
tracing::warn!(error = %e, "if_addrs::get_if_addrs() failed");
return None;
}
};
ifaces.into_iter().filter(|i| i.name == name).find_map(|i| {
if let if_addrs::IfAddr::V4(v4) = i.addr {
v4.broadcast
} else {
None
}
})
}
#[cfg(windows)]
pub fn set_socket_buffers(stream: &TcpStream, size: usize) {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_ref().as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
let _ = sock.set_recv_buffer_size(size);
let _ = sock.set_send_buffer_size(size);
}
/// Raise TCP send/recv buffers on a blocking std TCP stream; best-effort.
#[cfg(unix)]
pub fn set_socket_buffers_std(stream: &std::net::TcpStream, size: usize) {
use std::os::fd::{AsRawFd, FromRawFd};
let raw_fd = stream.as_raw_fd();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
let _ = sock.set_recv_buffer_size(size);
let _ = sock.set_send_buffer_size(size);
}
#[cfg(windows)]
pub fn set_socket_buffers_std(stream: &std::net::TcpStream, size: usize) {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
let _ = sock.set_recv_buffer_size(size);
let _ = sock.set_send_buffer_size(size);
}
/// Resolve interface name to `IpAddr`; `None` if missing. Caller falls back
/// to wildcard bind.
/// Resolve an interface name to `IpAddr`, preferring the requested address
/// family and falling back to the other family. Returns `None` if enumeration
/// fails or no address matches; the caller decides whether to fall back.
pub fn iface_addr_for(name: &str, prefer_ipv6: bool) -> Option<IpAddr> {
let ifaces = match if_addrs::get_if_addrs() {
Ok(v) => v,
@@ -210,7 +164,7 @@ pub fn iface_addr_for(name: &str, prefer_ipv6: bool) -> Option<IpAddr> {
#[cfg(test)]
mod tests {
use super::*;
use tokio::net::TcpListener;
use tokio::net::{TcpListener, TcpStream};
#[tokio::test]
async fn keepalive_and_buffers_apply_without_panic() {
@@ -244,6 +198,7 @@ mod tests {
set_socket_buffers(&client, 131_072);
}
/// The same generic helpers must accept blocking std streams.
#[test]
fn std_keepalive_and_buffers_apply_without_panic() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
@@ -252,17 +207,17 @@ mod tests {
let client = std::net::TcpStream::connect(addr).unwrap();
let server = accept.join().unwrap();
set_keepalive_std(&server).expect("server set_keepalive_std");
set_keepalive_std(&client).expect("client set_keepalive_std");
set_keepalive(&server).expect("server set_keepalive");
set_keepalive(&client).expect("client set_keepalive");
set_keepalive_tuned_std(
set_keepalive_tuned(
&server,
Duration::from_secs(5),
Duration::from_secs(2),
12,
Duration::from_secs(24),
);
set_keepalive_tuned_std(
set_keepalive_tuned(
&client,
Duration::from_secs(5),
Duration::from_secs(2),
@@ -270,8 +225,8 @@ mod tests {
Duration::from_secs(24),
);
set_socket_buffers_std(&server, 131_072);
set_socket_buffers_std(&client, 131_072);
set_socket_buffers(&server, 131_072);
set_socket_buffers(&client, 131_072);
}
#[test]
@@ -280,21 +235,21 @@ mod tests {
let candidates = ["lo", "lo0", "Loopback Pseudo-Interface 1"];
let mut found_v4 = false;
for name in candidates {
if let Some(IpAddr::V4(v4)) = iface_addr_for(name, false) {
if v4.is_loopback() {
found_v4 = true;
break;
}
if let Some(IpAddr::V4(v4)) = iface_addr_for(name, false)
&& v4.is_loopback()
{
found_v4 = true;
break;
}
}
// Hermetic CI may not expose loopback by name; only assert when seen.
if let Ok(ifaces) = if_addrs::get_if_addrs() {
if ifaces.iter().any(|i| candidates.contains(&i.name.as_str())) {
assert!(
found_v4,
"expected a loopback IPv4 on one of {candidates:?}"
);
}
if let Ok(ifaces) = if_addrs::get_if_addrs()
&& ifaces.iter().any(|i| candidates.contains(&i.name.as_str()))
{
assert!(
found_v4,
"expected a loopback IPv4 on one of {candidates:?}"
);
}
}
+308 -42
View File
@@ -1,3 +1,4 @@
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -8,31 +9,69 @@ use tokio::sync::mpsc;
use crate::hdlc;
use crate::kiss;
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
use crate::traits::{
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, TunnelIdentity,
handoff_accepted_interface, open_client_connection, python_host,
};
use rns_transport::messages::{InboundPacket, TransportMessage};
pub const RECONNECT_WAIT_INITIAL: u64 = 5;
pub const RECONNECT_WAIT_MAX: u64 = 300;
pub const DEFAULT_CONNECT_TIMEOUT: u64 = 5;
pub const DEFAULT_TCP_USER_TIMEOUT: u32 = 24;
/// I2P tunnels need a longer `TCP_USER_TIMEOUT` to absorb latency spikes.
pub const I2P_TCP_USER_TIMEOUT: u32 = 45;
pub const TCP_HW_MTU: u32 = 262144;
// Python TCPClientInterface: TCP_PROBE_AFTER / TCP_PROBE_INTERVAL / TCP_PROBES.
// Dead-peer detection: 5s idle + 12 probes × 2s ≈ 29s.
pub const TCP_KEEPIDLE: u32 = 5;
pub const TCP_KEEPINTVL: u32 = 2;
pub const TCP_KEEPCNT: u32 = 12;
/// Python's ordinary TCP or I2P Linux timeout values through the shared Rust
/// socket tuner. Accepted sockets use ordinary TCP tuning.
pub(crate) fn set_tcp_keepalive_tuned(stream: &TcpStream, i2p_tunneled: bool) {
let (idle, interval, count, user_timeout) = if i2p_tunneled {
(
crate::i2p::I2P_PROBE_AFTER,
crate::i2p::I2P_PROBE_INTERVAL,
crate::i2p::I2P_PROBES as u32,
crate::i2p::I2P_TCP_USER_TIMEOUT,
)
} else {
(
TCP_KEEPIDLE as u64,
TCP_KEEPINTVL as u64,
TCP_KEEPCNT,
DEFAULT_TCP_USER_TIMEOUT,
)
};
crate::socket_tuning::set_keepalive_tuned(
stream,
std::time::Duration::from_secs(idle),
std::time::Duration::from_secs(interval),
count,
std::time::Duration::from_secs(user_timeout as u64),
);
}
#[derive(Debug, Clone)]
pub struct TcpClientConfig {
pub name: String,
pub target_host: String,
pub target_port: u16,
pub kiss_framing: bool,
/// Use the longer socket timeouts for a TCP connection tunneled over I2P.
pub i2p_tunneled: bool,
pub connect_timeout_secs: u64,
pub max_reconnect_tries: Option<usize>,
pub mode: InterfaceMode,
/// Override the MTU used for link MTU discovery. Accepted values are
/// 500 through 262,144 bytes, inclusive.
pub fixed_mtu: Option<u32>,
/// Identity used to request a signed tunnel synthesis for each non-KISS
/// connection. `None`, or an identity without signing material, sends none.
pub tunnel_identity: Option<TunnelIdentity>,
}
impl TcpClientConfig {
@@ -42,11 +81,24 @@ impl TcpClientConfig {
target_host: host.to_string(),
target_port: port,
kiss_framing: false,
i2p_tunneled: false,
connect_timeout_secs: DEFAULT_CONNECT_TIMEOUT,
max_reconnect_tries: None,
mode: InterfaceMode::Full,
fixed_mtu: None,
tunnel_identity: None,
}
}
/// Python `str(TCPClientInterface)` (TCPInterface.py:457-461).
pub fn python_name(&self) -> String {
format!(
"TCPInterface[{}/{}:{}]",
self.name,
python_host(&self.target_host),
self.target_port
)
}
}
#[derive(Debug, Clone)]
@@ -57,6 +109,9 @@ pub struct TcpServerConfig {
pub kiss_framing: bool,
pub prefer_ipv6: bool,
pub mode: InterfaceMode,
/// Bind to this network device's address instead of `listen_ip`
/// (Python `device =` option).
pub device: Option<String>,
}
impl TcpServerConfig {
@@ -68,10 +123,30 @@ impl TcpServerConfig {
kiss_framing: false,
prefer_ipv6: false,
mode: InterfaceMode::Full,
device: None,
}
}
}
/// First usable address on `device`, honouring `prefer_ipv6`. Python
/// `TCPServerInterface.get_address_for_if` equivalent.
fn address_for_device(device: &str, prefer_ipv6: bool) -> Option<std::net::IpAddr> {
let addrs = if_addrs::get_if_addrs().ok()?;
let on_dev: Vec<std::net::IpAddr> = addrs
.iter()
.filter(|a| a.name == device)
.map(|a| a.ip())
.collect();
if prefer_ipv6 && let Some(v6) = on_dev.iter().find(|ip| ip.is_ipv6()) {
return Some(*v6);
}
on_dev
.iter()
.find(|ip| ip.is_ipv4())
.or_else(|| on_dev.first())
.copied()
}
pub struct TcpInterfaceState {
pub online: AtomicBool,
pub detached: AtomicBool,
@@ -86,28 +161,14 @@ pub struct TcpInterfaceState {
impl TcpInterfaceState {
pub fn new() -> Arc<Self> {
Arc::new(Self {
online: AtomicBool::new(false),
detached: AtomicBool::new(false),
rx_bytes: AtomicU64::new(0),
tx_bytes: AtomicU64::new(0),
rx_packets: AtomicU64::new(0),
tx_packets: AtomicU64::new(0),
shared_rxb: None,
shared_txb: None,
})
Arc::new(Self::default())
}
pub fn with_shared_counters(rxb: Arc<AtomicU64>, txb: Arc<AtomicU64>) -> Arc<Self> {
Arc::new(Self {
online: AtomicBool::new(false),
detached: AtomicBool::new(false),
rx_bytes: AtomicU64::new(0),
tx_bytes: AtomicU64::new(0),
rx_packets: AtomicU64::new(0),
tx_packets: AtomicU64::new(0),
shared_rxb: Some(rxb),
shared_txb: Some(txb),
..Self::default()
})
}
@@ -151,12 +212,12 @@ pub fn frame_for_tcp(data: &[u8], kiss_framing: bool) -> Vec<u8> {
}
}
use crate::socket_tuning::{set_keepalive, set_socket_buffers};
use crate::socket_tuning::set_socket_buffers;
async fn tcp_read_loop(
mut reader: tokio::net::tcp::OwnedReadHalf,
interface_id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
transport_tx: InterfaceTransportSender,
state: Arc<TcpInterfaceState>,
kiss_framing: bool,
) {
@@ -261,19 +322,30 @@ async fn tcp_write_loop(
state.online.store(false, Ordering::SeqCst);
}
/// Spawn an auto-reconnecting TCP client interface.
/// Spawn an auto-reconnecting TCP client interface. IFAC masking, when
/// configured, is applied by the transport actor, not the driver.
pub async fn spawn_tcp_client(
config: TcpClientConfig,
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
_ifac: Option<crate::traits::IfacConfig>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
if config
.fixed_mtu
.is_some_and(|mtu| !(500..=262144).contains(&mtu))
{
return Err(crate::traits::InterfaceError::SendFailed(
"fixed_mtu must be between 500 and 262144 clear packet bytes".into(),
));
}
let online = Arc::new(AtomicBool::new(false));
let online2 = online.clone();
let (tx, rx) = mpsc::channel::<Bytes>(1024);
let name = config.name.clone();
let mode = config.mode;
let kiss_framing = config.kiss_framing;
let fixed_mtu = config.fixed_mtu;
// Wrap rx so it survives reconnects; forwarder task feeds per-connection channel.
let rx = Arc::new(tokio::sync::Mutex::new(rx));
@@ -283,12 +355,16 @@ pub async fn spawn_tcp_client(
let task_rxb = shared_rxb.clone();
let task_txb = shared_txb.clone();
let python_name = config.python_name();
let read_task = tokio::spawn(async move {
let max_tries = config.max_reconnect_tries;
let mut tries: usize = 0;
let mut backoff = RECONNECT_WAIT_INITIAL;
// Every attempt after the first follows a failure or an outage.
let mut attempted = false;
loop {
let after_outage = std::mem::replace(&mut attempted, true);
let addr = format!("{}:{}", config.target_host, config.target_port);
let stream = match tokio::time::timeout(
std::time::Duration::from_secs(config.connect_timeout_secs),
@@ -303,6 +379,11 @@ pub async fn spawn_tcp_client(
tries += 1;
if tries >= max {
tracing::warn!(name = %config.name, "max reconnect tries reached");
// Same dereg as the post-connect give-up below —
// otherwise the actor keeps a zombie entry.
let _ = transport_tx
.send(TransportMessage::DeregisterInterface { id })
.await;
return;
}
}
@@ -316,6 +397,9 @@ pub async fn spawn_tcp_client(
tries += 1;
if tries >= max {
tracing::warn!(name = %config.name, "max reconnect tries reached");
let _ = transport_tx
.send(TransportMessage::DeregisterInterface { id })
.await;
return;
}
}
@@ -325,9 +409,7 @@ pub async fn spawn_tcp_client(
}
};
if let Err(e) = set_keepalive(&stream) {
tracing::debug!(error = %e, "failed to set TCP keepalive");
}
set_tcp_keepalive_tuned(&stream, config.i2p_tunneled);
// Nagle off for low-latency packets; larger buffers for bulk transfers.
let _ = stream.set_nodelay(true);
@@ -335,9 +417,16 @@ pub async fn spawn_tcp_client(
let state = TcpInterfaceState::with_shared_counters(task_rxb.clone(), task_txb.clone());
state.online.store(true, Ordering::SeqCst);
online2.store(true, Ordering::SeqCst);
tries = 0;
backoff = RECONNECT_WAIT_INITIAL;
// Python synthesizes on every non-KISS connection
// (TCPInterface.py:178-179, :298-299).
let synthesis = config
.tunnel_identity
.as_ref()
.filter(|_| !kiss_framing)
.and_then(|identity| identity.synthesis(&python_name));
open_client_connection(&rx, after_outage, &transport_tx, synthesis, &online2).await;
let (reader, writer) = stream.into_split();
@@ -391,6 +480,14 @@ pub async fn spawn_tcp_client(
let bitrate: u64 = 10_000_000;
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(
fixed_mtu
.unwrap_or_else(|| crate::traits::optimise_mtu(bitrate).unwrap_or(TCP_HW_MTU))
.min(262144),
262144,
fixed_mtu.is_some() || crate::traits::optimise_mtu(bitrate).is_some(),
),
parent_id: None,
name,
mode,
@@ -401,10 +498,12 @@ pub async fn spawn_tcp_client(
repeat: false,
},
bitrate,
mtu: crate::traits::optimise_mtu(bitrate).unwrap_or(TCP_HW_MTU),
mtu: fixed_mtu
.unwrap_or_else(|| crate::traits::optimise_mtu(bitrate).unwrap_or(TCP_HW_MTU)),
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: None,
tx,
read_task,
})
@@ -426,6 +525,8 @@ async fn spawn_tcp_accepted(
kiss_framing: bool,
mode: InterfaceMode,
) -> InterfaceHandle {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let online = Arc::new(AtomicBool::new(true));
let online2 = online.clone();
let (tx, conn_rx) = mpsc::channel::<Bytes>(1024);
@@ -435,9 +536,7 @@ async fn spawn_tcp_accepted(
let state = TcpInterfaceState::with_shared_counters(shared_rxb.clone(), shared_txb.clone());
state.online.store(true, Ordering::SeqCst);
if let Err(e) = set_keepalive(&stream) {
tracing::debug!(error = %e, "failed to set keepalive on accepted socket");
}
set_tcp_keepalive_tuned(&stream, false);
let _ = stream.set_nodelay(true);
set_socket_buffers(&stream, 131072);
@@ -461,6 +560,14 @@ async fn spawn_tcp_accepted(
let bitrate: u64 = 10_000_000;
InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(
crate::traits::optimise_mtu(bitrate)
.unwrap_or(TCP_HW_MTU)
.min(262144),
262144,
crate::traits::optimise_mtu(bitrate).is_some(),
),
parent_id: Some(parent_id),
name,
mode,
@@ -475,6 +582,7 @@ async fn spawn_tcp_accepted(
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: None,
tx,
read_task,
}
@@ -489,7 +597,19 @@ pub async fn spawn_tcp_server(
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let addr = format!("{}:{}", config.listen_ip, config.listen_port);
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let addr = match config.device.as_deref() {
Some(device) => {
let ip = address_for_device(device, config.prefer_ipv6).ok_or_else(|| {
crate::traits::InterfaceError::SendFailed(format!(
"no usable address on device '{device}'"
))
})?;
std::net::SocketAddr::new(ip, config.listen_port).to_string()
}
None => format!("{}:{}", config.listen_ip, config.listen_port),
};
let listener = TcpListener::bind(&addr).await?;
let local_addr = listener.local_addr()?;
tracing::info!(name = %config.name, addr = %local_addr, "TCP server listening");
@@ -515,12 +635,15 @@ pub async fn spawn_tcp_server(
client_id,
id,
client_name,
transport_tx.clone(),
transport_tx.actor_sender(),
kiss_framing,
mode,
)
.await;
if handle_tx.send(handle).await.is_err() {
if handoff_accepted_interface(&handle_tx, handle)
.await
.is_err()
{
tracing::warn!("handle registry channel closed, stopping accept loop");
break;
}
@@ -537,6 +660,14 @@ pub async fn spawn_tcp_server(
let bitrate: u64 = 10_000_000;
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(
crate::traits::optimise_mtu(bitrate)
.unwrap_or(TCP_HW_MTU)
.min(262144),
262144,
crate::traits::optimise_mtu(bitrate).is_some(),
),
parent_id: None,
name,
mode,
@@ -551,6 +682,7 @@ pub async fn spawn_tcp_server(
online,
rxb: Some(Arc::new(AtomicU64::new(0))),
txb: Some(Arc::new(AtomicU64::new(0))),
inspection: None,
tx,
read_task,
})
@@ -560,6 +692,24 @@ pub async fn spawn_tcp_server(
mod tests {
use super::*;
#[test]
fn client_python_names_match_python() {
// Python 1.5.5 `str()` output for these interfaces.
for (host, expected) in [
("127.0.0.1", "TCPInterface[Golden Uplink/127.0.0.1:4242]"),
("::1", "TCPInterface[Golden Uplink/[::1]:4242]"),
(
"hub.example.org",
"TCPInterface[Golden Uplink/hub.example.org:4242]",
),
] {
assert_eq!(
TcpClientConfig::new("Golden Uplink", host, 4242).python_name(),
expected
);
}
}
#[test]
fn test_tcp_client_config() {
let config = TcpClientConfig::new("test", "127.0.0.1", 4242);
@@ -575,6 +725,97 @@ mod tests {
assert!(!config.prefer_ipv6);
}
/// Read back Python's Linux timeout values applied by the shared Rust
/// socket tuner for ordinary TCP and I2P-tunneled connections.
#[cfg(unix)]
#[tokio::test]
async fn tuned_keepalive_applies_python_probe_values() {
use std::os::fd::AsRawFd;
fn get_opt(fd: i32, level: i32, name: i32) -> i32 {
let mut val: libc::c_int = 0;
let mut len = std::mem::size_of::<libc::c_int>() as libc::socklen_t;
let rc = unsafe {
libc::getsockopt(
fd,
level,
name,
&mut val as *mut _ as *mut libc::c_void,
&mut len,
)
};
assert_eq!(rc, 0, "getsockopt({level},{name}) failed");
val
}
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let (accepted, client) = tokio::join!(listener.accept(), TcpStream::connect(addr));
let client = client.unwrap();
let (server, _) = accepted.unwrap();
for (i2p_tunneled, _expected) in [(false, [5, 2, 12, 24]), (true, [10, 9, 5, 45])] {
for stream in [&client, &server] {
set_tcp_keepalive_tuned(stream, i2p_tunneled);
let fd = stream.as_ref().as_raw_fd();
// BSD getsockopt returns the option bit, not 1 — assert enabled.
assert_ne!(get_opt(fd, libc::SOL_SOCKET, libc::SO_KEEPALIVE), 0);
#[cfg(target_os = "linux")]
let idle = get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPIDLE);
#[cfg(target_os = "macos")]
let idle = get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPALIVE);
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
assert_eq!(idle, _expected[0]);
assert_eq!(
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPINTVL),
_expected[1]
);
assert_eq!(
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPCNT),
_expected[2]
);
}
#[cfg(target_os = "linux")]
assert_eq!(
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_USER_TIMEOUT),
_expected[3] * 1000
);
}
}
}
/// T1-11: exhausting max_reconnect_tries before the FIRST successful
/// connect must send DeregisterInterface, same as the post-connect path —
/// otherwise the actor keeps a zombie entry forever.
#[tokio::test]
async fn test_initial_connect_give_up_sends_deregister() {
let (transport_tx, mut transport_rx) = mpsc::channel::<TransportMessage>(8);
// Bind-then-drop: the port refuses connections immediately.
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
drop(listener);
let mut config = TcpClientConfig::new("tcp-giveup", &addr.ip().to_string(), addr.port());
config.max_reconnect_tries = Some(1);
config.connect_timeout_secs = 2;
let handle = spawn_tcp_client(config, 77, transport_tx).await.unwrap();
handle.owner.mark_registered();
let msg = tokio::time::timeout(std::time::Duration::from_secs(10), transport_rx.recv())
.await
.expect("expected DeregisterInterface before timeout")
.expect("transport channel closed");
match crate::traits::test_event_for_handle(msg, &handle) {
TransportMessage::DeregisterInterface { id } => assert_eq!(id, 77),
other => panic!("expected DeregisterInterface, got {other:?}"),
}
handle.read_task.abort();
}
#[test]
fn test_frame_for_tcp_hdlc() {
let data = b"test packet";
@@ -622,6 +863,7 @@ mod tests {
spawn_tcp_server(server_cfg2, 99, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
server_handle.owner.mark_registered();
assert_eq!(server_handle.id, 99);
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
@@ -631,28 +873,42 @@ mod tests {
target_host: "127.0.0.1".into(),
target_port: port,
kiss_framing: false,
i2p_tunneled: false,
connect_timeout_secs: 5,
max_reconnect_tries: Some(1),
mode: InterfaceMode::Full,
fixed_mtu: None,
tunnel_identity: None,
};
let client_handle = spawn_tcp_client(client_cfg, 1, transport_tx.clone(), None)
let client_handle = spawn_tcp_client(client_cfg, 1, transport_tx.clone())
.await
.unwrap();
client_handle.owner.mark_registered();
let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for accepted handle")
.expect("handle channel closed");
assert_ne!(accepted.owner, server_handle.owner);
assert_ne!(accepted.owner, client_handle.owner);
assert_eq!(accepted.packet_capacity.max_wire_packet_bytes, 262144);
let payload = Bytes::from_static(b"hello from client");
client_handle.tx.send(payload.clone()).await.unwrap();
assert!(
tokio::time::timeout(std::time::Duration::from_millis(20), transport_rx.recv())
.await
.is_err(),
"the first packet waits for accepted-child registration"
);
accepted.owner.mark_registered();
let msg = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv())
.await
.expect("timeout waiting for transport message")
.expect("transport channel closed");
match msg {
match crate::traits::test_event_for_handle(msg, &accepted) {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, payload);
assert_eq!(pkt.interface_id, accepted.id);
@@ -668,7 +924,7 @@ mod tests {
.expect("timeout waiting for reply")
.expect("transport channel closed");
match msg2 {
match crate::traits::test_event_for_handle(msg2, &client_handle) {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, reply);
assert_eq!(pkt.interface_id, 1);
@@ -715,14 +971,16 @@ mod tests {
target_host: "127.0.0.1".into(),
target_port: 1,
kiss_framing: false,
i2p_tunneled: false,
connect_timeout_secs: 1,
max_reconnect_tries: Some(2),
mode: InterfaceMode::Full,
fixed_mtu: None,
tunnel_identity: None,
};
let handle = spawn_tcp_client(config, 99, transport_tx, None)
.await
.unwrap();
let handle = spawn_tcp_client(config, 99, transport_tx).await.unwrap();
handle.owner.mark_registered();
// Two failed tries with 5s waits each; 20s headroom.
let result =
@@ -750,6 +1008,7 @@ mod tests {
spawn_tcp_server(server_cfg, 88, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
server_handle.owner.mark_registered();
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
@@ -758,18 +1017,23 @@ mod tests {
target_host: "127.0.0.1".into(),
target_port: port,
kiss_framing: false,
i2p_tunneled: false,
connect_timeout_secs: 5,
max_reconnect_tries: Some(1),
mode: InterfaceMode::Full,
fixed_mtu: None,
tunnel_identity: None,
};
let client_handle = spawn_tcp_client(client_cfg, 321, transport_tx.clone(), None)
let client_handle = spawn_tcp_client(client_cfg, 321, transport_tx.clone())
.await
.unwrap();
client_handle.owner.mark_registered();
let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for accepted handle")
.expect("handle channel closed");
accepted.owner.mark_registered();
let server_side_client_id = accepted.id;
// Abort client-side tasks; server's per-client reader sees EOF and exits.
@@ -781,7 +1045,9 @@ mod tests {
while tokio::time::Instant::now() < deadline {
match tokio::time::timeout(std::time::Duration::from_millis(500), transport_rx.recv())
.await
{
.map(|message| {
message.map(|event| crate::traits::test_event_for_handle(event, &accepted))
}) {
Ok(Some(TransportMessage::DeregisterInterface { id }))
if id == server_side_client_id =>
{
+239 -51
View File
@@ -6,8 +6,10 @@ use tokio::sync::mpsc;
pub type InterfaceId = u64;
/// Handle returned by every `spawn_*`: write channel, status flag, and read task.
/// Common transport handle: write channel, status flag, and read task.
pub struct InterfaceHandle {
pub owner: rns_transport::messages::InterfaceOwner,
pub packet_capacity: rns_transport::messages::InterfacePacketCapacity,
pub id: InterfaceId,
/// Parent interface for dynamically spawned children such as accepted TCP,
/// Backbone or I2P peers.
@@ -20,17 +22,96 @@ pub struct InterfaceHandle {
pub online: Arc<AtomicBool>,
pub rxb: Option<Arc<AtomicU64>>,
pub txb: Option<Arc<AtomicU64>>,
/// Optional live aggregate inspection source carried into the transport actor.
pub inspection: Option<rns_transport::messages::InterfaceInspectionSource>,
pub tx: mpsc::Sender<Bytes>,
pub read_task: tokio::task::JoinHandle<()>,
}
/// Optional per-interface IFAC (Interface Authentication Code) configuration.
pub struct IfacConfig {
pub ifac_key: [u8; 64],
pub ifac_size: usize,
/// Deliver a dynamically accepted interface to its owner.
///
/// A failed handoff returns the handle to this producer. The producer must
/// finish disposing of the exact child it created rather than detaching its
/// read task when the receiving runtime has gone away.
pub(crate) async fn handoff_accepted_interface(
handle_tx: &mpsc::Sender<InterfaceHandle>,
handle: InterfaceHandle,
) -> Result<(), ()> {
match handle_tx.send(handle).await {
Ok(()) => Ok(()),
Err(mpsc::error::SendError(handle)) => {
handle
.online
.store(false, std::sync::atomic::Ordering::SeqCst);
handle.read_task.abort();
let _ = handle.read_task.await;
Err(())
}
}
}
/// Interface operating mode. Byte values are on-wire constants.
/// The transport identity a client signs its tunnel syntheses with (Python
/// `Transport.identity`). 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")
.field(&hex::encode(self.0.hash))
.finish()
}
}
/// A host as Python's interface `str()` renders it: IPv6 in brackets.
pub(crate) fn python_host(host: &str) -> std::borrow::Cow<'_, str> {
if host.contains(':') {
format!("[{host}]").into()
} else {
host.into()
}
}
/// Start a client connection as Python does: traffic queued during an outage
/// is dropped (TCPInterface.py:314-315), then the connection's synthesis is
/// queued, and only then does the interface report online.
pub(crate) async fn open_client_connection(
outbound: &tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
after_outage: bool,
transport_tx: &rns_transport::messages::InterfaceTransportSender,
synthesis: Option<Bytes>,
online: &AtomicBool,
) {
if after_outage {
let mut queued = outbound.lock().await;
while queued.try_recv().is_ok() {}
}
if let Some(raw_packet) = synthesis {
let _ = transport_tx
.send(
rns_transport::messages::TransportMessage::SynthesizeTunnel {
interface_id: transport_tx.interface_id(),
raw_packet,
},
)
.await;
}
online.store(true, std::sync::atomic::Ordering::SeqCst);
}
/// Interface operating mode. Numeric values match Reticulum interface mode constants.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
#[derive(Default)]
@@ -42,6 +123,8 @@ pub enum InterfaceMode {
Roaming = 0x04,
Boundary = 0x05,
Gateway = 0x06,
/// Python 1.3.8 `MODE_INTERNAL` (Interface.py:51) — local/shared-instance interfaces.
Internal = 0x07,
}
pub const MODE_FULL: InterfaceMode = InterfaceMode::Full;
@@ -57,6 +140,7 @@ pub const DISCOVER_PATHS_FOR: &[InterfaceMode] = &[
InterfaceMode::AccessPoint,
InterfaceMode::Gateway,
InterfaceMode::Roaming,
InterfaceMode::Internal,
];
impl InterfaceMode {
@@ -68,6 +152,7 @@ impl InterfaceMode {
0x04 => Some(Self::Roaming),
0x05 => Some(Self::Boundary),
0x06 => Some(Self::Gateway),
0x07 => Some(Self::Internal),
_ => None,
}
}
@@ -82,51 +167,8 @@ pub struct InterfaceDirection {
pub repeat: bool,
}
/// Interface statistics.
#[derive(Debug, Clone, Default)]
pub struct InterfaceStats {
pub rx_bytes: u64,
pub tx_bytes: u64,
pub rx_packets: u64,
pub tx_packets: u64,
pub online: bool,
pub bitrate: u64,
pub mtu: u32,
}
/// Base trait for all network interfaces.
pub trait Interface: Send + Sync {
fn process_incoming(&self, data: &[u8]);
fn process_outgoing(&self, data: &[u8]) -> Result<(), InterfaceError>;
fn get_stats(&self) -> InterfaceStats;
fn detach(&mut self);
fn name(&self) -> &str;
fn mode(&self) -> InterfaceMode;
/// Interface bitrate in bits/sec.
fn bitrate(&self) -> u64;
fn mtu(&self) -> u32 {
rns_wire::constants::MTU as u32
}
fn online(&self) -> bool;
/// 16-byte interface identifier: truncated SHA-256 of the interface name.
fn get_hash(&self) -> [u8; 16] {
let full = rns_crypto::sha::full_hash(self.name().as_bytes());
let mut h = [0u8; 16];
h.copy_from_slice(&full[..16]);
h
}
}
/// Select an MTU for the given bitrate; `None` below 62.5 kbps minimum.
/// Select an MTU for the given bitrate in bits per second. Returns `None`
/// for rates at or below 62,500 bps.
pub fn optimise_mtu(bitrate: u64) -> Option<u32> {
if bitrate >= 1_000_000_000 {
Some(524_288)
@@ -203,9 +245,61 @@ pub enum InterfaceError {
Io(#[from] std::io::Error),
}
#[cfg(test)]
pub(crate) fn test_registered_sender(
id: rns_transport::messages::InterfaceId,
tx: tokio::sync::mpsc::Sender<rns_transport::messages::TransportMessage>,
) -> rns_transport::messages::InterfaceTransportSender {
let sender = rns_transport::messages::InterfaceTransportSender::new(id, tx);
sender.owner().mark_registered();
sender
}
#[cfg(test)]
pub(crate) fn test_event_body(
message: rns_transport::messages::TransportMessage,
) -> rns_transport::messages::TransportMessage {
match message {
rns_transport::messages::TransportMessage::InterfaceEvent { message, .. } => *message,
message => message,
}
}
#[cfg(test)]
pub(crate) fn test_event_for_handle(
message: rns_transport::messages::TransportMessage,
handle: &InterfaceHandle,
) -> rns_transport::messages::TransportMessage {
match message {
rns_transport::messages::TransportMessage::InterfaceEvent {
interface_id,
owner,
message,
} => {
assert_eq!(interface_id, handle.id);
assert_eq!(owner, handle.owner);
*message
}
other => panic!("expected registration-bound interface event, got {other:?}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::Ordering;
struct TaskExitGuard {
exited: Option<tokio::sync::oneshot::Sender<()>>,
}
impl Drop for TaskExitGuard {
fn drop(&mut self) {
if let Some(exited) = self.exited.take() {
let _ = exited.send(());
}
}
}
#[test]
fn test_optimise_mtu() {
@@ -224,6 +318,7 @@ mod tests {
assert_eq!(InterfaceMode::Roaming as u8, 0x04);
assert_eq!(InterfaceMode::Boundary as u8, 0x05);
assert_eq!(InterfaceMode::Gateway as u8, 0x06);
assert_eq!(InterfaceMode::Internal as u8, 0x07);
}
#[test]
@@ -234,7 +329,9 @@ mod tests {
Some(InterfaceMode::PointToPoint)
);
assert_eq!(InterfaceMode::from_u8(0x06), Some(InterfaceMode::Gateway));
assert_eq!(InterfaceMode::from_u8(0x07), Some(InterfaceMode::Internal));
assert_eq!(InterfaceMode::from_u8(0x00), None);
assert_eq!(InterfaceMode::from_u8(0x08), None);
assert_eq!(InterfaceMode::from_u8(0xFF), None);
}
@@ -249,6 +346,7 @@ mod tests {
assert!(DISCOVER_PATHS_FOR.contains(&InterfaceMode::AccessPoint));
assert!(DISCOVER_PATHS_FOR.contains(&InterfaceMode::Gateway));
assert!(DISCOVER_PATHS_FOR.contains(&InterfaceMode::Roaming));
assert!(DISCOVER_PATHS_FOR.contains(&InterfaceMode::Internal));
assert!(!DISCOVER_PATHS_FOR.contains(&InterfaceMode::Full));
}
@@ -281,4 +379,94 @@ mod tests {
assert_eq!(EC_PR_FREQ, 5.0);
const { assert!(!EGRESS_CONTROL) };
}
#[tokio::test]
async fn rejected_accepted_interface_is_stopped_and_disposed() {
let (handle_tx, handle_rx) = mpsc::channel(1);
drop(handle_rx);
let online = Arc::new(AtomicBool::new(true));
let (interface_tx, mut interface_rx) = mpsc::channel(1);
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
let (exited_tx, exited_rx) = tokio::sync::oneshot::channel();
let read_task = tokio::spawn(async move {
let _exit_guard = TaskExitGuard {
exited: Some(exited_tx),
};
let _ = started_tx.send(());
std::future::pending::<()>().await;
});
started_rx.await.expect("read task should start");
let handle = InterfaceHandle {
owner: rns_transport::messages::InterfaceOwner::new(),
packet_capacity: rns_transport::messages::InterfacePacketCapacity::base(1),
id: 1,
parent_id: Some(0),
name: "rejected-child".to_string(),
mode: InterfaceMode::Full,
direction: InterfaceDirection::default(),
bitrate: 1,
mtu: 1,
online: Arc::clone(&online),
rxb: None,
txb: None,
inspection: None,
tx: interface_tx,
read_task,
};
assert_eq!(
handoff_accepted_interface(&handle_tx, handle).await,
Err(())
);
assert!(!online.load(Ordering::SeqCst));
exited_rx
.await
.expect("helper should await exact read-task termination");
assert_eq!(
interface_rx.recv().await,
None,
"rejected handle resources should be dropped"
);
}
#[tokio::test]
async fn accepted_interface_handoff_preserves_live_handle() {
let (handle_tx, mut handle_rx) = mpsc::channel(1);
let online = Arc::new(AtomicBool::new(true));
let (interface_tx, _interface_rx) = mpsc::channel(1);
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
let read_task = tokio::spawn(async move {
let _ = started_tx.send(());
std::future::pending::<()>().await;
});
started_rx.await.expect("read task should start");
let handle = InterfaceHandle {
owner: rns_transport::messages::InterfaceOwner::new(),
packet_capacity: rns_transport::messages::InterfacePacketCapacity::base(1),
id: 2,
parent_id: Some(0),
name: "accepted-child".to_string(),
mode: InterfaceMode::Full,
direction: InterfaceDirection::default(),
bitrate: 1,
mtu: 1,
online: Arc::clone(&online),
rxb: None,
txb: None,
inspection: None,
tx: interface_tx,
read_task,
};
assert_eq!(handoff_accepted_interface(&handle_tx, handle).await, Ok(()));
let delivered = handle_rx.recv().await.expect("handle should be delivered");
assert!(online.load(Ordering::SeqCst));
assert!(!delivered.read_task.is_finished());
delivered.read_task.abort();
let _ = delivered.read_task.await;
}
}
+67 -4
View File
@@ -1,3 +1,4 @@
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -54,7 +55,30 @@ pub async fn spawn_udp_interface(
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let listen_ip = config.listen_ip.as_deref().unwrap_or("0.0.0.0");
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
// Python UDPInterface `device =`: fill unset listen/forward IPs with the
// NIC's IPv4 broadcast address; a device that can't be resolved is a
// config error, not a silent fallback to wildcard.
let mut listen_ip_cfg = config.listen_ip.clone();
let mut forward_ip_cfg = config.forward_ip.clone();
if let Some(device) = config.device.as_deref()
&& (listen_ip_cfg.is_none() || forward_ip_cfg.is_none())
{
let bcast = crate::socket_tuning::iface_broadcast_for(device).ok_or_else(|| {
crate::traits::InterfaceError::SendFailed(format!(
"UDP device '{device}' not found or has no IPv4 broadcast address"
))
})?;
if listen_ip_cfg.is_none() {
listen_ip_cfg = Some(bcast.to_string());
}
if forward_ip_cfg.is_none() {
forward_ip_cfg = Some(bcast.to_string());
}
}
let listen_ip = listen_ip_cfg.as_deref().unwrap_or("0.0.0.0");
let listen_port = config.listen_port.unwrap_or(0);
let bind_addr = format!("{}:{}", listen_ip, listen_port);
let socket = Arc::new(UdpSocket::bind(&bind_addr).await?);
@@ -73,7 +97,7 @@ pub async fn spawn_udp_interface(
let task_rxb = shared_rxb.clone();
let task_txb = shared_txb.clone();
let forward_addr: Option<SocketAddr> = match (&config.forward_ip, config.forward_port) {
let forward_addr: Option<SocketAddr> = match (&forward_ip_cfg, config.forward_port) {
(Some(ip), Some(port)) => {
let addr_str = format!("{}:{}", ip, port);
match addr_str.parse() {
@@ -145,6 +169,8 @@ pub async fn spawn_udp_interface(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 1064, false),
parent_id: None,
name,
mode,
@@ -159,6 +185,7 @@ pub async fn spawn_udp_interface(
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: None,
tx,
read_task,
})
@@ -185,6 +212,39 @@ mod tests {
assert_eq!(HW_MTU, 1064);
}
/// T1-11: `device =` was parsed then silently ignored. A device that
/// cannot be resolved must now fail the spawn with a clear error.
#[tokio::test]
async fn test_udp_device_unresolvable_errors() {
let (transport_tx, _rx) = mpsc::channel::<TransportMessage>(8);
let mut cfg = UdpInterfaceConfig::new("udp-dev");
cfg.device = Some("definitely-not-a-real-interface-zzz".to_string());
let err = match spawn_udp_interface(cfg, 1, transport_tx).await {
Err(e) => e,
Ok(_) => panic!("unresolvable device must error"),
};
assert!(
err.to_string()
.contains("definitely-not-a-real-interface-zzz")
);
}
/// Explicit listen/forward IPs take precedence — the device is not
/// resolved at all, so the spawn succeeds regardless of the NIC name.
#[tokio::test]
async fn test_udp_device_ignored_when_ips_explicit() {
let (transport_tx, _rx) = mpsc::channel::<TransportMessage>(8);
let mut cfg = UdpInterfaceConfig::new("udp-dev-explicit")
.listen("127.0.0.1", 0)
.forward("127.0.0.1", 19999);
cfg.device = Some("definitely-not-a-real-interface-zzz".to_string());
let handle = spawn_udp_interface(cfg, 2, transport_tx)
.await
.expect("explicit IPs bypass device resolution");
handle.owner.mark_registered();
handle.read_task.abort();
}
#[test]
fn test_udp_config_defaults() {
let cfg = UdpInterfaceConfig::new("udp0");
@@ -224,6 +284,7 @@ mod tests {
let handle_a = spawn_udp_interface(cfg_a, 10, transport_tx.clone())
.await
.unwrap();
handle_a.owner.mark_registered();
// Reserve two free ports via bind-drop; handle doesn't expose its addr.
let sock_tmp1 = UdpSocket::bind("127.0.0.1:0").await.unwrap();
@@ -244,9 +305,11 @@ mod tests {
let handle_a = spawn_udp_interface(cfg_a, 10, transport_tx.clone())
.await
.unwrap();
handle_a.owner.mark_registered();
let handle_b = spawn_udp_interface(cfg_b, 20, transport_tx.clone())
.await
.unwrap();
handle_b.owner.mark_registered();
// A → B's listen port; inbound carries B's interface_id (20).
let payload = Bytes::from_static(b"udp test data");
@@ -257,7 +320,7 @@ mod tests {
.expect("timeout")
.expect("channel closed");
match msg {
match crate::traits::test_event_for_handle(msg, &handle_b) {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, payload);
assert_eq!(pkt.interface_id, 20);
@@ -273,7 +336,7 @@ mod tests {
.expect("timeout")
.expect("channel closed");
match msg2 {
match crate::traits::test_event_for_handle(msg2, &handle_a) {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, reply);
assert_eq!(pkt.interface_id, 10);
+26 -5
View File
@@ -1,12 +1,13 @@
//! Weave switching fabric — protocol primitives only.
//! Weave switching-fabric codecs and constants.
//!
//! Wire format (WDCL inside HDLC):
//! ```text
//! [HDLC_FLAG] [escaped WDCL] [HDLC_FLAG]
//! WDCL = [ADDR u32][TYPE u8][PAYLOAD…] ADDR 0xFFFFFFFF = broadcast
//! WDCL = [ADDR:4 bytes][TYPE:1 byte][PAYLOAD...]
//! ADDR 0xFFFFFFFF = broadcast
//! ```
//! Discovery: Ed25519 challenge-response over WDCL_T_DISCOVER / WDCL_T_CONNECT.
//! Runtime spawn (serial I/O, peer mgmt) not yet wired up.
//! This module provides frame and log codecs plus configuration types. It
//! has no serial runtime, discovery handshake, or signature-verification path.
use crate::traits::InterfaceMode;
@@ -58,6 +59,8 @@ pub const CMD_REMOTE_INPUT: u16 = 0x0A01;
pub const EVT_MSG: u16 = 0x0000;
pub const EVT_SYSTEM_BOOT: u16 = 0x0001;
pub const EVT_CORE_INIT: u16 = 0x0002;
// "Board hardware initialization" (1.3.8 WeaveInterface.py:342, newer firmware boot event)
pub const EVT_BOARD_INIT: u16 = 0x0003;
// Driver events (0x1xxx)
pub const EVT_DRV_UART_INIT: u16 = 0x1000;
@@ -112,6 +115,7 @@ pub const EVT_STAT_UPTIME: u16 = 0xE001;
pub const EVT_STAT_TIMEBASE: u16 = 0xE002;
pub const EVT_STAT_CPU: u16 = 0xE003;
pub const EVT_STAT_TASK_CPU: u16 = 0xE004;
// EVT_STAT_MEMORY data = [free u32 BE][total u32 BE] (1.3.8 WeaveInterface.py:760-761)
pub const EVT_STAT_MEMORY: u16 = 0xE005;
pub const EVT_STAT_STORAGE: u16 = 0xE006;
@@ -333,7 +337,6 @@ mod tests {
#[test]
fn test_weave_constants() {
assert_eq!(HW_MTU, 1024);
const { assert!(FIXED_MTU) };
assert_eq!(PEERING_TIMEOUT, 20.0);
assert_eq!(BITRATE_GUESS, 250_000);
assert_eq!(DEFAULT_IFAC_SIZE, 16);
@@ -442,6 +445,24 @@ mod tests {
assert_eq!(frame.data, b"ok");
}
#[test]
fn test_boot_event_codes() {
assert_eq!(EVT_MSG, 0x0000);
assert_eq!(EVT_SYSTEM_BOOT, 0x0001);
assert_eq!(EVT_CORE_INIT, 0x0002);
assert_eq!(EVT_BOARD_INIT, 0x0003);
}
#[test]
fn test_parse_log_frame_board_init() {
// flags=0, ts=42ms, level=NOTICE, event=EVT_BOARD_INIT, no data
let payload = [0x00, 0x00, 0x00, 0x00, 0x2A, 0x04, 0x00, 0x03];
let frame = parse_log_frame(&payload).unwrap();
assert_eq!(frame.timestamp_ms, 42);
assert_eq!(frame.event, EVT_BOARD_INIT);
assert!(frame.data.is_empty());
}
#[test]
fn test_parse_log_frame_too_short() {
assert!(parse_log_frame(&[0; 7]).is_none());
@@ -0,0 +1,212 @@
//! A SAM session's private key, read from its key file or returned by the SAM
//! bridge, must not survive in freed heap memory.
#[path = "../../rns-crypto/tests/residue/mod.rs"]
mod residue;
use std::io::{BufRead, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use residue::{assert_no_residue, freed_by, pseudo_random, serial};
use rns_interface::i2p::{I2PClientConfig, I2PServerConfig, spawn_i2p_client, spawn_i2p_server};
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-~";
/// A SAM private key: a destination of 384 key bytes and an Ed25519 key
/// certificate, then 256 private and 32 signing-key bytes. Returns the key's
/// bytes and its I2P base64 text.
fn sam_private_key(seed: u64) -> (Vec<u8>, String) {
let mut key = pseudo_random::<384>(seed).to_vec();
key.extend_from_slice(&[5, 0, 4, 0, 7, 0, 0]);
key.extend_from_slice(&pseudo_random::<288>(seed + 1));
let mut text = String::new();
for chunk in key.chunks(3) {
let bits = chunk.iter().enumerate().fold(0u32, |bits, (n, byte)| {
bits | u32::from(*byte) << (16 - 8 * n)
});
for n in 0..=chunk.len() {
text.push(char::from(ALPHABET[(bits >> (18 - 6 * n)) as usize & 63]));
}
text.extend(std::iter::repeat_n('=', 3 - chunk.len()));
}
(key, text)
}
/// A SAM bridge on its own threads, so none of its frees are recorded. A
/// session keeps the key it asks for, a transient one gets `transient`, and a
/// STREAM CONNECT succeeds; every socket then stays open.
fn sam_bridge(transient: String) -> u16 {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
std::thread::spawn(move || {
for socket in listener.incoming() {
let Ok(socket) = socket else { return };
let transient = transient.clone();
std::thread::spawn(move || serve(socket, &transient));
}
});
port
}
fn serve(mut socket: TcpStream, transient: &str) {
let mut reader = BufReader::new(socket.try_clone().unwrap());
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
return;
}
let _ = socket.write_all(b"HELLO REPLY RESULT=OK VERSION=3.1\n");
line.clear();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
return;
}
if line.starts_with("SESSION CREATE") {
let destination = match line
.split_whitespace()
.find_map(|token| token.strip_prefix("DESTINATION="))
{
Some("TRANSIENT") | None => transient,
Some(key) => key,
};
let _ = socket
.write_all(format!("SESSION STATUS RESULT=OK DESTINATION={destination}\n").as_bytes());
} else if line.starts_with("STREAM CONNECT") {
let _ = socket.write_all(b"STREAM STATUS RESULT=OK\n");
}
let mut rest = Vec::new();
let _ = std::io::Read::read_to_end(&mut reader, &mut rest);
}
/// Run `body` on a current-thread runtime inside the check, then drop the
/// runtime there too, so every task's frees are recorded.
fn checked(body: impl std::future::Future<Output = ()>) -> residue::Freed {
let ((), freed) = freed_by(|| {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(body);
drop(runtime);
});
freed
}
struct TempDir(PathBuf);
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn temp_dir(label: &str) -> TempDir {
let path = std::env::temp_dir().join(format!("rns-i2p-residue-{label}-{}", std::process::id()));
std::fs::create_dir_all(&path).unwrap();
TempDir(path)
}
async fn run_server(sam_port: u16, key_path: PathBuf) {
let (b32_tx, mut b32_rx) = tokio::sync::watch::channel(None);
let mut config = I2PServerConfig::new("residue");
config.sam_host = "127.0.0.1".into();
config.sam_port = sam_port;
config.key_path = Some(key_path);
config.b32 = Some(b32_tx);
let (transport_tx, _transport_rx) = tokio::sync::mpsc::channel(16);
let (handle_tx, _handle_rx) = tokio::sync::mpsc::channel(16);
let _handle = spawn_i2p_server(
config,
1,
Arc::new(AtomicU64::new(2)),
transport_tx,
handle_tx,
)
.await
.unwrap();
tokio::time::timeout(Duration::from_secs(10), b32_rx.wait_for(Option::is_some))
.await
.expect("session created")
.unwrap();
// Let the server reach its STREAM ACCEPT.
tokio::time::sleep(Duration::from_millis(100)).await;
}
#[test]
fn i2p_server_with_a_stored_key_frees_no_private_key() {
let _serial = serial();
let (key, text) = sam_private_key(10);
let sam_port = sam_bridge(sam_private_key(11).1);
let dir = temp_dir("stored");
let key_path = dir.0.join("i2p.key");
std::fs::write(&key_path, format!("{text}\n")).unwrap();
let freed = checked(run_server(sam_port, key_path));
assert_no_residue(
&freed,
&[("private key text", text.as_bytes()), ("private key", &key)],
);
}
#[test]
fn i2p_server_storing_a_new_key_frees_no_private_key() {
let _serial = serial();
let (key, text) = sam_private_key(20);
let sam_port = sam_bridge(text.clone());
let dir = temp_dir("new");
let key_path = dir.0.join("i2p.key");
let freed = checked(run_server(sam_port, key_path.clone()));
assert_eq!(std::fs::read_to_string(&key_path).unwrap(), text);
assert_no_residue(
&freed,
&[("private key text", text.as_bytes()), ("private key", &key)],
);
}
#[test]
fn i2p_client_session_frees_no_private_key() {
let _serial = serial();
let (key, text) = sam_private_key(30);
let sam_port = sam_bridge(text.clone());
let peer = sam_private_key(40).1;
let freed = checked(async move {
let mut config = I2PClientConfig::new("residue", &peer[..516]);
config.sam_host = "127.0.0.1".into();
config.sam_port = sam_port;
let (transport_tx, mut transport_rx) = tokio::sync::mpsc::channel(16);
let handle = spawn_i2p_client(config, 1, transport_tx).await.unwrap();
tokio::time::timeout(Duration::from_secs(10), async {
while !handle.online.load(Ordering::SeqCst) {
tokio::select! {
_ = transport_rx.recv() => {}
_ = tokio::time::sleep(Duration::from_millis(10)) => {}
}
}
})
.await
.expect("client online");
});
assert_no_residue(
&freed,
&[("private key text", text.as_bytes()), ("private key", &key)],
);
}
#[test]
fn i2p_server_debug_output_hides_its_key() {
let (_, text) = sam_private_key(50);
let mut config = I2PServerConfig::new("residue");
config.keyfile = Some(text.clone());
let shown = format!("{config:?}");
assert!(!shown.contains(&text[..32]), "{shown}");
assert!(shown.contains("residue"), "{shown}");
}
+9 -1
View File
@@ -1,9 +1,11 @@
[package]
name = "rns-link"
description = "Link layer and encrypted channel for Reticulum"
publish = false
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
license-file.workspace = true
[features]
default = ["std"]
@@ -20,5 +22,11 @@ rand = { workspace = true }
tracing = { workspace = true }
hex = { workspace = true }
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_System_Performance"] }
[dev-dependencies]
proptest = { workspace = true }
+323
View File
@@ -0,0 +1,323 @@
//! A monotonic clock for deadlines that account for system suspension.
//!
//! Uses `CLOCK_BOOTTIME` on Linux and Android, `CLOCK_MONOTONIC_RAW` on Apple
//! platforms, and the performance counter on Windows. Other targets fall back
//! to `std::time::Instant` from the first reading, inheriting that platform
//! clock's suspend behavior.
//!
//! This type does not schedule a wakeup or change the clock used by an async
//! timer. Check deadlines against [`ContinuousInstant::now`] on a regular
//! tick and after resuming. Link and request timing elsewhere in this crate
//! still uses `std::time::Instant`.
use std::ops::{Add, AddAssign, Sub, SubAssign};
use std::time::Duration;
/// A reading of this module's clock, in signed nanoseconds from the
/// platform's origin, usually boot.
///
/// Readings are process-local: never persist one or send it to another
/// process, which is what wall time is for. They do not convert to or from
/// `std::time::Instant`, so the two clocks never mix.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ContinuousInstant(i64);
impl ContinuousInstant {
/// The current reading.
///
/// # Panics
///
/// If the platform clock fails, as `std::time::Instant::now` does.
pub fn now() -> Self {
Self(backend::now_nanos())
}
/// The time from `earlier` to `self`, or zero if `earlier` is later.
pub fn duration_since(self, earlier: Self) -> Duration {
self.saturating_duration_since(earlier)
}
/// The time from `earlier` to `self`, or zero if `earlier` is later.
pub fn saturating_duration_since(self, earlier: Self) -> Duration {
self.checked_duration_since(earlier).unwrap_or_default()
}
/// The time from `earlier` to `self`, or `None` if `earlier` is later.
pub fn checked_duration_since(self, earlier: Self) -> Option<Duration> {
let nanos = i128::from(self.0) - i128::from(earlier.0);
u64::try_from(nanos).ok().map(Duration::from_nanos)
}
/// The time since this reading, with the suspend behavior of the selected
/// backend described at module level.
pub fn elapsed(self) -> Duration {
Self::now().duration_since(self)
}
/// `self + duration`, or `None` beyond the clock's range, about 292 years
/// either side of its origin.
pub fn checked_add(self, duration: Duration) -> Option<Self> {
Self::from_nanos(i128::from(self.0) + nanos(duration)?)
}
/// `self - duration`, or `None` beyond the clock's range, about 292 years
/// either side of its origin.
pub fn checked_sub(self, duration: Duration) -> Option<Self> {
Self::from_nanos(i128::from(self.0) - nanos(duration)?)
}
fn from_nanos(nanos: i128) -> Option<Self> {
i64::try_from(nanos).ok().map(Self)
}
}
fn nanos(duration: Duration) -> Option<i128> {
i128::try_from(duration.as_nanos()).ok()
}
/// # Panics
///
/// Beyond the clock's range, as `std::time::Instant` does.
impl Add<Duration> for ContinuousInstant {
type Output = Self;
fn add(self, duration: Duration) -> Self {
self.checked_add(duration)
.expect("overflow when adding duration to instant")
}
}
impl AddAssign<Duration> for ContinuousInstant {
fn add_assign(&mut self, duration: Duration) {
*self = *self + duration;
}
}
/// # Panics
///
/// Beyond the clock's range, as `std::time::Instant` does.
impl Sub<Duration> for ContinuousInstant {
type Output = Self;
fn sub(self, duration: Duration) -> Self {
self.checked_sub(duration)
.expect("overflow when subtracting duration from instant")
}
}
impl SubAssign<Duration> for ContinuousInstant {
fn sub_assign(&mut self, duration: Duration) {
*self = *self - duration;
}
}
/// The time from `earlier` to `self`, or zero if `earlier` is later.
impl Sub for ContinuousInstant {
type Output = Duration;
fn sub(self, earlier: Self) -> Duration {
self.duration_since(earlier)
}
}
#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
mod backend {
#[cfg(any(target_os = "linux", target_os = "android"))]
const CLOCK: libc::clockid_t = libc::CLOCK_BOOTTIME;
#[cfg(target_vendor = "apple")]
const CLOCK: libc::clockid_t = libc::CLOCK_MONOTONIC_RAW;
// `time_t` and `c_long` are 32 bits wide on some of these targets.
#[allow(clippy::useless_conversion)]
pub(super) fn now_nanos() -> i64 {
let mut now = std::mem::MaybeUninit::<libc::timespec>::uninit();
// SAFETY: `now` is valid for writes of a timespec for the whole call.
let result = unsafe { libc::clock_gettime(CLOCK, now.as_mut_ptr()) };
assert_eq!(
result,
0,
"clock_gettime failed: {}",
std::io::Error::last_os_error()
);
// SAFETY: a successful `clock_gettime` filled in `now`.
let now = unsafe { now.assume_init() };
i64::from(now.tv_sec) * 1_000_000_000 + i64::from(now.tv_nsec)
}
}
#[cfg(windows)]
mod backend {
use std::sync::OnceLock;
use windows_sys::Win32::System::Performance::{
QueryPerformanceCounter, QueryPerformanceFrequency,
};
fn frequency() -> i64 {
static FREQUENCY: OnceLock<i64> = OnceLock::new();
*FREQUENCY.get_or_init(|| {
let mut frequency = 0;
// SAFETY: `frequency` is a valid, writable i64 for the whole call.
let succeeded = unsafe { QueryPerformanceFrequency(&mut frequency) } != 0;
assert!(
succeeded && frequency > 0,
"QueryPerformanceFrequency failed"
);
frequency
})
}
pub(super) fn now_nanos() -> i64 {
let mut counter = 0;
// SAFETY: `counter` is a valid, writable i64 for the whole call.
let succeeded = unsafe { QueryPerformanceCounter(&mut counter) } != 0;
assert!(succeeded, "QueryPerformanceCounter failed");
let nanos = i128::from(counter) * 1_000_000_000 / i128::from(frequency());
i64::try_from(nanos).expect("performance counter beyond the clock's range")
}
}
#[cfg(not(any(
target_os = "linux",
target_os = "android",
target_vendor = "apple",
windows
)))]
mod backend {
use std::sync::OnceLock;
use std::time::Instant;
pub(super) fn now_nanos() -> i64 {
static ORIGIN: OnceLock<Instant> = OnceLock::new();
let origin = *ORIGIN.get_or_init(Instant::now);
i64::try_from(origin.elapsed().as_nanos()).expect("clock beyond its range")
}
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
#[test]
fn readings_never_go_backwards() {
let mut last = ContinuousInstant::now();
for _ in 0..10_000 {
let now = ContinuousInstant::now();
assert!(now >= last, "{now:?} after {last:?}");
last = now;
}
}
/// While the system is awake the clock keeps `Instant`'s rate, which
/// catches a backend's unit or scaling mistake. Each reading is bracketed
/// by two `Instant` readings, so a preemption widens the bounds instead of
/// failing the check.
#[test]
fn it_runs_at_instants_rate_while_awake() {
let bracketed = || {
let before = std::time::Instant::now();
let reading = ContinuousInstant::now();
(before, reading, std::time::Instant::now())
};
let (start_before, start, start_after) = bracketed();
std::thread::sleep(Duration::from_millis(200));
let (end_before, end, end_after) = bracketed();
let advance = (end - start).as_secs_f64();
let shortest = end_before.duration_since(start_after).as_secs_f64();
let longest = end_after.duration_since(start_before).as_secs_f64();
assert!(
(shortest * 0.95..=longest * 1.05).contains(&advance),
"advanced {advance}s while Instant advanced {shortest}s to {longest}s"
);
}
#[test]
fn backdating_never_underflows() {
let now = ContinuousInstant::now();
let century = Duration::from_secs(100 * 365 * 24 * 3600);
let past = now - century;
assert!(past < now);
assert_eq!(now.duration_since(past), century);
let later = ContinuousInstant::now();
assert_eq!(later - past - (later - now), century);
}
#[test]
fn a_later_earlier_reading_saturates() {
let (earlier, later) = (ContinuousInstant(-5), ContinuousInstant(7));
assert_eq!(later - earlier, Duration::from_nanos(12));
assert_eq!(earlier - later, Duration::ZERO);
assert_eq!(earlier.duration_since(later), Duration::ZERO);
assert_eq!(earlier.saturating_duration_since(later), Duration::ZERO);
assert_eq!(earlier.checked_duration_since(later), None);
assert_eq!(later.checked_duration_since(later), Some(Duration::ZERO));
}
#[test]
fn arithmetic_beyond_the_range_is_none() {
let (min, max) = (ContinuousInstant(i64::MIN), ContinuousInstant(i64::MAX));
assert_eq!(max.checked_add(Duration::from_nanos(1)), None);
assert_eq!(min.checked_sub(Duration::from_nanos(1)), None);
assert_eq!(ContinuousInstant(0).checked_add(Duration::MAX), None);
assert_eq!(ContinuousInstant(0).checked_sub(Duration::MAX), None);
assert_eq!(
max.checked_duration_since(min),
Some(Duration::from_nanos(u64::MAX))
);
}
#[test]
#[should_panic(expected = "overflow when adding duration to instant")]
fn adding_beyond_the_range_panics() {
let _ = ContinuousInstant(i64::MAX) + Duration::from_nanos(1);
}
#[test]
#[should_panic(expected = "overflow when subtracting duration from instant")]
fn subtracting_beyond_the_range_panics() {
let _ = ContinuousInstant(i64::MIN) - Duration::from_nanos(1);
}
#[test]
fn assigning_operators_match_the_plain_ones() {
let start = ContinuousInstant(1_000);
let mut moved = start;
moved += Duration::from_nanos(250);
assert_eq!(moved, start + Duration::from_nanos(250));
moved -= Duration::from_nanos(500);
assert_eq!(moved, start - Duration::from_nanos(250));
}
proptest! {
#[test]
fn a_duration_added_is_the_duration_measured(origin in any::<i64>(), nanos in any::<u64>()) {
let start = ContinuousInstant(origin);
let duration = Duration::from_nanos(nanos);
match start.checked_add(duration) {
Some(end) => {
prop_assert_eq!(end - start, duration);
prop_assert_eq!(end.checked_sub(duration), Some(start));
prop_assert_eq!(start.saturating_duration_since(end), Duration::ZERO);
prop_assert_eq!(
start.checked_duration_since(end),
(nanos == 0).then_some(Duration::ZERO)
);
}
None => prop_assert!(i128::from(origin) + i128::from(nanos) > i128::from(i64::MAX)),
}
}
#[test]
fn a_duration_subtracted_is_the_duration_measured(origin in any::<i64>(), nanos in any::<u64>()) {
let end = ContinuousInstant(origin);
let duration = Duration::from_nanos(nanos);
match end.checked_sub(duration) {
Some(start) => {
prop_assert_eq!(end.duration_since(start), duration);
prop_assert_eq!(start.checked_add(duration), Some(end));
}
None => prop_assert!(i128::from(origin) - i128::from(nanos) < i128::from(i64::MIN)),
}
}
}
}
+7 -5
View File
@@ -42,7 +42,7 @@ pub const TRAFFIC_TIMEOUT_FLOOR_MS: u64 = 5;
pub const MODE_AES128_CBC: u8 = 0x00;
/// Default: AES-256-CBC.
pub const MODE_AES256_CBC: u8 = 0x01;
/// Reserved for future AES-256-GCM support.
/// Reserved AES-256-GCM identifier; not accepted by current Link endpoints.
pub const MODE_AES256_GCM: u8 = 0x02;
pub const MODE_OTP_RESERVED: u8 = 0x03;
pub const MODE_PQ_RESERVED_1: u8 = 0x04;
@@ -50,7 +50,8 @@ pub const MODE_PQ_RESERVED_2: u8 = 0x05;
pub const MODE_PQ_RESERVED_3: u8 = 0x06;
pub const MODE_PQ_RESERVED_4: u8 = 0x07;
/// Encryption modes accepted by this implementation; others are advertised-but-refused.
/// Encryption modes accepted by [`crate::link::Link`] endpoints. Other mode
/// identifiers are representable on the wire but rejected by those endpoints.
pub const ENABLED_MODES: &[u8] = &[MODE_AES256_CBC];
pub const DEFAULT_MODE: u8 = MODE_AES256_CBC;
@@ -67,13 +68,14 @@ pub const ACCEPT_ALL: u8 = 0x02;
/// Low 21 bits of the 24-bit MTU signalling value carry the MTU.
pub const MTU_BYTEMASK: u32 = 0x001F_FFFF;
/// Bits 21-23 of the MTU signalling value carry the encryption mode.
/// Mask for mode bits 5–7 of the first signalling byte. In the full 24-bit
/// big-endian signalling value, those are bits 21–23 (mask `0xE00000`).
pub const MODE_BYTEMASK: u32 = 0x00E0;
/// Derived key length for AES-256-CBC: 32 bytes cipher key || 32 bytes HMAC key.
/// Derived key length for AES-256-CBC: 32-byte HMAC key || 32-byte cipher key.
pub const AES256_DERIVED_KEY_LENGTH: usize = 64;
/// Derived key length for AES-128-CBC: 16 bytes cipher key || 16 bytes HMAC key.
/// Derived key length for AES-128-CBC: 16-byte HMAC key || 16-byte cipher key.
pub const AES128_DERIVED_KEY_LENGTH: usize = 32;
/// Seconds of slack granted to a response beyond its nominal transfer time.
+3 -2
View File
@@ -18,8 +18,9 @@ pub fn link_encrypt(keys: &LinkKeys, plaintext: &[u8]) -> Result<Vec<u8>, LinkCr
/// Decrypt a ciphertext frame with the link's session keys.
///
/// Errors are deliberately opaque — padding and HMAC failures are indistinguishable
/// to callers so timing side channels cannot leak which check failed.
/// All token errors map to `DecryptionFailed`, so the error value does not
/// distinguish padding, HMAC, or key-length failure. This error mapping alone
/// is not a guarantee of identical execution time for every invalid input.
pub fn link_decrypt(keys: &LinkKeys, ciphertext: &[u8]) -> Result<Vec<u8>, LinkCryptoError> {
let mut combined_key = Zeroizing::new(Vec::with_capacity(
keys.signing_key.len() + keys.encryption_key.len(),
+47 -9
View File
@@ -49,7 +49,8 @@ impl EphemeralKeys {
/// Link request payload (Message 1: initiator -> destination).
///
/// Wire format: `X25519_pub(32) || Ed25519_pub(32) || signalling(3)` — 67 bytes.
/// Modern wire format: `X25519_pub(32) || Ed25519_pub(32) || signalling(3)`
/// (67 bytes). Parsing also accepts the 64-byte legacy form without signalling.
#[derive(Debug, Clone)]
pub struct LinkRequestData {
pub peer_x25519_pub: [u8; 32],
@@ -69,8 +70,9 @@ impl LinkRequestData {
/// Parse a link request payload.
///
/// Python accepts exactly the legacy 64-byte key payload or the modern
/// 67-byte key payload with signalling. Other lengths are dropped.
/// Accepts exactly the legacy 64-byte key payload or modern 67-byte
/// payload, and validates the signalled MTU domain. It does not authenticate
/// the keys or enforce the endpoint's enabled cipher modes.
pub fn unpack(data: &[u8]) -> Result<Self, HandshakeError> {
if data.len() < ECPUBSIZE {
return Err(HandshakeError::TooShort);
@@ -79,6 +81,7 @@ impl LinkRequestData {
return Err(HandshakeError::InvalidLength(data.len()));
}
rns_wire::link_signalling::parse_request_signalling(data)?;
let mut x25519_pub = [0u8; 32];
x25519_pub.copy_from_slice(&data[0..32]);
@@ -105,7 +108,9 @@ impl LinkRequestData {
///
/// The hashable body is `flags_low_nibble || dest_hash || context || data[..ECPUBSIZE]`
/// — the signalling trailer is intentionally excluded so both sides agree on the same
/// link ID regardless of MTU/mode negotiation.
/// link ID regardless of MTU/mode signalling. The flags are fixed to a SINGLE
/// LINKREQUEST with context NONE. Short payloads are hashed as supplied;
/// validate request shape separately with [`LinkRequestData::unpack`].
pub fn compute_link_id(destination_hash: &[u8; 16], request_data: &[u8]) -> [u8; 16] {
// LinkRequest(0x02) | DestinationType::Single(0x00); context is PacketContext::None.
let flags_low_nibble = 0x02u8;
@@ -122,6 +127,11 @@ pub fn compute_link_id(destination_hash: &[u8; 16], request_data: &[u8]) -> [u8;
}
/// Compute the link ID from a full raw packet (for transport relay paths).
/// The caller supplies a validated packet and its matching header type.
///
/// # Panics
///
/// Panics if `raw` is empty; see [`rns_wire::hash::link_id_from_raw`].
pub fn compute_link_id_from_raw(raw: &[u8], header_type: rns_wire::flags::HeaderType) -> [u8; 16] {
rns_wire::hash::link_id_from_raw(raw, header_type)
}
@@ -131,6 +141,11 @@ pub fn compute_link_id_from_raw(raw: &[u8], header_type: rns_wire::flags::Header
/// Wire format: `signature(64) || X25519_pub(32) || signalling(3)` — 99 bytes.
/// The signature covers `link_id || responder_x25519_pub || identity_ed25519_pub || signalling`
/// under the destination's long-term identity Ed25519 key.
///
/// Parsing also accepts a 96-byte legacy body, but this representation does
/// not preserve trailer absence. Its `pack` and `validate` methods use the
/// modern three-byte trailer. Use [`crate::link::Link::validate_proof`] with
/// the original bytes to validate legacy or modern incoming proofs.
#[derive(Debug, Clone)]
pub struct LinkProofData {
pub signature: [u8; 64],
@@ -208,7 +223,9 @@ impl LinkProofData {
}
/// Parse a proof payload, accepting exactly 96-byte legacy frames or
/// 99-byte frames with signalling.
/// 99-byte frames with signalling. Validates the MTU domain but not the
/// signature or endpoint mode policy. A legacy body receives default
/// signalling in this representation; see [`LinkProofData`].
pub fn unpack(data: &[u8]) -> Result<Self, HandshakeError> {
if data.len() < 96 {
return Err(HandshakeError::TooShort);
@@ -217,6 +234,7 @@ impl LinkProofData {
return Err(HandshakeError::InvalidLength(data.len()));
}
rns_wire::link_signalling::parse_proof_signalling(data)?;
let mut signature = [0u8; 64];
signature.copy_from_slice(&data[0..64]);
@@ -239,7 +257,10 @@ impl LinkProofData {
})
}
/// Verify the proof signature against the destination's identity public key.
/// Verify a modern proof signature, including this representation's trailer.
/// `peer_ed25519_pub` must be the destination identity bytes corresponding
/// to `identity_verify_key`. For an incoming legacy proof, use
/// [`crate::link::Link::validate_proof`] with the original packet payload.
pub fn validate(
&self,
identity_verify_key: &Ed25519PublicKey,
@@ -259,7 +280,9 @@ impl LinkProofData {
}
}
/// Perform the ECDH handshake and derive session keys.
/// Perform ECDH and derive session keys. This primitive does not authenticate
/// a handshake proof or enforce the current endpoint admission policy; see
/// [`LinkKeys::derive`] for its supported modes and input responsibilities.
pub fn perform_handshake(
my_x25519_prv: &X25519PrivateKey,
peer_x25519_pub_bytes: &[u8; 32],
@@ -272,6 +295,8 @@ pub fn perform_handshake(
#[derive(Debug, thiserror::Error)]
pub enum HandshakeError {
#[error(transparent)]
Signalling(#[from] rns_wire::link_signalling::LinkSignallingError),
#[error("handshake data too short")]
TooShort,
#[error("invalid handshake data length: {0}")]
@@ -527,7 +552,7 @@ mod tests {
x25519_pub: [u8; 32],
ed25519_pub: [u8; 32],
mode in 0u8..=7,
mtu in 0u32..=crate::constants::MTU_BYTEMASK,
mtu in prop_oneof![Just(0u32), 500u32..=crate::constants::MTU_BYTEMASK],
) {
let signalling = SignallingData::new(mode, mtu);
// EphemeralKeys is the higher-level wrapper; we pack the
@@ -553,7 +578,7 @@ mod tests {
signature: [u8; 64],
responder_x25519_pub: [u8; 32],
mode in 0u8..=7,
mtu in 0u32..=crate::constants::MTU_BYTEMASK,
mtu in prop_oneof![Just(0u32), 500u32..=crate::constants::MTU_BYTEMASK],
) {
let signalling = SignallingData::new(mode, mtu);
let proof = LinkProofData {
@@ -570,5 +595,18 @@ mod tests {
prop_assert_eq!(unpacked.signalling, signalling);
prop_assert_eq!(unpacked.pack(), packed);
}
/// The representation packer remains permissive, but both handshake
/// parsers reject every nonzero offer below the supported Link floor.
#[test]
fn proptest_handshake_rejects_sub_base_mtu(mode in 0u8..=7, mtu in 1u32..500) {
let signalling = SignallingData::new(mode, mtu).pack();
let mut request = vec![0u8; ECPUBSIZE];
request.extend_from_slice(&signalling);
prop_assert!(LinkRequestData::unpack(&request).is_err());
let mut proof = vec![0u8; 96];
proof.extend_from_slice(&signalling);
prop_assert!(LinkProofData::unpack(&proof).is_err());
}
}
}
+114 -26
View File
@@ -4,7 +4,9 @@ use crate::constants::*;
/// Keepalive timing state for a single link.
///
/// Only the initiator side schedules keepalives; the responder simply echoes them.
/// Only the initiator schedules requests. The responder can suppress a reply
/// when it has sent other traffic within the keepalive interval. The owner
/// records activity and sends any required frames.
#[derive(Debug, Clone)]
pub struct KeepaliveState {
pub keepalive_interval: Duration,
@@ -46,7 +48,8 @@ impl KeepaliveState {
/// Rescale the keepalive interval after a new RTT measurement.
///
/// Interval scales linearly with RTT up to `KEEPALIVE_MAX_RTT`, then saturates.
/// Interval scales linearly with RTT, clamped to `KEEPALIVE_MIN` through
/// `KEEPALIVE_MAX`; it reaches the upper limit at `KEEPALIVE_MAX_RTT`.
/// Jitter is re-rolled so the ±10% spread is relative to the new interval.
pub fn update_from_rtt(&mut self, rtt: Duration) {
let rtt_secs = rtt.as_secs_f64();
@@ -89,6 +92,10 @@ impl KeepaliveState {
/// Whether the initiator should emit a keepalive now (jitter applied).
pub fn should_send_keepalive(&self) -> bool {
self.should_send_keepalive_at(Instant::now())
}
pub(crate) fn should_send_keepalive_at(&self, now: Instant) -> bool {
let jittered = if self.jitter_negative {
self.keepalive_interval
.saturating_sub(self.jitter_offset)
@@ -97,48 +104,75 @@ impl KeepaliveState {
self.keepalive_interval + self.jitter_offset
};
let inbound_elapsed = self.last_inbound.elapsed();
let inbound_elapsed = now.saturating_duration_since(self.last_inbound);
let outbound_elapsed = self
.last_outbound
.or(self.activated_at)
.map(|baseline| now.saturating_duration_since(baseline))
.unwrap_or(inbound_elapsed);
let keepalive_elapsed = self
.last_keepalive_sent
.map(|t| t.elapsed())
.map(|last_keepalive| now.saturating_duration_since(last_keepalive))
.unwrap_or(Duration::MAX);
self.is_initiator && inbound_elapsed >= jittered && keepalive_elapsed >= jittered
self.is_initiator
&& (inbound_elapsed >= jittered || outbound_elapsed >= jittered)
&& keepalive_elapsed >= jittered
}
pub(crate) fn should_respond_to_keepalive_at(&self, now: Instant) -> bool {
!self.is_initiator
&& self
.last_outbound
.map(|last_outbound| {
now.saturating_duration_since(last_outbound) >= self.keepalive_interval
})
.unwrap_or(true)
}
/// Whether the link should transition to STALE.
///
/// Uses the most recent of inbound, proof, or activation as the baseline so a
/// link that just came up isn't immediately flagged stale on a quiet channel.
/// Uses only peer evidence — inbound traffic, proof, or activation — as the
/// baseline. Local outbound traffic cannot prove that the peer remains alive.
pub fn is_stale(&self) -> bool {
self.is_stale_at(Instant::now())
}
pub(crate) fn is_stale_at(&self, now: Instant) -> bool {
let mut latest = self.last_inbound;
if let Some(proof) = self.last_proof {
if proof > latest {
latest = proof;
}
if let Some(proof) = self.last_proof
&& proof > latest
{
latest = proof;
}
if let Some(outbound) = self.last_outbound {
if outbound > latest {
latest = outbound;
}
if let Some(activated) = self.activated_at
&& activated > latest
{
latest = activated;
}
if let Some(activated) = self.activated_at {
if activated > latest {
latest = activated;
}
}
latest.elapsed() >= self.stale_time
now.saturating_duration_since(latest) >= self.stale_time
}
/// How long to wait in STALE before tearing the link down.
pub fn stale_grace_timeout(&self, rtt: Duration) -> Duration {
rtt * KEEPALIVE_TIMEOUT_FACTOR as u32 + Duration::from_secs_f64(STALE_GRACE)
rtt.saturating_mul(KEEPALIVE_TIMEOUT_FACTOR as u32)
.saturating_add(Duration::from_secs_f64(STALE_GRACE))
}
pub fn mark_keepalive_sent(&mut self) {
self.last_keepalive_sent = Some(Instant::now());
}
pub(crate) fn mark_keepalive_sent_at(&mut self, now: Instant) {
self.last_keepalive_sent = Some(now);
}
pub(crate) fn record_keepalive_outbound(&mut self) {
let now = Instant::now();
self.last_outbound = Some(now);
self.last_keepalive_sent = Some(now);
}
pub fn since_inbound(&self) -> Duration {
self.last_inbound.elapsed()
}
@@ -220,6 +254,60 @@ mod tests {
assert!(!ks2.should_send_keepalive());
}
#[test]
fn continuous_inbound_still_schedules_keepalive_when_outbound_is_quiet() {
let now = Instant::now();
let mut state = KeepaliveState::new(true);
state.keepalive_interval = Duration::from_secs(5);
state.jitter_offset = Duration::ZERO;
state.jitter_negative = false;
state.last_inbound = now;
state.last_outbound = None;
state.activated_at = Some(now - Duration::from_secs(6));
state.last_keepalive_sent = Some(now - Duration::from_secs(6));
assert!(state.should_send_keepalive_at(now));
}
#[test]
fn recent_keepalive_suppresses_duplicate_at_exact_tick_time() {
let now = Instant::now();
let mut state = KeepaliveState::new(true);
state.keepalive_interval = Duration::from_secs(5);
state.jitter_offset = Duration::ZERO;
state.jitter_negative = false;
state.last_inbound = now - Duration::from_secs(6);
state.last_outbound = Some(now - Duration::from_secs(6));
state.last_keepalive_sent = Some(now - Duration::from_secs(4));
assert!(!state.should_send_keepalive_at(now));
assert!(state.should_send_keepalive_at(now + Duration::from_secs(1)));
}
#[test]
fn local_outbound_traffic_does_not_mask_a_stale_peer() {
let now = Instant::now();
let mut state = KeepaliveState::new(true);
state.stale_time = Duration::from_secs(5);
state.last_inbound = now - Duration::from_secs(6);
state.last_outbound = Some(now);
state.last_proof = None;
state.activated_at = None;
assert!(state.is_stale_at(now));
}
#[test]
fn responder_suppresses_keepalive_reply_after_recent_outbound() {
let now = Instant::now();
let mut state = KeepaliveState::new(false);
state.keepalive_interval = Duration::from_secs(5);
state.last_outbound = Some(now);
assert!(!state.should_respond_to_keepalive_at(now));
assert!(state.should_respond_to_keepalive_at(now + Duration::from_secs(5)));
}
#[test]
fn test_stale_detection() {
let mut ks = KeepaliveState::new(true);
@@ -235,12 +323,12 @@ mod tests {
#[test]
fn test_jitter_desynchronizes_keepalives() {
let links: Vec<KeepaliveState> = (0..20)
let links: Vec<KeepaliveState> = (0usize..20)
.map(|i| {
let mut ks = KeepaliveState::new(true);
ks.keepalive_interval = Duration::from_secs_f64(KEEPALIVE_MIN);
ks.jitter_offset = Duration::from_millis(500);
ks.jitter_negative = i % 2 == 0;
ks.jitter_negative = i.is_multiple_of(2);
// Push last_inbound just past the interval boundary.
ks.last_inbound = instant_before_now(ks.keepalive_interval);
ks
@@ -249,12 +337,12 @@ mod tests {
let firing: usize = links.iter().filter(|ks| ks.should_send_keepalive()).count();
let links_past: Vec<KeepaliveState> = (0..20)
let links_past: Vec<KeepaliveState> = (0usize..20)
.map(|i| {
let mut ks = KeepaliveState::new(true);
ks.keepalive_interval = Duration::from_secs_f64(KEEPALIVE_MIN);
ks.jitter_offset = Duration::from_millis(500);
ks.jitter_negative = i % 2 == 0;
ks.jitter_negative = i.is_multiple_of(2);
ks.last_inbound = instant_before_now(Duration::from_secs(6));
ks
})
+9 -4
View File
@@ -1,14 +1,15 @@
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
use zeroize::{Zeroize, Zeroizing};
use zeroize::Zeroize;
use crate::constants::{
AES128_DERIVED_KEY_LENGTH, AES256_DERIVED_KEY_LENGTH, MODE_AES128_CBC, MODE_AES256_CBC,
};
/// Derived session keys for a link.
/// Symmetric session keys shared by both directions of a Link. Cloning copies
/// the key material; each owned copy is zeroised when dropped.
#[derive(Clone)]
pub struct LinkKeys {
/// HMAC-SHA256 signing key.
/// HMAC-SHA256 authentication key, distinct from an Ed25519 signing key.
pub signing_key: Vec<u8>,
/// AES encryption key.
pub encryption_key: Vec<u8>,
@@ -20,6 +21,10 @@ impl LinkKeys {
/// Runs `HKDF-SHA256(ECDH(my_prv, peer_pub), salt = link_id)` and splits the
/// output into `signing_key || encryption_key`. Intermediate shared secrets
/// are zeroized as soon as HKDF consumes them.
///
/// This primitive accepts AES-128-CBC and AES-256-CBC; endpoint admission
/// is narrower (see [`crate::constants::ENABLED_MODES`]). It does not
/// authenticate the peer or reject an all-zero X25519 shared secret.
pub fn derive(
my_prv: &X25519PrivateKey,
peer_pub: &X25519PublicKey,
@@ -38,7 +43,7 @@ impl LinkKeys {
rns_crypto::hkdf::hkdf_sha256(derived_key_length, &shared_key, Some(link_id), None)
.map_err(|_| LinkKeyError::HkdfFailed);
shared_key.zeroize();
let derived = Zeroizing::new(derived_result?);
let derived = derived_result?;
let half = derived_key_length / 2;
let signing_key = derived[..half].to_vec();
+5 -2
View File
@@ -1,7 +1,10 @@
//! Encrypted point-to-point Links between two Reticulum destinations.
//! LR/LRPROOF handshake → AES-256 + HMAC-SHA256 session, MTU discovery,
//! keepalives, request/response. Python reference: `RNS/Link.py`.
//! LR/LRPROOF handshake, AES-256-CBC + HMAC-SHA256 sessions, checked MTU
//! signalling, keepalives, and request/response. Current [`link::Link`] endpoints
//! use the 500-byte base MTU; representable signalling offers are a wider domain.
//! The owning runtime sends packets, drives ticks, and dispatches Link callbacks.
pub mod clock;
pub mod constants;
pub mod encryption;
pub mod handshake;
+1461 -296
View File
File diff suppressed because it is too large. Load diff
+6 -39
View File
@@ -1,46 +1,13 @@
use crate::constants::{MODE_BYTEMASK, MTU_BYTEMASK};
/// MTU and encryption-mode signalling packed into 3 bytes (big-endian).
///
/// Wire layout: `[23:21] mode (0..=7)`, `[20:0] mtu (0..=2_097_151)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SignallingData {
pub mode: u8,
pub mtu: u32,
}
impl SignallingData {
pub fn new(mode: u8, mtu: u32) -> Self {
Self {
mode: mode & 0x07,
mtu: mtu & MTU_BYTEMASK,
}
}
/// Pack into 3 big-endian bytes.
pub fn pack(&self) -> [u8; 3] {
let value = (self.mtu & MTU_BYTEMASK) | ((((self.mode as u32) << 5) & MODE_BYTEMASK) << 16);
let bytes = value.to_be_bytes();
// Value fits in 24 bits; drop the high byte of the u32.
[bytes[1], bytes[2], bytes[3]]
}
/// Parse 3 big-endian bytes. Returns `None` if the input is shorter.
pub fn unpack(bytes: &[u8]) -> Option<Self> {
if bytes.len() < 3 {
return None;
}
let value = ((bytes[0] as u32) << 16) | ((bytes[1] as u32) << 8) | (bytes[2] as u32);
let mtu = value & MTU_BYTEMASK;
let mode = ((value >> 21) & 0x07) as u8;
Some(Self { mode, mtu })
}
}
//! Shared dependency-neutral Link signalling representation and checked budget.
pub use rns_wire::link_signalling::{
LinkMtu, LinkSignalling, LinkSignallingError, SignallingData, parse_proof_signalling,
parse_request_signalling,
};
#[cfg(test)]
mod tests {
use super::*;
use crate::constants::{DEFAULT_MODE, MODE_AES256_CBC};
use crate::constants::{DEFAULT_MODE, MODE_AES256_CBC, MTU_BYTEMASK};
#[test]
fn test_pack_unpack_roundtrip() {
Loaded 100 of 284 files, more files were not shown because too many files have changed in this diff. Show more