Compare commits

...
174 Commits
Author SHA1 Message Date
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
DeFiDude 2f077af27b release: bump rsReticulum to 0.9.4 2026-05-24 00:11:36 -06:00
DeFiDude 05e2cdff83 interface: fix clippy hex grouping 2026-05-23 23:56:37 -06:00
DeFiDude 52c670e5fc tools: fix probe discovery and listener shutdown 2026-05-23 23:52:13 -06:00
DeFiDude 4cbb7d8b59 ble: smooth rnode pairing startup 2026-05-23 20:46:48 -06:00
DeFiDude 84bfd4871d rnode: detach serial transports on teardown 2026-05-23 17:43:24 -06:00
DeFiDude 4df2e6581f rnode: send detach sequence on BLE stop 2026-05-23 17:27:17 -06:00
DeFiDude 8328393a5f rnode: send radio off on BLE teardown 2026-05-23 16:46:41 -06:00
DeFiDude b45f6b10de tests: cover shared instance startup smoke 2026-05-23 15:33:19 -06:00
DeFiDude 55d2d34488 transport: load persisted state before actor startup 2026-05-23 15:19:34 -06:00
DeFiDude 73b250f36e Revert "ble-peer: add low-power advertising option"
This reverts commit f21f526b0a.
2026-05-23 02:38:05 -06:00
DeFiDude 1d4c1d6d7f Revert "ble-peer: restore balanced advertising default"
This reverts commit d30626a098.
2026-05-23 02:38:05 -06:00
DeFiDude d30626a098 ble-peer: restore balanced advertising default 2026-05-23 02:28:12 -06:00
DeFiDude f21f526b0a ble-peer: add low-power advertising option 2026-05-23 02:11:21 -06:00
DeFiDude 52cd1a0939 ble-peer: fix direct link request framing 2026-05-23 01:04:12 -06:00
DeFiDude d9af1beece runtime: satisfy ingress override clippy 2026-05-22 14:25:07 -06:00
DeFiDude 8b80ca88fd Merge remote-tracking branch 'origin/main' 2026-05-22 14:03:27 -06:00
DeFiDude a2c2a256d4 transport: harden shared instance client state 2026-05-22 13:57:45 -06:00
dude.eth 112dfc1d2c Update README.md
oops
2026-05-21 13:01:32 -06:00
dude.eth f9a8f89ffd Update README.md
Change target to 1.2.5 after the 1.2.4 -> 1.2.5 changes
2026-05-21 13:01:05 -06:00
DeFiDude 46449b21d3 runtime: normalize announce cap percent 2026-05-20 16:59:07 -06:00
DeFiDude 08848509b6 transport: add cache clear queries 2026-05-20 14:33:15 -06:00
DeFiDude 6a4e3af78a transport: mark path response announce entries 2026-05-20 12:02:57 -06:00
DeFiDude ffe641b3af transport: ignore stale paths for live routing 2026-05-20 10:27:47 -06:00
Belousov Oleg b89e434a00 Disable ansi for log file 2026-05-20 15:34:16 +03:00
DeFiDude 0013707496 resource: track outbound send progress 2026-05-19 23:59:38 -06:00
DeFiDude ade40c8283 interface: satisfy rnode tcp clippy 2026-05-19 22:34:25 -06:00
DeFiDude 20bee8bafd interface: split RNode TCP feature gate 2026-05-19 19:59:55 -06:00
DeFiDude f1042c0bb4 ci: use Node 24 action versions 2026-05-18 02:31:16 -06:00
DeFiDude 9d45c9a61f transport: suppress failed direct path interfaces 2026-05-17 22:24:14 -06:00
dude.eth a6c384f856 Merge pull request #2 from strijar/fix/ble
Fixed dependency on BLE
2026-05-17 15:48:38 -06:00
DeFiDude 84b0f0175a Update README.md 2026-05-17 15:38:54 -06:00
dude.eth 8e7d588faf Merge pull request #4 from strijar/fix/udevlib
Unnecessary dependency on udevlib has been removed
2026-05-17 15:35:55 -06:00
DeFiDude 83c63b463e interface: tune RNode TCP sockets 2026-05-17 15:23:12 -06:00
DeFiDude 8ac7f9a625 interface: clean up RNode TCP error wrapping 2026-05-17 15:11:42 -06:00
DeFiDude c7f048bac5 interface: reconnect RNode streams after disconnect 2026-05-17 15:02:06 -06:00
DeFiDude 7579873409 interface: harden RNode TCP endpoint parsing 2026-05-17 14:41:25 -06:00
DeFiDude a8df6d0b36 interface: note RNode TCP feature-gate cleanup 2026-05-17 14:20:41 -06:00
DeFiDude eb2972510c interface: bound RNode TCP connect attempts 2026-05-17 14:11:51 -06:00
DeFiDude 6d1b43bfc4 interface: treat RNode TCP EOF as disconnect 2026-05-17 14:10:51 -06:00
Belousov Oleg bebb9a8fca RNode cosmetic fixes 2026-05-17 14:09:02 -06:00
Belousov Oleg 497502596a RNode via TCP 2026-05-17 14:09:02 -06:00
DeFiDude 491664d24c interface: silence Android BLE build warnings 2026-05-15 20:37:13 -06:00
DeFiDude 3e85c74917 transport: satisfy strict ci lints 2026-05-15 19:32:47 -06:00
DeFiDude 68a83f83dc transport: finish upstream path reliability gaps 2026-05-15 15:45:27 -06:00
DeFiDude 1ad1a12388 transport: align path routing with upstream 2026-05-15 15:02:34 -06:00
DeFiDude 3758ae8bac transport: normalize inbound hop accounting 2026-05-15 14:34:33 -06:00
DeFiDude 15ae922535 runtime: choose packet or resource for link payloads 2026-05-15 03:25:02 -06:00
DeFiDude 5d0b6641cd runtime: add link app send commands 2026-05-15 03:22:52 -06:00
Belousov Oleg d651a4bcea Unnecessary dependency on udevlib has been removed 2026-05-15 09:29:42 +03:00
Belousov Oleg 51def9d622 Fixed dependency on BLE 2026-05-15 08:58:43 +03:00
DeFiDude 017b747eeb ci: avoid caching cargo shims 2026-05-14 23:34:50 -06:00
DeFiDude 863d723531 link: make keepalive jitter test platform-safe 2026-05-14 23:28:42 -06:00
DeFiDude 673a9715d5 tools: align utilities with Reticulum 1.2.5 2026-05-14 13:31:25 -06:00
DeFiDude 81672542ce runtime: group BLE RNode spawn args 2026-05-13 23:22:12 -06:00
DeFiDude c744831517 transport: satisfy strict clippy checks 2026-05-12 05:05:37 -06:00
DeFiDude 4cab54659c transport: implement Reticulum 1.2.5 routing controls 2026-05-11 20:15:21 -06:00
DeFiDude 4ddbf01a2a transport: expose announce aspect hashes 2026-05-11 16:05:05 -06:00
DeFiDude fe665b2216 release: prepare v0.9.3 2026-05-10 01:06:50 -06:00
DeFiDude e83fa8e208 interface: keep AutoInterface link-local addrs 2026-05-09 22:39:38 -06:00
DeFiDude bc232d65da release: prepare AutoInterface prerelease 2026-05-09 20:49:23 -06:00
DeFiDude 365bd02e75 interface: scope AutoInterface peers 2026-05-09 19:48:31 -06:00
114 changed files with 24959 additions and 4279 deletions

No files matched your search

+8 -6
View File
@@ -19,24 +19,26 @@ jobs:
os: [ubuntu-latest, macos-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@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: 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
- name: Test BLE interface features (Linux/macOS)
if: runner.os != 'Windows'
run: cargo test -p rns-interface --features ble
lint:
name: Lint
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy, rustfmt
@@ -44,4 +46,4 @@ jobs:
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- run: cargo fmt --all -- --check
- run: cargo clippy --workspace --all-targets -- -D warnings
- run: cargo clippy -p rns-interface --features ble,ble_peer --all-targets -- -D warnings
- run: cargo clippy -p rns-interface --features ble --all-targets -- -D warnings
+7 -5
View File
@@ -39,11 +39,13 @@ jobs:
env:
ARCHIVE_NAME: rsReticulum-${{ github.event.inputs.tag_name || github.ref_name }}-${{ matrix.artifact_suffix }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
ref: ${{ env.RELEASE_TAG }}
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@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
@@ -70,7 +72,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@v4
- uses: actions/upload-artifact@v7
with:
name: ${{ env.ARCHIVE_NAME }}
path: |
@@ -85,15 +87,15 @@ jobs:
permissions:
contents: write
steps:
- uses: actions/download-artifact@v4
- uses: actions/download-artifact@v7
with:
path: release-assets
merge-multiple: true
- name: Generate checksums
working-directory: release-assets
run: sha256sum * > SHA256SUMS
- uses: softprops/action-gh-release@v2
- uses: softprops/action-gh-release@v3
with:
tag_name: ${{ env.RELEASE_TAG }}
prerelease: true
prerelease: ${{ contains(env.RELEASE_TAG, '-') }}
files: release-assets/*
+1 -1
View File
@@ -6,4 +6,4 @@ __pycache__/
/interop_artifacts/
/rust_artifacts/
proptest-regressions/
/tools/
/tools/*
Generated
+264 -60
View File
@@ -69,6 +69,12 @@ version = "1.0.102"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
[[package]]
name = "arrayvec"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
[[package]]
name = "async-trait"
version = "0.1.89"
@@ -98,6 +104,17 @@ version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "bip39"
version = "2.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90dbd31c98227229239363921e60fcf5e558e43ec69094d46fc4996f08d1d5bc"
dependencies = [
"bitcoin_hashes",
"serde",
"unicode-normalization",
]
[[package]]
name = "bit-set"
version = "0.8.0"
@@ -113,6 +130,15 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
[[package]]
name = "bitcoin_hashes"
version = "0.14.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c9901a56e133a1fc86eeb1113e2591f45f4682451ca893bff494d2f88918e3f"
dependencies = [
"hex-conservative",
]
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -252,21 +278,11 @@ checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
[[package]]
name = "bzip2"
version = "0.5.2"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49ecfb22d906f800d4fe833b6282cf4dc1c298f5057ca0b5445e5c209735ca47"
checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c"
dependencies = [
"bzip2-sys",
]
[[package]]
name = "bzip2-sys"
version = "0.1.13+1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14"
dependencies = [
"cc",
"pkg-config",
"libbz2-rs-sys",
]
[[package]]
@@ -278,16 +294,6 @@ dependencies = [
"cipher",
]
[[package]]
name = "cc"
version = "1.2.58"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1e928d4b69e3077709075a938a05ffbedfa53a84c8f766efbf8220bb1ff60e1"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cesu8"
version = "1.1.0"
@@ -570,9 +576,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
dependencies = [
"const-oid",
"der_derive",
"flagset",
"pem-rfc7468",
"zeroize",
]
[[package]]
name = "der_derive"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "des"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffdd80ce8ce993de27e9f063a444a4d53ce8e8db4c1f00cc03af5ad5a9867a1e"
dependencies = [
"cipher",
]
[[package]]
name = "digest"
version = "0.10.7"
@@ -580,6 +609,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"const-oid",
"crypto-common",
"subtle",
]
@@ -655,10 +685,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
[[package]]
name = "find-msvc-tools"
version = "0.1.9"
name = "flagset"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe"
[[package]]
name = "fnv"
@@ -839,6 +869,15 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hex-conservative"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fda06d18ac606267c40c04e41b9947729bf8b9efe74bd4e82b61a5f26a510b9f"
dependencies = [
"arrayvec",
]
[[package]]
name = "hkdf"
version = "0.12.4"
@@ -1004,6 +1043,9 @@ name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
dependencies = [
"spin",
]
[[package]]
name = "leb128fmt"
@@ -1011,6 +1053,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "libbz2-rs-sys"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c"
[[package]]
name = "libc"
version = "0.2.183"
@@ -1027,24 +1075,10 @@ dependencies = [
]
[[package]]
name = "libudev"
version = "0.3.0"
name = "libm"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78b324152da65df7bb95acfcaab55e3097ceaab02fb19b228a9eb74d55f135e0"
dependencies = [
"libc",
"libudev-sys",
]
[[package]]
name = "libudev-sys"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c8469b4a23b962c1396b9b451dda50ef5b283e8dd309d69033475fa9b334324"
dependencies = [
"libc",
"pkg-config",
]
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "linux-raw-sys"
@@ -1082,6 +1116,16 @@ dependencies = [
"libc",
]
[[package]]
name = "md-5"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
dependencies = [
"cfg-if",
"digest",
]
[[package]]
name = "memchr"
version = "2.8.0"
@@ -1131,6 +1175,22 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "num-bigint-dig"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7"
dependencies = [
"lazy_static",
"libm",
"num-integer",
"num-iter",
"num-traits",
"rand 0.8.5",
"smallvec",
"zeroize",
]
[[package]]
name = "num-derive"
version = "0.4.2"
@@ -1142,6 +1202,26 @@ dependencies = [
"syn",
]
[[package]]
name = "num-integer"
version = "0.1.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
dependencies = [
"num-traits",
]
[[package]]
name = "num-iter"
version = "0.1.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf"
dependencies = [
"autocfg",
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -1149,6 +1229,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
"libm",
]
[[package]]
@@ -1250,6 +1331,15 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "pem-rfc7468"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"
dependencies = [
"base64ct",
]
[[package]]
name = "pin-project"
version = "1.1.11"
@@ -1276,6 +1366,17 @@ version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "pkcs1"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"
dependencies = [
"der",
"pkcs8",
"spki",
]
[[package]]
name = "pkcs8"
version = "0.10.2"
@@ -1481,7 +1582,7 @@ dependencies = [
[[package]]
name = "rns-crypto"
version = "0.9.2"
version = "1.0.1"
dependencies = [
"aes",
"cbc",
@@ -1502,7 +1603,7 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "0.9.2"
version = "1.0.1"
dependencies = [
"hex",
"proptest",
@@ -1519,7 +1620,7 @@ dependencies = [
[[package]]
name = "rns-interface"
version = "0.9.2"
version = "1.0.1"
dependencies = [
"bluer",
"btleplug",
@@ -1534,6 +1635,7 @@ dependencies = [
"objc2-foundation",
"rand 0.8.5",
"rns-crypto",
"rns-identity",
"rns-transport",
"rns-wire",
"serde",
@@ -1549,7 +1651,7 @@ dependencies = [
[[package]]
name = "rns-link"
version = "0.9.2"
version = "1.0.1"
dependencies = [
"hex",
"proptest",
@@ -1565,7 +1667,7 @@ dependencies = [
[[package]]
name = "rns-protocol"
version = "0.9.2"
version = "1.0.1"
dependencies = [
"bzip2",
"hex",
@@ -1582,27 +1684,38 @@ dependencies = [
[[package]]
name = "rns-ratkey"
version = "0.9.2"
version = "1.0.1"
dependencies = [
"aes",
"bip39",
"const-oid",
"der",
"des",
"hex",
"hkdf",
"pcsc",
"rand 0.8.5",
"rns-crypto",
"rns-identity",
"rns-link",
"rsa",
"serde",
"sha2",
"thiserror 2.0.18",
"toml",
"tracing",
"x509-cert",
"zeroize",
]
[[package]]
name = "rns-runtime"
version = "0.9.2"
version = "1.0.1"
dependencies = [
"bytes",
"hex",
"hmac",
"md-5",
"nix 0.29.0",
"rmp-serde",
"rmpv",
@@ -1623,7 +1736,7 @@ dependencies = [
[[package]]
name = "rns-tools"
version = "0.9.2"
version = "1.0.1"
dependencies = [
"base64",
"bytes",
@@ -1650,7 +1763,7 @@ dependencies = [
[[package]]
name = "rns-transport"
version = "0.9.2"
version = "1.0.1"
dependencies = [
"bytes",
"hex",
@@ -1670,7 +1783,7 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "0.9.2"
version = "1.0.1"
dependencies = [
"proptest",
"rns-crypto",
@@ -1678,6 +1791,27 @@ dependencies = [
"thiserror 2.0.18",
]
[[package]]
name = "rsa"
version = "0.9.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"
dependencies = [
"const-oid",
"digest",
"num-bigint-dig",
"num-integer",
"num-traits",
"pkcs1",
"pkcs8",
"rand_core 0.6.4",
"sha2",
"signature",
"spki",
"subtle",
"zeroize",
]
[[package]]
name = "rustc_version"
version = "0.4.1"
@@ -1824,7 +1958,6 @@ dependencies = [
"core-foundation",
"core-foundation-sys",
"io-kit-sys",
"libudev",
"mach2",
"nix 0.26.4",
"scopeguard",
@@ -1832,6 +1965,17 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "sha1"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "sha2"
version = "0.10.9"
@@ -1852,12 +1996,6 @@ dependencies = [
"lazy_static",
]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
@@ -1874,6 +2012,7 @@ version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
dependencies = [
"digest",
"rand_core 0.6.4",
]
@@ -1909,6 +2048,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "spin"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
[[package]]
name = "spki"
version = "0.7.3"
@@ -2043,6 +2188,42 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "tinyvec"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tls_codec"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b"
dependencies = [
"tls_codec_derive",
"zeroize",
]
[[package]]
name = "tls_codec_derive"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tokio"
version = "1.50.0"
@@ -2221,6 +2402,15 @@ version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "unicode-normalization"
version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-xid"
version = "0.2.6"
@@ -2774,6 +2964,20 @@ dependencies = [
"zeroize",
]
[[package]]
name = "x509-cert"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94"
dependencies = [
"const-oid",
"der",
"sha1",
"signature",
"spki",
"tls_codec",
]
[[package]]
name = "xml"
version = "1.2.1"
+17 -16
View File
@@ -14,7 +14,7 @@ members = [
]
[workspace.package]
version = "0.9.2"
version = "1.0.1"
edition = "2024"
license = "AGPL-3.0-or-later"
rust-version = "1.85"
@@ -24,9 +24,11 @@ rust-version = "1.85"
x25519-dalek = { version = "2", features = ["static_secrets"] }
ed25519-dalek = { version = "2", features = ["hazmat", "rand_core"] }
aes = "0.8"
des = "0.8"
cbc = { version = "0.1", features = ["alloc"] }
hkdf = "0.12"
hmac = "0.12"
md-5 = "0.10"
sha2 = "0.10"
subtle = "2"
zeroize = { version = "1", features = ["derive"] }
@@ -46,16 +48,15 @@ serde_json = "1"
tokio = { version = "1", features = ["full"] }
# Compression
bzip2 = "0.5"
bzip2 = "0.6"
# Serial
serialport = "4"
# BLE
btleplug = "0.11"
serialport = { version = "4", default-features = false }
# Networking
if-addrs = "0.13"
# AutoInterface requires fe80::/10 discovery addresses. if-addrs filters them
# unless this feature is enabled, which leaves Linux/Windows with no adopted NICs.
if-addrs = { version = "0.13", features = ["link-local"] }
socket2 = { version = "0.5", features = ["all"] }
# CLI
@@ -78,12 +79,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.0.1", default-features = false }
rns-wire = { path = "crates/rns-wire", version = "1.0.1", default-features = false }
rns-identity = { path = "crates/rns-identity", version = "1.0.1" }
rns-transport = { path = "crates/rns-transport", version = "1.0.1" }
rns-link = { path = "crates/rns-link", version = "1.0.1" }
rns-protocol = { path = "crates/rns-protocol", version = "1.0.1" }
rns-interface = { path = "crates/rns-interface", version = "1.0.1" }
rns-runtime = { path = "crates/rns-runtime", version = "1.0.1" }
rns-ratkey = { path = "crates/rns-ratkey", version = "1.0.1" }
+19 -14
View File
@@ -7,7 +7,7 @@
[![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.4](https://img.shields.io/badge/target-Reticulum%201.2.4-success.svg)](https://reticulum.network/)
[![Reticulum 1.3.8](https://img.shields.io/badge/target-Reticulum%201.3.8-success.svg)](https://reticulum.network/)
[![Status](https://img.shields.io/badge/status-experimental-yellow.svg)](#feature-status)
[Reticulum Manual](https://reticulum.network/manual/) |
@@ -61,19 +61,19 @@ Debian, Ubuntu, and Raspberry Pi OS:
```bash
sudo apt update
sudo apt install -y build-essential pkg-config libudev-dev
sudo apt install -y build-essential pkg-config
```
Fedora:
```bash
sudo dnf install gcc make pkgconf-pkg-config systemd-devel
sudo dnf install gcc make pkgconf-pkg-config
```
Arch:
```bash
sudo pacman -S --needed base-devel pkgconf systemd
sudo pacman -S --needed base-devel pkgconf
```
##### Build the tools:
@@ -116,14 +116,14 @@ The `rns-tools` crate builds Rust-namespaced Reticulum utilities:
#### Commands:
```text
rnsd-rs [-c CONFIG_DIR] [-v|-q]... [--service] [--exampleconfig] [--version]
rnstatus-rs [--all] [--sort rate|traffic|rx|tx|rxs|txs|announces|arx|atx|held]
rnsd-rs [-c CONFIG_DIR] [-v|-q]... [-i] [--service] [--exampleconfig] [--version]
rnstatus-rs [--all] [--sort rate|traffic|rx|tx|rxs|txs|announces|arx|atx|prx|ptx|held]
[--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,6 +131,11 @@ 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] [-N|-T] [-b|-B|-p] [-w MODE] [-D N] [-t N] [-R N] [--freq HZ]
[--bw HZ] [--txp DBM] [--sf SF] [--cr CR] [-x|-X]
[--eeprom-backup|--eeprom-dump] [--trust-key HASH] [--version] [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
@@ -145,7 +150,7 @@ intentional.
`rnodeconf-rs` in the current build only covers safe inspection/device setting paths, EEPROM
dump/backup, and trusted-key storage.
`rnid-rs` tracks the Reticulum 1.2.4 identity utility surface for normal
`rnid-rs` tracks the Reticulum 1.3.8 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`
@@ -169,7 +174,7 @@ 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
# Sign and validate. New signatures are Reticulum 1.2.4 .rsg envelopes.
# Sign and validate. New signatures are Reticulum 1.3.8 .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
@@ -181,7 +186,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 1.3.8 validation.
## Configuration
@@ -247,7 +252,7 @@ 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. |
## Compatibility Notes
@@ -256,8 +261,8 @@ 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 current compatibility target is Reticulum 1.3.8 where the matching Rust
surface is implemented and tested. `rnid-rs` has explicit 1.3.8 coverage for
the normal identity utility flow.
Known gaps and intentional limits:
+25 -1
View File
@@ -198,6 +198,19 @@ impl AnnounceData {
packet_dest_hash: &[u8; 16],
known_public_key: Option<&[u8; 64]>,
) -> Result<Identity, AnnounceError> {
let identity = self.verify_signature(packet_dest_hash)?;
self.validate_destination_binding(packet_dest_hash, &identity, known_public_key)?;
Ok(identity)
}
/// Verify the announce signature without checking destination-hash
/// binding or first-seen key continuity.
///
/// Reticulum transport performs this lightweight precheck before announce
/// ingress limiting, then runs full binding validation before learning the
/// path. Keeping this as a distinct step lets transport match that order
/// without duplicating announce wire-format logic.
pub fn verify_signature(&self, packet_dest_hash: &[u8; 16]) -> Result<Identity, AnnounceError> {
let identity = Identity::from_public_key(&self.public_key)
.map_err(|_| AnnounceError::InvalidPublicKey)?;
@@ -224,6 +237,17 @@ impl AnnounceData {
return Err(AnnounceError::SignatureInvalid);
}
Ok(identity)
}
/// Validate destination-hash binding and first-seen public-key continuity
/// after [`verify_signature`] has succeeded.
pub fn validate_destination_binding(
&self,
packet_dest_hash: &[u8; 16],
identity: &Identity,
known_public_key: Option<&[u8; 64]>,
) -> Result<(), AnnounceError> {
// Destination hash = SHA-256(name_hash || identity_hash) truncated to 16 bytes.
let expected_hash = {
let mut material = Vec::with_capacity(26);
@@ -256,7 +280,7 @@ impl AnnounceData {
}
}
Ok(identity)
Ok(())
}
}
+133 -4
View File
@@ -9,6 +9,7 @@ use zeroize::{Zeroize, Zeroizing};
use crate::persistence;
use std::path::Path;
use std::sync::Arc;
/// HKDF-derived key length: 32 bytes AES key || 32 bytes HMAC key.
pub const DERIVED_KEY_LENGTH: usize = 64;
@@ -33,6 +34,20 @@ 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). No-op for software backends.
fn lock(&self) {}
}
/// A Reticulum identity: X25519 keypair for encryption + Ed25519 keypair for signing.
///
/// Wire representation:
@@ -45,6 +60,29 @@ pub struct Identity {
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>>,
}
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 {
@@ -67,6 +105,7 @@ impl Identity {
pub_key,
sig_pub,
hash,
backend: None,
}
}
@@ -91,6 +130,7 @@ impl Identity {
pub_key,
sig_pub,
hash,
backend: None,
})
}
@@ -114,9 +154,22 @@ impl Identity {
pub_key,
sig_pub,
hash,
backend: None,
})
}
/// 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. Wire-identical to a software identity.
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)
}
/// 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> {
@@ -167,15 +220,32 @@ impl Identity {
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()
}
/// Re-lock the hardware backend (drop its cached authentication). No-op for
/// software identities. The next private operation will fail until re-auth.
pub fn lock(&self) {
if let Some(b) = self.backend.as_ref() {
b.lock();
}
}
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)),
}
}
pub fn verify(&self, message: &[u8], signature: &[u8; 64]) -> bool {
@@ -251,8 +321,16 @@ 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();
@@ -483,4 +561,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");
}
}
+10 -1
View File
@@ -5,7 +5,8 @@ use std::path::Path;
/// Write `data` to `path` via `<path>.tmp` + `rename`, fsyncing first.
///
/// On Unix the temp file is created with mode `0600` so that key material is
/// not world-readable even during the write.
/// not world-readable even during the write. After the rename the parent
/// directory is fsynced best-effort so the rename itself survives power loss.
pub fn atomic_write(path: &Path, data: &[u8]) -> std::io::Result<()> {
let tmp_path = path.with_extension("tmp");
@@ -28,6 +29,14 @@ pub fn atomic_write(path: &Path, data: &[u8]) -> std::io::Result<()> {
}
fs::rename(&tmp_path, path)?;
#[cfg(unix)]
if let Some(dir) = path.parent() {
if let Ok(d) = fs::File::open(dir) {
let _ = d.sync_all();
}
}
Ok(())
}
+1
View File
@@ -233,6 +233,7 @@ impl Default for RatchetRing {
/// Ratchet public key learned from a remote destination's announce, with
/// the local receive time used for expiry.
#[derive(Clone, Copy)]
pub struct ReceivedRatchet {
pub ratchet_pub: [u8; 32],
pub received_at: f64,
+9 -4
View File
@@ -8,8 +8,8 @@ license.workspace = true
[features]
default = []
serial = ["dep:serialport"]
ble = ["dep:btleplug", "dep:futures", "dep:uuid"]
ble_peer = ["ble"]
rnode-tcp = []
ble = ["dep:btleplug", "dep:futures", "dep:uuid", "dep:bluer"]
# 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.
@@ -18,6 +18,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 }
@@ -26,7 +27,7 @@ tracing = { workspace = true }
socket2 = { workspace = true }
if-addrs = { workspace = true }
serialport = { workspace = true, optional = true }
btleplug = { workspace = true, optional = true }
btleplug = { version = "0.11", optional = true }
futures = { version = "0.3", optional = true }
uuid = { version = "1", optional = true }
rand = { workspace = true }
@@ -48,6 +49,10 @@ objc2-core-bluetooth = "0.2"
[target.'cfg(target_os = "macos")'.dependencies]
libc = "0.2"
# 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"
@@ -56,7 +61,7 @@ jni = "0.19"
# Linux-only target dep so non-Linux builds don't pull in BlueZ. The
# linux_peripheral module is gated by both `ble` feature and target_os.
[target.'cfg(target_os = "linux")'.dependencies]
bluer = { version = "0.17", features = ["bluetoothd"] }
bluer = { version = "0.17", features = ["bluetoothd"], optional = true }
# Windows BLE Peripheral via WinRT GattServiceProvider (MSIX-packaged apps).
# Windows-only target dep so cross-platform builds don't pull in WinRT
+93 -10
View File
@@ -1,7 +1,8 @@
//! USB serial RNode over Android USB-C OTG via JNI to `UsbManager`. 115200 8N1.
use std::sync::Arc;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use bytes::Bytes;
use tokio::sync::mpsc;
@@ -27,6 +28,60 @@ pub const KNOWN_VIDS: &[(u16, &str)] = &[
(0x1915, "Nordic Semiconductor NRF52840"),
];
type AndroidUsbRNodeStopRegistry = Mutex<HashMap<InterfaceId, mpsc::Sender<()>>>;
fn android_usb_rnode_stop_registry() -> &'static AndroidUsbRNodeStopRegistry {
static REGISTRY: OnceLock<AndroidUsbRNodeStopRegistry> = OnceLock::new();
REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
}
struct AndroidUsbRNodeStopRegistryGuard {
id: InterfaceId,
}
impl Drop for AndroidUsbRNodeStopRegistryGuard {
fn drop(&mut self) {
android_usb_rnode_stop_registry()
.lock()
.expect("android_usb_rnode_stop_registry mutex poisoned")
.remove(&self.id);
}
}
fn register_android_usb_rnode_stop(
id: InterfaceId,
stop_tx: mpsc::Sender<()>,
) -> AndroidUsbRNodeStopRegistryGuard {
android_usb_rnode_stop_registry()
.lock()
.expect("android_usb_rnode_stop_registry mutex poisoned")
.insert(id, stop_tx);
AndroidUsbRNodeStopRegistryGuard { id }
}
/// Ask an Android USB RNode interface to send upstream's detach sequence before
/// runtime teardown aborts the task. Idempotent; unknown ids are ignored.
pub fn stop_android_usb_rnode_interface(id: InterfaceId) {
let stop_tx = android_usb_rnode_stop_registry()
.lock()
.expect("android_usb_rnode_stop_registry mutex poisoned")
.get(&id)
.cloned();
let Some(stop_tx) = stop_tx else {
tracing::debug!(id, "Android USB RNode stop requested for unknown interface");
return;
};
match stop_tx.try_send(()) {
Ok(()) => tracing::info!(id, "Android USB RNode stop signal sent"),
Err(mpsc::error::TrySendError::Full(_)) => {
tracing::debug!(id, "Android USB RNode stop signal already pending")
}
Err(mpsc::error::TrySendError::Closed(_)) => {
tracing::debug!(id, "Android USB RNode stop signal receiver already closed")
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UsbSerialDevice {
pub device_name: String,
@@ -48,6 +103,12 @@ pub struct AndroidUsbConfig {
pub coding_rate: u8,
pub tx_power: u8,
pub mode: InterfaceMode,
/// Gate each TX on the radio's CMD_READY. Python default: off.
pub flow_control: bool,
/// Short-term airtime cap, percent (0.0..=100.0). `None` = unlimited.
pub st_alock: Option<f32>,
/// Long-term airtime cap, percent (0.0..=100.0). `None` = unlimited.
pub lt_alock: Option<f32>,
}
impl AndroidUsbConfig {
@@ -62,13 +123,15 @@ impl AndroidUsbConfig {
coding_rate: 6,
tx_power: 17,
mode: InterfaceMode::Full,
flow_control: false,
st_alock: None,
lt_alock: None,
}
}
}
use jni::JavaVM;
use jni::objects::{GlobalRef, JObject, JValue};
use std::sync::OnceLock;
static JAVA_VM: OnceLock<JavaVM> = OnceLock::new();
static APP_CONTEXT: OnceLock<GlobalRef> = OnceLock::new();
@@ -453,7 +516,7 @@ async fn open_usb_serial(
let cw = connected.clone();
let vm = match JAVA_VM.get() {
Some(v) => v.clone(),
Some(v) => v,
None => return Err("JavaVM not initialized for USB write loop".into()),
};
let cr_w = conn_ref.clone();
@@ -487,7 +550,7 @@ async fn open_usb_serial(
let cr = connected.clone();
let vm2 = match JAVA_VM.get() {
Some(v) => v.clone(),
Some(v) => v,
None => return Err("JavaVM not initialized for USB read loop".into()),
};
tokio::task::spawn_blocking(move || {
@@ -561,6 +624,9 @@ pub async fn spawn_android_usb_rnode_interface(
rnode_cfg.coding_rate = config.coding_rate;
rnode_cfg.tx_power = config.tx_power;
rnode_cfg.mode = config.mode;
rnode_cfg.flow_control = config.flow_control;
rnode_cfg.st_alock = config.st_alock;
rnode_cfg.lt_alock = config.lt_alock;
let init_bytes = rnode::build_init_sequence(&rnode_cfg);
if raw_write_tx.send(init_bytes).await.is_err() {
return Err(InterfaceError::SendFailed(
@@ -572,17 +638,32 @@ pub async fn spawn_android_usb_rnode_interface(
let shared_rxb = Arc::new(AtomicU64::new(0));
let (tx, mut app_rx) = mpsc::channel::<Bytes>(64);
let (stop_tx, mut stop_rx) = mpsc::channel::<()>(1);
let stop_guard = register_android_usb_rnode_stop(id, stop_tx);
let txb = shared_txb.clone();
let wtx = raw_write_tx.clone();
let write_name = name.clone();
tokio::spawn(async move {
while let Some(payload) = app_rx.recv().await {
let frame = kiss::frame(&payload);
txb.fetch_add(frame.len() as u64, Ordering::Relaxed);
if wtx.send(frame).await.is_err() {
tracing::warn!(name = %write_name, "USB write channel closed");
break;
loop {
tokio::select! {
Some(payload) = app_rx.recv() => {
let frame = kiss::frame(&payload);
txb.fetch_add(frame.len() as u64, Ordering::Relaxed);
if wtx.send(frame).await.is_err() {
tracing::warn!(name = %write_name, "USB write channel closed");
break;
}
}
Some(_) = stop_rx.recv() => {
if wtx.send(rnode::build_detach_sequence()).await.is_err() {
tracing::warn!(name = %write_name, "USB detach sequence could not be queued");
} else {
tracing::info!(name = %write_name, "USB detach sequence queued");
}
break;
}
else => break,
}
}
});
@@ -593,6 +674,7 @@ pub async fn spawn_android_usb_rnode_interface(
let rxb = shared_rxb.clone();
let online = connected.clone();
let read_task = tokio::spawn(async move {
let _stop_guard = stop_guard;
let mut deframer = kiss::KissDeframer::new();
let mut last_rssi: Option<f32> = None;
let mut last_snr: Option<f32> = None;
@@ -625,6 +707,7 @@ pub async fn spawn_android_usb_rnode_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode: config.mode,
direction: InterfaceDirection {
+496 -99
View File
@@ -237,14 +237,38 @@ impl Default for AutoInterfaceConfig {
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct PeerKey {
ip: Ipv6Addr,
scope_id: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PeerScopeSource {
Received,
LocalCandidate,
UnscopedNonLinkLocal,
}
#[derive(Debug, Clone)]
struct PeerScopeCandidate {
ifname: String,
scope_id: u32,
source: PeerScopeSource,
}
#[derive(Debug, Clone)]
struct Peer {
ip: Ipv6Addr,
ifname: String,
scope_id: u32,
scope_source: PeerScopeSource,
addr: SocketAddrV6,
last_seen: Instant,
last_reverse: Instant,
}
type PeerTable = Arc<Mutex<HashMap<Ipv6Addr, Peer>>>;
type PeerTable = Arc<Mutex<HashMap<PeerKey, Peer>>>;
#[derive(Debug, Clone)]
struct DeduplicateEntry {
@@ -334,6 +358,111 @@ fn normalize_link_local_addr(addr: Ipv6Addr) -> Ipv6Addr {
)
}
fn is_link_local_v6(addr: Ipv6Addr) -> bool {
(addr.segments()[0] & 0xffc0) == 0xfe80
}
fn peer_scope_candidates(
peer_ip: Ipv6Addr,
received_scope: u32,
link_locals: &[(String, Ipv6Addr, u32)],
) -> Vec<PeerScopeCandidate> {
// Python Reticulum associates AutoInterface peers with the receiving
// ifname and sends to fe80::peer%ifindex. Some platforms report scope 0
// from a wildcard-bound socket, so expand link-local peers to scoped local
// candidates instead of storing an unusable fe80::peer%0 address.
if received_scope != 0 {
let ifname = link_locals
.iter()
.find(|(_, _, scope_id)| *scope_id == received_scope)
.map(|(name, _, _)| name.clone())
.unwrap_or_else(|| format!("ifindex:{received_scope}"));
return vec![PeerScopeCandidate {
ifname,
scope_id: received_scope,
source: PeerScopeSource::Received,
}];
}
if !is_link_local_v6(peer_ip) {
return vec![PeerScopeCandidate {
ifname: String::new(),
scope_id: 0,
source: PeerScopeSource::UnscopedNonLinkLocal,
}];
}
let mut candidates = Vec::new();
for (ifname, _, scope_id) in link_locals {
if *scope_id == 0
|| candidates
.iter()
.any(|c: &PeerScopeCandidate| c.scope_id == *scope_id)
{
continue;
}
candidates.push(PeerScopeCandidate {
ifname: ifname.clone(),
scope_id: *scope_id,
source: PeerScopeSource::LocalCandidate,
});
}
candidates
}
fn upsert_peer_candidates(
table: &mut HashMap<PeerKey, Peer>,
peer_ip: Ipv6Addr,
data_port: u16,
received_scope: u32,
link_locals: &[(String, Ipv6Addr, u32)],
now: Instant,
source: &'static str,
) -> usize {
let candidates = peer_scope_candidates(peer_ip, received_scope, link_locals);
if candidates.is_empty() {
tracing::warn!(
peer = %peer_ip,
received_scope,
local_candidates = link_locals.len(),
source,
"auto: discovered link-local peer but no usable scope candidates are available"
);
return 0;
}
let mut inserted = 0usize;
for candidate in candidates {
let key = PeerKey {
ip: peer_ip,
scope_id: candidate.scope_id,
};
let data_addr = SocketAddrV6::new(peer_ip, data_port, 0, candidate.scope_id);
table
.entry(key)
.and_modify(|p| {
p.ifname = candidate.ifname.clone();
p.scope_id = candidate.scope_id;
p.scope_source = candidate.source;
p.addr = data_addr;
p.last_seen = now;
})
.or_insert_with(|| {
inserted += 1;
Peer {
ip: peer_ip,
ifname: candidate.ifname,
scope_id: candidate.scope_id,
scope_source: candidate.source,
addr: data_addr,
last_seen: now,
last_reverse: now,
}
});
}
inserted
}
/// Derive `ff_T_S_:0:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX` from address-type nibble,
/// scope nibble, and bytes 2..14 of `SHA-256(group_id)`.
pub fn derive_multicast_address(
@@ -779,9 +908,19 @@ fn get_link_local_addrs_android(
}
fn iface_scope_id(iface: &if_addrs::Interface) -> u32 {
iface
.index
.unwrap_or_else(|| iface_name_to_scope_id(&iface.name))
if let Some(index) = iface.index {
return index;
}
#[cfg(windows)]
{
let adapter_index = iface_name_to_scope_id(&iface.adapter_name);
if adapter_index != 0 {
return adapter_index;
}
}
iface_name_to_scope_id(&iface.name)
}
/// Convert interface name to scope ID via POSIX/Windows `if_nametoindex`.
@@ -841,6 +980,11 @@ fn bind_one(port: u16) -> std::io::Result<UdpSocket> {
UdpSocket::from_std(sock.into())
}
fn set_multicast_if_v6(sock: &UdpSocket, scope_id: u32) -> std::io::Result<()> {
let sock_ref = socket2::SockRef::from(sock);
sock_ref.set_multicast_if_v6(scope_id)
}
/// Diagnostic: probe alternate ports to localize bind failures.
#[cfg(target_os = "android")]
fn probe_alternate_ports(base: u16) {
@@ -927,11 +1071,20 @@ pub async fn spawn_auto_interface(
tracing::info!(name = %config.name, port = config.discovery_port, "auto discovery socket bound");
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!(
iface = %iface_name,
scope_id,
error = %e,
raw_os_error = ?e.raw_os_error(),
"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.
// PermissionDenied (EPERM/EACCES, Windows ERROR_ACCESS_DENIED) on
// Apple platforms is the canonical signal that the multicast
// networking entitlement isn't provisioned. Surfaced as an event
// so UIs can show pending Apple approval.
if e.kind() == std::io::ErrorKind::PermissionDenied {
tracing::warn!(
iface = %iface_name,
@@ -1001,16 +1154,38 @@ pub async fn spawn_auto_interface(
for (_name, ll_addr, scope_id) in &snapshot {
let beacon = make_beacon(&group_id, ll_addr);
let dest = SocketAddrV6::new(mcast_group, disc_port, 0, *scope_id);
if let Err(e) = set_multicast_if_v6(disc_sock_send.as_ref(), *scope_id) {
tracing::warn!(
iface = %_name,
ll = %ll_addr,
scope_id,
error = %e,
raw_os_error = ?e.raw_os_error(),
"auto: failed to select multicast outbound interface"
);
}
let res = disc_sock_send.send_to(&beacon, dest).await;
tracing::debug!(
iface = %_name,
ll = %ll_addr,
scope_id,
dst = %dest,
hash = %hex32(&beacon),
sent = res.is_ok(),
"auto-instr beacon TX"
);
match res {
Ok(n) => tracing::debug!(
iface = %_name,
ll = %ll_addr,
scope_id,
dst = %dest,
hash = %hex32(&beacon),
sent_bytes = n,
"auto-instr beacon TX"
),
Err(e) => tracing::warn!(
iface = %_name,
ll = %ll_addr,
scope_id,
dst = %dest,
hash = %hex32(&beacon),
error = %e,
raw_os_error = ?e.raw_os_error(),
"auto: beacon TX failed"
),
}
}
}
});
@@ -1024,12 +1199,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;
@@ -1037,28 +1217,29 @@ pub async fn spawn_auto_interface(
if let SocketAddr::V6(src_v6) = src {
let peer_ip = *src_v6.ip();
// Match source LL against ours — non-empty means self-echo.
let snapshot = { disc_link_locals.lock().await.clone() };
let self_iface = {
let snapshot = disc_link_locals.lock().await;
snapshot
.iter()
.find(|(_, ll, _)| *ll == peer_ip)
.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;
@@ -1068,26 +1249,36 @@ pub async fn spawn_auto_interface(
if !match_ok {
continue;
}
let scope = src_v6.scope_id();
let data_addr = SocketAddrV6::new(peer_ip, data_port, 0, scope);
let received_scope = src_v6.scope_id();
let now = Instant::now();
let mut table = peers_disc.lock().await;
table
.entry(peer_ip)
.and_modify(|p| p.last_seen = now)
.or_insert(Peer {
addr: data_addr,
last_seen: now,
last_reverse: now,
});
tracing::debug!(peer = %peer_ip, "auto: peer discovered/refreshed");
let inserted = upsert_peer_candidates(
&mut table,
peer_ip,
data_port,
received_scope,
&snapshot,
now,
"multicast",
);
tracing::debug!(
peer = %peer_ip,
received_scope,
inserted,
peer_records = table.len(),
"auto: peer discovered/refreshed"
);
} else {
tracing::debug!(src = %src, "auto-instr mcast RX non-v6 source");
}
}
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;
}
}
}
@@ -1099,16 +1290,19 @@ pub async fn spawn_auto_interface(
let unicast_group_id = config.group_id.clone();
let unicast_link_locals = link_locals.clone();
let unicast_disc_port = config.discovery_port + 1;
if let Ok(unicast_sock) = UdpSocket::bind(SocketAddrV6::new(
Ipv6Addr::UNSPECIFIED,
unicast_disc_port,
0,
0,
))
.await
{
let unicast_sock = Arc::new(unicast_sock);
let unicast_sock = match bind_reusable_udp_v6(unicast_disc_port) {
Ok(sock) => Some(Arc::new(sock)),
Err(e) => {
tracing::debug!(
port = unicast_disc_port,
error = %e,
raw_os_error = ?e.raw_os_error(),
"auto: could not bind unicast discovery port"
);
None
}
};
if let Some(unicast_sock) = unicast_sock {
let urecv_sock = unicast_sock.clone();
let urecv_peers = peers_unicast.clone();
let urecv_online = online_u.clone();
@@ -1116,45 +1310,59 @@ 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;
}
if let SocketAddr::V6(src_v6) = src {
let peer_ip = *src_v6.ip();
let is_self = {
let snapshot = urecv_link_locals.lock().await;
snapshot.iter().any(|(_, ll, _)| *ll == peer_ip)
};
let snapshot = { urecv_link_locals.lock().await.clone() };
let is_self = { snapshot.iter().any(|(_, ll, _)| *ll == peer_ip) };
if is_self {
continue;
}
if !verify_beacon(&buf[..n], &urecv_group_id, &peer_ip) {
continue;
}
let scope = src_v6.scope_id();
let data_addr = SocketAddrV6::new(peer_ip, data_port, 0, scope);
let received_scope = src_v6.scope_id();
let now = Instant::now();
let mut table = urecv_peers.lock().await;
table
.entry(peer_ip)
.and_modify(|p| p.last_seen = now)
.or_insert(Peer {
addr: data_addr,
last_seen: now,
last_reverse: now,
});
tracing::debug!(peer = %peer_ip, "auto: unicast peer discovered");
let inserted = upsert_peer_candidates(
&mut table,
peer_ip,
data_port,
received_scope,
&snapshot,
now,
"unicast",
);
tracing::debug!(
peer = %peer_ip,
received_scope,
inserted,
peer_records = table.len(),
"auto: unicast peer discovered"
);
}
}
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;
}
}
}
@@ -1193,27 +1401,56 @@ 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 (_ip, peer) in table.iter_mut() {
if now.duration_since(peer.last_reverse).as_secs_f64()
>= REVERSE_PEERING_INTERVAL
{
for (_name, ll_addr, scope_id) in &snapshot {
let beacon = make_beacon(&rev_group_id, ll_addr);
let dest =
SocketAddrV6::new(*peer.addr.ip(), unicast_disc_port, 0, *scope_id);
let _ = unicast_sock.send_to(&beacon, dest).await;
// 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"
);
}
}
}
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;
}
}
}
});
} else {
tracing::debug!(
"auto: could not bind unicast discovery port {}",
unicast_disc_port
);
}
// Periodic jobs: NIC re-enum, peer aging, carrier detection (every PEER_JOB_INTERVAL).
@@ -1273,6 +1510,17 @@ pub async fn spawn_auto_interface(
);
}
for (ifname, addr, scope_id) in &added {
if let Err(e) = set_multicast_if_v6(jobs_disc_sock.as_ref(), *scope_id) {
tracing::warn!(
iface = %jobs_iface_name,
nic = %ifname,
addr = %addr,
scope_id,
error = %e,
raw_os_error = ?e.raw_os_error(),
"AutoInterface failed to set multicast interface for new NIC"
);
}
match jobs_disc_sock.join_multicast_v6(&jobs_mcast, *scope_id) {
Ok(()) => tracing::info!(
iface = %jobs_iface_name,
@@ -1357,21 +1605,63 @@ 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();
for (_ip, peer) in table.iter() {
let res = data_sock_w.send_to(&data, peer.addr).await;
// 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!(
dst = %peer.addr,
len,
prefix = %prefix,
peer_count,
sent = res.is_ok(),
"auto-instr data TX"
"auto-instr data TX skipped: no discovered peers"
);
if res.is_ok() {
task_txb.fetch_add(len as u64, Ordering::Relaxed);
}
for peer in &targets {
let res = data_sock_w.send_to(&data, peer.addr).await;
match res {
Ok(n) => {
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) => {
tracing::warn!(
peer = %peer.ip,
ifname = %peer.ifname,
scope_id = peer.scope_id,
scope_source = ?peer.scope_source,
dst = %peer.addr,
len,
prefix = %hex_prefix(&data, 16),
peer_count,
error = %e,
raw_os_error = ?e.raw_os_error(),
"auto: data TX failed"
);
}
}
}
}
@@ -1382,9 +1672,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;
}
@@ -1415,8 +1707,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;
}
}
}
@@ -1427,6 +1723,7 @@ pub async fn spawn_auto_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -1559,6 +1856,83 @@ mod tests {
assert!(!verify_beacon(&beacon[..16], "reticulum", &addr));
}
#[test]
fn peer_scope_candidates_preserves_received_scope() {
let peer = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
let locals = vec![
("en0".to_string(), Ipv6Addr::LOCALHOST, 11),
("eth0".to_string(), Ipv6Addr::LOCALHOST, 22),
];
let candidates = peer_scope_candidates(peer, 22, &locals);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].ifname, "eth0");
assert_eq!(candidates[0].scope_id, 22);
assert_eq!(candidates[0].source, PeerScopeSource::Received);
}
#[test]
fn peer_scope_candidates_expands_zero_scope_for_link_local() {
let peer = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
let locals = vec![
("en0".to_string(), Ipv6Addr::LOCALHOST, 11),
("eth0".to_string(), Ipv6Addr::LOCALHOST, 22),
("duplicate".to_string(), Ipv6Addr::LOCALHOST, 22),
];
let candidates = peer_scope_candidates(peer, 0, &locals);
assert_eq!(candidates.len(), 2);
assert_eq!(candidates[0].ifname, "en0");
assert_eq!(candidates[0].scope_id, 11);
assert_eq!(candidates[0].source, PeerScopeSource::LocalCandidate);
assert_eq!(candidates[1].ifname, "eth0");
assert_eq!(candidates[1].scope_id, 22);
}
#[test]
fn upsert_peer_candidates_keys_same_ip_by_scope() {
let peer = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
let locals = vec![
("en0".to_string(), Ipv6Addr::LOCALHOST, 11),
("eth0".to_string(), Ipv6Addr::LOCALHOST, 22),
];
let mut table = HashMap::new();
let inserted = upsert_peer_candidates(
&mut table,
peer,
DATA_PORT,
0,
&locals,
Instant::now(),
"test",
);
assert_eq!(inserted, 2);
assert_eq!(table.len(), 2);
assert!(table.contains_key(&PeerKey {
ip: peer,
scope_id: 11,
}));
assert!(table.contains_key(&PeerKey {
ip: peer,
scope_id: 22,
}));
assert_eq!(
table
.get(&PeerKey {
ip: peer,
scope_id: 11,
})
.unwrap()
.addr
.scope_id(),
11
);
}
#[test]
fn test_scope_id_prefers_enumerated_interface_index() {
let addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
@@ -1566,6 +1940,29 @@ mod tests {
assert_eq!(iface_scope_id(&iface), 1234);
}
#[cfg(target_os = "linux")]
#[test]
fn if_addrs_link_local_feature_is_enabled() {
let proc_addrs = std::fs::read_to_string("/proc/net/if_inet6").unwrap_or_default();
let host_has_link_local = proc_addrs.lines().any(|line| {
line.split_whitespace()
.nth(3)
.is_some_and(|scope| scope.eq_ignore_ascii_case("20"))
});
if !host_has_link_local {
return;
}
let addrs = if_addrs::get_if_addrs().expect("list network interfaces");
assert!(
addrs.iter().any(|iface| {
matches!(&iface.addr, if_addrs::IfAddr::V6(addr) if addr.is_link_local())
}),
"Linux has link-local IPv6 addresses in /proc/net/if_inet6, but if-addrs returned none; \
keep the workspace if-addrs dependency feature `link-local` enabled"
);
}
fn test_interface(name: &str, ip: Ipv6Addr, index: Option<u32>) -> if_addrs::Interface {
let addr = if_addrs::IfAddr::V6(if_addrs::Ifv6Addr {
ip,
+20 -37
View File
@@ -56,6 +56,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 +78,9 @@ impl AX25KISSConfig {
slottime: 20,
flow_control: false,
mode: InterfaceMode::Full,
data_bits: 8,
parity: "N".to_string(),
stop_bits: 1,
}
}
@@ -232,10 +239,12 @@ pub async fn spawn_ax25kiss_interface(
crate::traits::InterfaceError::SendFailed(format!("ax25kiss config: {}", e))
})?;
let (data_bits, parity, stop_bits) =
crate::serial::serial_params_from(config.data_bits, &config.parity, config.stop_bits);
let port = serialport::new(&config.port, config.baud_rate)
.data_bits(serialport::DataBits::Eight)
.parity(serialport::Parity::None)
.stop_bits(serialport::StopBits::One)
.data_bits(data_bits)
.parity(parity)
.stop_bits(stop_bits)
.timeout(Duration::from_millis(AX25_READ_TIMEOUT_MS))
.open()
.map_err(|e| {
@@ -311,25 +320,13 @@ pub async fn spawn_ax25kiss_interface(
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 +345,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 +382,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 +393,7 @@ pub async fn spawn_ax25kiss_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
+3
View File
@@ -291,6 +291,7 @@ pub async fn spawn_backbone_server(
let handle = InterfaceHandle {
id: client_id,
parent_id: Some(id),
name: client_name,
mode,
direction: InterfaceDirection {
@@ -323,6 +324,7 @@ pub async fn spawn_backbone_server(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -490,6 +492,7 @@ pub async fn spawn_backbone_client(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -374,12 +374,27 @@ 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,
@@ -406,39 +421,33 @@ pub fn write_peer(address: &str, data: &[u8]) -> Result<(), String> {
return Err(format!("peer {address} marked offline"));
}
// 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(());
// Always enqueue, then drain, so every fragment leaves through the single
// FIFO path. Issuing directly on a "ready" radio would let a later
// fragment jump ahead of ones already queued from when it was busy, and
// the receiver would misparse the out-of-order envelope as a raw packet.
{
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());
}
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)"
);
unsafe { drain_pending_writes(address) };
Ok(())
}
/// Requeues at front if canSend flips false mid-drain.
/// Drains queued writes in FIFO order while the radio can accept them. Holds
/// the pending-write lock across the whole loop so a concurrent drain (or a
/// [`write_peer`] enqueue) can't interleave and reorder fragments — an
/// out-of-order envelope makes the receiver misparse the frame as a raw packet.
unsafe fn drain_pending_writes(address: &str) {
let peer = {
let g = connected_peers().lock().expect("connected_peers lock");
@@ -451,23 +460,27 @@ unsafe fn drain_pending_writes(address: &str) {
return;
}
let mut drained = 0usize;
let mut g = pending_write().lock().expect("pending_write lock");
let Some(q) = g.get_mut(address) else {
return;
};
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;
};
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);
// Peek before popping: leave the fragment queued if the radio can't
// take it, so ordering is preserved for the next drain.
if q.front().is_none() {
break;
}
let ready: bool = unsafe { msg_send![peer.peripheral.0, canSendWriteWithoutResponse] };
if !ready {
break;
}
let Some(data) = q.pop_front() else {
break;
};
unsafe { issue_write(&peer, &data) };
drained += 1;
}
drop(g);
if drained > 0 {
tracing::debug!(
target: "ble_trace",
@@ -804,9 +817,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 +832,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 {
@@ -1265,9 +1282,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]
File diff suppressed because it is too large. Load diff
+338 -121
View File
@@ -46,9 +46,12 @@ const RECONNECT_WAIT_MAX: u64 = 120;
/// `None` retries forever; teardown goes via `stop_ble_rnode_interface`.
const MAX_RECONNECT_TRIES: Option<usize> = None;
const SCAN_TIMEOUT: u64 = 3;
const CONNECT_TIMEOUT: u64 = 5;
/// Bounds disable-while-offline teardown latency to ~1s.
const RUNNING_POLL: Duration = Duration::from_secs(1);
#[cfg(target_os = "linux")]
const RNODE_POST_BOND_SETTLE: Duration = Duration::from_millis(2600);
const RNODE_NATIVE_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(6);
const RNODE_NATIVE_HANDSHAKE_PROBE: Duration = Duration::from_millis(650);
/// `stop_ble_rnode_interface` flips false; the read_task removes the entry
/// on its way out.
@@ -117,38 +120,77 @@ async fn wait_or_shutdown(total: Duration, flag: &AtomicBool) -> bool {
!flag.load(Ordering::SeqCst)
}
/// RNode can pack multiple frames in one read, so use the raw deframer for
/// full-command extended KISS framing.
async fn wait_for_rnode_handshake(
fn is_rnode_handshake_frame(cmd: u8, frame: &[u8]) -> bool {
(cmd == rnode::CMD_DETECT && frame.first().copied() == Some(rnode::DETECT_RESP))
|| (cmd == rnode::CMD_FW_VERSION && !frame.is_empty())
}
fn is_pairing_transition_error(error: &InterfaceError) -> bool {
matches!(
error,
InterfaceError::SendFailed(message) if message.starts_with("BLE pairing in progress:")
)
}
/// Android's native bridge can come up immediately after SMP completes, while
/// rsCardputer's RNode BLE stack is still settling. Probe detect a few times
/// inside one connection attempt so a single dropped early frame does not cost
/// a full reconnect backoff.
async fn probe_native_rnode_handshake(
tcp_read: &mut tokio::net::tcp::OwnedReadHalf,
tcp_write: &mut tokio::net::tcp::OwnedWriteHalf,
timeout: Duration,
probe_interval: Duration,
running_task: &AtomicBool,
) -> bool {
use tokio::io::AsyncReadExt;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let detect_seq = rnode::build_detect_sequence();
let mut deframer = kiss::RawKissDeframer::new();
let mut buf = [0u8; 1024];
let deadline = std::time::Instant::now() + timeout;
let mut next_probe = std::time::Instant::now();
while std::time::Instant::now() < deadline {
if !running_task.load(Ordering::SeqCst) {
return false;
}
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
let read = tokio::time::timeout(remaining.min(RUNNING_POLL), tcp_read.read(&mut buf)).await;
let now = std::time::Instant::now();
if now >= next_probe {
if let Err(e) = tcp_write.write_all(&detect_seq).await {
tracing::warn!(error = %e, "BLE RNode native detect probe write failed");
return false;
}
let _ = tcp_write.flush().await;
next_probe = std::time::Instant::now() + probe_interval;
}
let now = std::time::Instant::now();
let read_budget = next_probe
.min(deadline)
.saturating_duration_since(now)
.min(RUNNING_POLL);
if read_budget.is_zero() {
tokio::task::yield_now().await;
continue;
}
let read = tokio::time::timeout(read_budget, tcp_read.read(&mut buf)).await;
let n = match read {
Ok(Ok(0)) => return false,
Ok(Ok(n)) => n,
Ok(Err(_)) => return false,
Err(_) => continue,
};
for (cmd, frame) in deframer.feed(&buf[..n]) {
if cmd == rnode::CMD_DETECT && frame.first().copied() == Some(rnode::DETECT_RESP) {
return true;
}
if cmd == rnode::CMD_FW_VERSION && !frame.is_empty() {
if is_rnode_handshake_frame(cmd, &frame) {
return true;
}
}
}
false
}
@@ -337,6 +379,10 @@ pub struct BleRNodeConfig {
pub flow_control: bool,
pub st_alock: Option<f32>,
pub lt_alock: Option<f32>,
/// Station-ID beacon: seconds between IDs, armed by data TX
/// (Python `id_interval`/`id_callsign`, callsign max 32 bytes).
pub id_interval: Option<u64>,
pub id_callsign: Option<Vec<u8>>,
}
impl BleRNodeConfig {
@@ -350,13 +396,60 @@ impl BleRNodeConfig {
coding_rate: 5,
tx_power: 14,
mode: InterfaceMode::Full,
flow_control: true,
// Python RNodeInterface defaults flow_control off.
flow_control: false,
st_alock: None,
lt_alock: None,
id_interval: None,
id_callsign: None,
}
}
}
/// Station-ID beacon parameters, disabled for oversized callsigns
/// (Python RNodeInterface.py:333-343).
fn beacon_from_config(config: &BleRNodeConfig) -> Option<(Duration, Bytes)> {
config
.id_interval
.zip(config.id_callsign.clone())
.filter(|(_, callsign)| {
let ok = callsign.len() <= rnode::CALLSIGN_MAX_LEN;
if !ok {
tracing::error!(
name = %config.name,
len = callsign.len(),
"id_callsign exceeds {} bytes, beaconing disabled",
rnode::CALLSIGN_MAX_LEN
);
}
ok
})
.map(|(interval, callsign)| (Duration::from_secs(interval), Bytes::from(callsign)))
}
fn rnode_config_from_ble_config(config: &BleRNodeConfig) -> rnode::RNodeConfig {
rnode::RNodeConfig {
name: config.name.clone(),
port: config.ble_uri.clone(),
baud_rate: 0,
frequency: config.frequency,
bandwidth: config.bandwidth,
spreading_factor: config.spreading_factor,
coding_rate: config.coding_rate,
tx_power: config.tx_power,
mode: config.mode,
flow_control: config.flow_control,
st_alock: config.st_alock,
lt_alock: config.lt_alock,
id_interval: config.id_interval,
id_callsign: config.id_callsign.clone(),
}
}
fn build_ble_rnode_init_sequence(config: &BleRNodeConfig) -> Vec<u8> {
rnode::build_init_sequence(&rnode_config_from_ble_config(config))
}
pub(crate) async fn get_adapter() -> Result<Adapter, InterfaceError> {
// btleplug's Android global_adapter() panics without init; under
// panic=abort that kills the app. Fail loudly so the UI can prompt.
@@ -584,6 +677,11 @@ struct BleRNodeConnection {
write_mtu: usize,
}
enum NativeBridgeWrite {
Packet(Bytes),
Raw(Vec<u8>),
}
async fn connect_rnode(
adapter: &Adapter,
ble_uri: &str,
@@ -592,6 +690,18 @@ async fn connect_rnode(
let peripheral = resolve_ble_target(adapter, ble_uri).await?;
ble_diag(format!("[ble] resolved peripheral id={}", peripheral.id()));
#[cfg(target_os = "linux")]
{
// BlueZ needs explicit pairing before we open a btleplug GATT
// connection. If this creates a fresh bond, RNode intentionally
// disconnects shortly afterwards; wait through that before connect().
let bluer_addr = parse_linux_ble_address(&peripheral.address().to_string())?;
if linux_trigger_pairing(bluer_addr).await? {
ble_diag("[pair][linux] fresh bond complete — waiting for RNode post-pair disconnect");
tokio::time::sleep(RNODE_POST_BOND_SETTLE).await;
}
}
let mut last_err = String::new();
for attempt in 1..=3 {
match peripheral.connect().await {
@@ -654,21 +764,18 @@ async fn connect_rnode(
rx_char.properties, tx_char.properties
));
// SMP must run BEFORE subscribe on desktop / Apple platforms — reading
// the encrypted TX char kicks off SMP and drops L2CAP, which kills any
// pending subscribe. iOS/macOS share CoreBluetooth; Windows uses WinRT
// GATT (auto-prompt on encrypted-char reads). Same trigger shape works
// for all three. Linux uses bluer's explicit `Device::pair()` instead —
// BlueZ does not auto-prompt SMP from an encrypted-char read.
#[cfg(any(target_os = "ios", target_os = "macos", target_os = "windows"))]
// SMP must run BEFORE subscribe on desktop / Apple / Android platforms —
// reading the encrypted TX char kicks off SMP and drops L2CAP, which
// kills any pending subscribe. iOS/macOS share CoreBluetooth; Windows
// (WinRT) and Android auto-prompt and retry on encrypted-char reads.
// Linux used explicit BlueZ pairing before `connect()`, above.
#[cfg(any(
target_os = "ios",
target_os = "macos",
target_os = "windows",
target_os = "android"
))]
desktop_trigger_pairing(&peripheral, &tx_char).await?;
#[cfg(target_os = "linux")]
{
// peripheral.address() returns a BDAddr → MAC string; the helper
// also accepts BlueZ D-Bus paths for callers that pass `id()`.
let bluer_addr = parse_linux_ble_address(&peripheral.address().to_string())?;
linux_trigger_pairing(bluer_addr).await?;
}
ble_diag("[ble] subscribe TX start");
peripheral.subscribe(&tx_char).await.map_err(|e| {
@@ -707,7 +814,21 @@ async fn connect_rnode(
/// pairing flow when the characteristic requires authentication). Linux
/// uses `linux_trigger_pairing` instead — BlueZ requires an explicit
/// `Device::pair()` plus a registered Agent for the passkey callback.
#[cfg(any(target_os = "ios", target_os = "macos", target_os = "windows"))]
///
/// Android behaves like Windows: a GATT op on an auth-required char makes
/// the platform start bonding (system passkey dialog) and retry the op
/// internally once bonded. Without this read-first step the subscribe()
/// CCCD write fails instantly with insufficient-auth while the bond is
/// still running — first add fails, second connect works. If the stack
/// errors instead of blocking, the error maps to "BLE pairing in
/// progress" and the reconnect loop retries on a 1s cadence until the
/// bond lands.
#[cfg(any(
target_os = "ios",
target_os = "macos",
target_os = "windows",
target_os = "android"
))]
async fn desktop_trigger_pairing(
peripheral: &Peripheral,
tx_char: &btleplug::api::Characteristic,
@@ -896,7 +1017,7 @@ fn parse_linux_ble_address(addr: &str) -> Result<bluer::Address, InterfaceError>
/// daemon stops retrying SMP instead of re-invoking `request_passkey`
/// every ~60s.
#[cfg(target_os = "linux")]
async fn linux_trigger_pairing(bluer_addr: bluer::Address) -> Result<(), InterfaceError> {
async fn linux_trigger_pairing(bluer_addr: bluer::Address) -> Result<bool, InterfaceError> {
let overall_start = std::time::Instant::now();
// Reuse the cached session so the second-and-subsequent attempts skip
@@ -927,7 +1048,7 @@ async fn linux_trigger_pairing(bluer_addr: bluer::Address) -> Result<(), Interfa
"[pair][linux] already bonded with {bluer_addr} (is_paired check {:.2}s)",
t_paired.elapsed().as_secs_f32()
));
return Ok(());
return Ok(false);
}
ble_diag(format!(
"[pair][linux] is_paired=false in {:.2}s",
@@ -1049,7 +1170,7 @@ async fn linux_trigger_pairing(bluer_addr: bluer::Address) -> Result<(), Interfa
}
}
let _ = linux_pairing_finished_sender().send(LinuxPairingFinished { attempt_id, status });
outcome
outcome.map(|()| true)
}
/// WithoutResponse is fire-and-forget at the ATT layer; the radio still
@@ -1069,6 +1190,14 @@ pub(crate) async fn ble_write(
Ok(())
}
async fn ble_send_radio_off(conn: &BleRNodeConnection) {
let seq = rnode::build_detach_sequence();
match ble_write(&conn.peripheral, &conn.rx_char, &seq, conn.write_mtu).await {
Ok(()) => ble_diag("[ble] detach sent before disconnect"),
Err(e) => ble_diag(format!("[ble] detach before disconnect failed: {e}")),
}
}
/// Auto-reconnect across drops; resolve_ble_target re-runs every retry so
/// iOS RPA rotation heals automatically.
pub async fn spawn_ble_rnode_interface(
@@ -1092,24 +1221,12 @@ pub async fn spawn_ble_rnode_interface(
config.bandwidth,
);
let rnode_cfg = rnode::RNodeConfig {
name: config.name.clone(),
port: config.ble_uri.clone(),
baud_rate: 0,
frequency: config.frequency,
bandwidth: config.bandwidth,
spreading_factor: config.spreading_factor,
coding_rate: config.coding_rate,
tx_power: config.tx_power,
mode: config.mode,
flow_control: config.flow_control,
st_alock: config.st_alock,
lt_alock: config.lt_alock,
};
let init_seq_template = build_ble_rnode_init_sequence(&config);
let name = config.name.clone();
let mode = config.mode;
let flow_control = config.flow_control;
let beacon = beacon_from_config(&config);
let ble_uri = config.ble_uri.clone();
let log_name = name.clone();
let running_task = running.clone();
@@ -1154,9 +1271,11 @@ pub async fn spawn_ble_rnode_interface(
let conn = match connect_rnode(&adapter, &ble_uri).await {
Ok(c) => c,
Err(e) => {
let pairing_transition = is_pairing_transition_error(&e);
let retry_wait = if pairing_transition { 1 } else { backoff };
tracing::warn!(name = %log_name, error = %e, "BLE RNode connect failed");
ble_diag(format!(
"[ble] connect_rnode err: {e} — retrying in {backoff}s (attempt {})",
"[ble] connect_rnode err: {e} — retrying in {retry_wait}s (attempt {})",
tries + 1
));
if reconnect_try_exhausted(&mut tries) {
@@ -1164,10 +1283,14 @@ pub async fn spawn_ble_rnode_interface(
ble_diag("[ble] max reconnect tries reached — giving up");
return;
}
if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await {
if wait_or_shutdown(Duration::from_secs(retry_wait), &running_task).await {
return;
}
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
if pairing_transition {
backoff = RECONNECT_WAIT;
} else {
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
}
continue;
}
};
@@ -1189,9 +1312,8 @@ pub async fn spawn_ble_rnode_interface(
}
ble_diag("[ble] detect sent ok");
ble_diag("[ble] sending init + airtime sequence");
let mut init_seq = rnode::build_init_sequence(&rnode_cfg);
init_seq.extend_from_slice(&rnode::build_airtime_sequence(&rnode_cfg));
ble_diag("[ble] sending init sequence");
let init_seq = init_seq_template.clone();
if let Err(e) =
ble_write(&conn.peripheral, &conn.rx_char, &init_seq, conn.write_mtu).await
{
@@ -1228,8 +1350,37 @@ pub async fn spawn_ble_rnode_interface(
let online_w = online_handle.clone();
let ready_w = ready.clone();
let txb_w = task_txb.clone();
let beacon_w = beacon.clone();
let write_handle = tokio::spawn(async move {
while let Some(data) = conn_rx.recv().await {
// Python first_tx semantics: armed by data TX, cleared when
// the callsign beacon goes out (RNodeInterface.py:712-718).
let mut first_tx: Option<tokio::time::Instant> = None;
loop {
let data = if let Some((interval, ref callsign)) = beacon_w {
match tokio::time::timeout(Duration::from_secs(1), conn_rx.recv()).await {
Ok(Some(data)) => data,
Ok(None) => break,
Err(_) => {
if first_tx.is_none_or(|t| t.elapsed() < interval) {
continue;
}
tracing::debug!("BLE RNode transmitting station-ID beacon");
callsign.clone()
}
}
} else {
match conn_rx.recv().await {
Some(data) => data,
None => break,
}
};
if let Some((_, ref callsign)) = beacon_w {
if data == *callsign {
first_tx = None;
} else if first_tx.is_none() {
first_tx = Some(tokio::time::Instant::now());
}
}
txb_w.fetch_add(data.len() as u64, Ordering::Relaxed);
if flow_control {
while !ready_w.load(Ordering::SeqCst) {
@@ -1286,16 +1437,21 @@ pub async fn spawn_ble_rnode_interface(
let mut transport_closed = false;
'read: loop {
if !online_handle.load(Ordering::SeqCst) || !running_task.load(Ordering::SeqCst) {
if !online_handle.load(Ordering::SeqCst) {
break 'read;
}
if !running_task.load(Ordering::SeqCst) {
ble_send_radio_off(&conn).await;
break 'read;
}
let notification = tokio::select! {
n = notification_stream.next() => n,
_ = tokio::time::sleep(Duration::from_secs(CONNECT_TIMEOUT)) => {
_ = tokio::time::sleep(RUNNING_POLL) => {
// Polling slice — bounds disable-while-connected
// teardown latency.
if !running_task.load(Ordering::SeqCst) {
ble_send_radio_off(&conn).await;
break 'read;
}
if conn.peripheral.is_connected().await.unwrap_or(false) {
@@ -1368,6 +1524,7 @@ pub async fn spawn_ble_rnode_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -1412,24 +1569,12 @@ pub async fn spawn_ble_rnode_interface_native(
config.bandwidth,
);
let rnode_cfg = rnode::RNodeConfig {
name: config.name.clone(),
port: config.ble_uri.clone(),
baud_rate: 0,
frequency: config.frequency,
bandwidth: config.bandwidth,
spreading_factor: config.spreading_factor,
coding_rate: config.coding_rate,
tx_power: config.tx_power,
mode: config.mode,
flow_control: config.flow_control,
st_alock: config.st_alock,
lt_alock: config.lt_alock,
};
let init_seq_template = build_ble_rnode_init_sequence(&config);
let name = config.name.clone();
let mode = config.mode;
let flow_control = config.flow_control;
let beacon = beacon_from_config(&config);
let ble_uri = config.ble_uri.clone();
let log_name = name.clone();
let running = register_running(id);
@@ -1471,22 +1616,17 @@ pub async fn spawn_ble_rnode_interface_native(
let (mut tcp_read, mut tcp_write) = stream.into_split();
let detect_seq = rnode::build_detect_sequence();
if let Err(e) = tcp_write.write_all(&detect_seq).await {
tracing::warn!(error = %e, "BLE RNode native detect write failed");
if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await {
return;
}
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
continue;
}
// Without gating on DETECT_RESP + firmware version we'd flag
// "online" while the radio is asleep or the BLE-NUS bridge
// dropped a frame.
let detected =
wait_for_rnode_handshake(&mut tcp_read, Duration::from_secs(5), &running_task)
.await;
let detected = probe_native_rnode_handshake(
&mut tcp_read,
&mut tcp_write,
RNODE_NATIVE_HANDSHAKE_TIMEOUT,
RNODE_NATIVE_HANDSHAKE_PROBE,
&running_task,
)
.await;
if !detected {
tracing::warn!(
name = %log_name,
@@ -1499,8 +1639,7 @@ pub async fn spawn_ble_rnode_interface_native(
continue;
}
let mut init_seq = rnode::build_init_sequence(&rnode_cfg);
init_seq.extend_from_slice(&rnode::build_airtime_sequence(&rnode_cfg));
let init_seq = init_seq_template.clone();
if let Err(e) = tcp_write.write_all(&init_seq).await {
tracing::warn!(error = %e, "BLE RNode native init write failed");
if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await {
@@ -1524,26 +1663,67 @@ pub async fn spawn_ble_rnode_interface_native(
let ready = Arc::new(AtomicBool::new(true));
let (conn_tx, mut conn_rx) = mpsc::channel::<Bytes>(256);
let (conn_tx, mut conn_rx) = mpsc::channel::<NativeBridgeWrite>(256);
let conn_tx_for_stop = conn_tx.clone();
let online_w = online_handle.clone();
let ready_w = ready.clone();
let txb_w = task_txb.clone();
let beacon_w = beacon.clone();
let write_handle = tokio::spawn(async move {
while let Some(data) = conn_rx.recv().await {
txb_w.fetch_add(data.len() as u64, Ordering::Relaxed);
if flow_control {
while !ready_w.load(Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(10)).await;
if !online_w.load(Ordering::SeqCst) {
let mut first_tx: Option<tokio::time::Instant> = None;
loop {
let msg = if let Some((interval, ref callsign)) = beacon_w {
match tokio::time::timeout(Duration::from_secs(1), conn_rx.recv()).await {
Ok(Some(msg)) => msg,
Ok(None) => break,
Err(_) => {
if first_tx.is_none_or(|t| t.elapsed() < interval) {
continue;
}
tracing::debug!(
"BLE RNode (native) transmitting station-ID beacon"
);
NativeBridgeWrite::Packet(callsign.clone())
}
}
} else {
match conn_rx.recv().await {
Some(msg) => msg,
None => break,
}
};
match msg {
NativeBridgeWrite::Packet(data) => {
if let Some((_, ref callsign)) = beacon_w {
if data == *callsign {
first_tx = None;
} else if first_tx.is_none() {
first_tx = Some(tokio::time::Instant::now());
}
}
txb_w.fetch_add(data.len() as u64, Ordering::Relaxed);
if flow_control {
while !ready_w.load(Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(10)).await;
if !online_w.load(Ordering::SeqCst) {
return;
}
}
}
let framed = kiss::frame(&data);
if let Err(e) = tcp_write.write_all(&framed).await {
tracing::warn!(error = %e, "BLE RNode native write error");
online_w.store(false, Ordering::SeqCst);
return;
}
}
}
let framed = kiss::frame(&data);
if let Err(e) = tcp_write.write_all(&framed).await {
tracing::warn!(error = %e, "BLE RNode native write error");
online_w.store(false, Ordering::SeqCst);
return;
NativeBridgeWrite::Raw(data) => {
if let Err(e) = tcp_write.write_all(&data).await {
tracing::warn!(error = %e, "BLE RNode native raw write error");
}
let _ = tcp_write.flush().await;
return;
}
}
}
});
@@ -1554,7 +1734,7 @@ pub async fn spawn_ble_rnode_interface_native(
let fwd_handle = tokio::spawn(async move {
let mut guard = rx_ref.lock().await;
while let Some(data) = guard.recv().await {
if conn_tx.send(data).await.is_err() {
if conn_tx.send(NativeBridgeWrite::Packet(data)).await.is_err() {
break;
}
}
@@ -1567,7 +1747,14 @@ pub async fn spawn_ble_rnode_interface_native(
let mut transport_closed = false;
'read: loop {
if !online_handle.load(Ordering::SeqCst) || !running_task.load(Ordering::SeqCst) {
if !online_handle.load(Ordering::SeqCst) {
break 'read;
}
if !running_task.load(Ordering::SeqCst) {
let _ = conn_tx_for_stop
.send(NativeBridgeWrite::Raw(rnode::build_detach_sequence()))
.await;
tokio::time::sleep(Duration::from_millis(100)).await;
break 'read;
}
@@ -1589,6 +1776,10 @@ pub async fn spawn_ble_rnode_interface_native(
// Idle LoRa silence is normal — only break if
// shutdown flag cleared.
if !running_task.load(Ordering::SeqCst) {
let _ = conn_tx_for_stop
.send(NativeBridgeWrite::Raw(rnode::build_detach_sequence()))
.await;
tokio::time::sleep(Duration::from_millis(100)).await;
break 'read;
}
continue;
@@ -1648,6 +1839,7 @@ pub async fn spawn_ble_rnode_interface_native(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -1682,7 +1874,10 @@ mod tests {
assert_eq!(cfg.spreading_factor, 7);
assert_eq!(cfg.coding_rate, 5);
assert_eq!(cfg.tx_power, 14);
assert!(cfg.flow_control);
assert!(
!cfg.flow_control,
"flow_control defaults off (Python parity)"
);
assert!(cfg.st_alock.is_none());
assert!(cfg.lt_alock.is_none());
}
@@ -1972,28 +2167,29 @@ mod tests {
// ── Init sequence tests ──
fn frame_command_count(frames: &[(u8, Vec<u8>)], command: u8) -> usize {
frames.iter().filter(|(cmd, _)| *cmd == command).count()
}
#[test]
fn test_ble_init_sequence_uses_rnode_helpers() {
let ble_cfg = BleRNodeConfig::new("ble0", "ble://RNode 1234");
let rnode_cfg = rnode::RNodeConfig {
name: ble_cfg.name.clone(),
port: ble_cfg.ble_uri.clone(),
baud_rate: 0,
frequency: ble_cfg.frequency,
bandwidth: ble_cfg.bandwidth,
spreading_factor: ble_cfg.spreading_factor,
coding_rate: ble_cfg.coding_rate,
tx_power: ble_cfg.tx_power,
mode: ble_cfg.mode,
flow_control: ble_cfg.flow_control,
st_alock: ble_cfg.st_alock,
lt_alock: ble_cfg.lt_alock,
};
let seq = rnode::build_init_sequence(&rnode_cfg);
let rnode_cfg = rnode_config_from_ble_config(&ble_cfg);
let seq = build_ble_rnode_init_sequence(&ble_cfg);
assert!(!seq.is_empty());
assert_eq!(seq, rnode::build_init_sequence(&rnode_cfg));
let mut deframer = kiss::RawKissDeframer::new();
let frames = deframer.feed(&seq);
assert_eq!(frames.len(), 6);
assert_eq!(frames.len(), 7);
assert_eq!(
frames[0],
(rnode::CMD_RADIO_STATE, vec![rnode::RADIO_STATE_OFF])
);
assert_eq!(
frames.last().unwrap(),
&(rnode::CMD_RADIO_STATE, vec![rnode::RADIO_STATE_ON])
);
}
#[test]
@@ -2006,15 +2202,36 @@ mod tests {
#[test]
fn test_ble_full_init_with_airtime() {
let mut rnode_cfg = rnode::RNodeConfig::new("test", "ble://");
rnode_cfg.st_alock = Some(25.0);
rnode_cfg.lt_alock = Some(50.0);
let mut seq = rnode::build_init_sequence(&rnode_cfg);
seq.extend_from_slice(&rnode::build_airtime_sequence(&rnode_cfg));
let mut cfg = BleRNodeConfig::new("test", "ble://");
cfg.st_alock = Some(25.0);
cfg.lt_alock = Some(50.0);
// Airtime locks are part of the init sequence, before RADIO_STATE_ON.
let seq = build_ble_rnode_init_sequence(&cfg);
let mut deframer = kiss::RawKissDeframer::new();
let frames = deframer.feed(&seq);
assert_eq!(frames.len(), 8); // 6 init + 2 airtime
assert_eq!(frames.len(), 9);
assert_eq!(
frames[0],
(rnode::CMD_RADIO_STATE, vec![rnode::RADIO_STATE_OFF])
);
assert_eq!(
frames.last().unwrap(),
&(rnode::CMD_RADIO_STATE, vec![rnode::RADIO_STATE_ON])
);
assert_eq!(frame_command_count(&frames, rnode::CMD_ST_ALOCK), 1);
assert_eq!(frame_command_count(&frames, rnode::CMD_LT_ALOCK), 1);
let radio_on = frames.len() - 1;
let st = frames
.iter()
.position(|(cmd, _)| *cmd == rnode::CMD_ST_ALOCK)
.expect("CMD_ST_ALOCK present");
let lt = frames
.iter()
.position(|(cmd, _)| *cmd == rnode::CMD_LT_ALOCK)
.expect("CMD_LT_ALOCK present");
assert!(st < radio_on);
assert!(lt < radio_on);
}
// ── process_rnode_response tests ──
@@ -2055,7 +2272,7 @@ mod tests {
fn test_response_rssi_updates() {
let mut rssi = None;
let mut snr = None;
rnode::process_rnode_response(rnode::CMD_STAT_RSSI, &[0xBF], 1, &mut rssi, &mut snr);
rnode::process_rnode_response(rnode::CMD_STAT_RSSI, &[92], 1, &mut rssi, &mut snr);
assert_eq!(rssi, Some(-65.0));
}
+128 -52
View File
@@ -262,6 +262,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)
}
@@ -344,8 +352,7 @@ pub async fn spawn_i2p_client(
let task_txb = shared_txb.clone();
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);
loop {
let session_id = generate_session_id();
@@ -358,12 +365,14 @@ 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;
}
};
@@ -377,11 +386,14 @@ pub async fn spawn_i2p_client(
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;
}
@@ -407,11 +419,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 +440,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 +461,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 +486,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;
}
@@ -480,8 +504,7 @@ pub async fn spawn_i2p_client(
);
online_task.store(true, Ordering::SeqCst);
tries = 0;
backoff = config.reconnect_delay;
pacer.reset();
// BufReader may have prefetched past the handshake; flush its tail first.
let buffered = stream_buf_reader.buffer().to_vec();
@@ -526,25 +549,25 @@ 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,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -738,6 +761,7 @@ pub async fn spawn_i2p_server(
let handle = InterfaceHandle {
id: client_id,
parent_id: Some(0),
name: client_name,
mode: config.mode,
direction: InterfaceDirection {
@@ -774,6 +798,7 @@ pub async fn spawn_i2p_server(
Ok(InterfaceHandle {
id: 0,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -863,13 +888,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;
}
}
@@ -997,24 +1060,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]
+14 -65
View File
@@ -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();
}
}
@@ -221,6 +165,7 @@ pub struct RawKissDeframer {
buffer: Vec<u8>,
in_frame: bool,
command: u8,
/// Reusable scratch for unescape output.
unescape_scratch: Vec<u8>,
}
@@ -270,6 +215,10 @@ 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 {
+79 -35
View File
@@ -28,6 +28,10 @@ pub struct KissInterfaceConfig {
pub txtail: Option<u8>,
/// Honour CMD_READY from TNC.
pub flow_control: bool,
/// Station-ID beacon: seconds between IDs, counted from the first data
/// TX after the previous beacon (Python `id_interval`/`id_callsign`).
pub id_interval: Option<u64>,
pub id_callsign: Option<Vec<u8>>,
}
impl KissInterfaceConfig {
@@ -45,10 +49,22 @@ 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.py:350-353).
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,
@@ -113,9 +129,49 @@ 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 {
// 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 data = 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 rx.recv().await {
Some(data) => data,
None => break,
}
};
// 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);
// Flow control: bounded wait so a stuck TNC can't hang transmit.
if flow_control {
@@ -132,25 +188,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 +213,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 +251,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 +262,7 @@ pub async fn spawn_kiss_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -261,6 +291,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]
+4 -1
View File
@@ -1,6 +1,7 @@
//! 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.
//! concrete transport; [`traits::InterfaceHandle`] is the common handle the
//! runtime registers with the transport actor.
#[cfg(target_os = "android")]
pub mod android_usb;
@@ -32,6 +33,8 @@ pub mod rnode_admin;
pub mod rnode_multi;
#[cfg(feature = "serial")]
pub mod serial;
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
mod serial_io;
pub mod socket_tuning;
pub mod tcp;
pub mod traits;
+124 -192
View File
@@ -148,6 +148,94 @@ async fn local_write_loop<W: AsyncWriteExt + Unpin>(
online.store(false, Ordering::SeqCst);
}
/// 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 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,
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),
tx,
read_task,
}
}
/// Handle for the listener pseudo-interface (id 0): inbound-only, no
/// per-byte counters of its own.
fn server_listener_handle(
name: String,
online: Arc<AtomicBool>,
tx: mpsc::Sender<Bytes>,
read_task: tokio::task::JoinHandle<()>,
) -> InterfaceHandle {
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(Arc::new(AtomicU64::new(0))),
txb: Some(Arc::new(AtomicU64::new(0))),
tx,
read_task,
}
}
#[cfg(unix)]
mod platform {
use super::*;
@@ -238,49 +326,16 @@ 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,
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,
};
let handle = wire_local_stream(
client_id,
client_name,
Some(0),
reader,
writer,
transport_tx.clone(),
true,
);
if handle_tx.send(handle).await.is_err() {
tracing::warn!("local handle registry closed");
break;
@@ -295,27 +350,7 @@ 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,
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(name, online, tx, read_task))
}
pub async fn spawn_local_client_impl(
@@ -326,41 +361,16 @@ mod platform {
let stream = connect_unix_stream(&config.socket_path).await?;
tracing::info!(name = %config.name, path = %display_socket_path(&config.socket_path), "local client connected");
let online = Arc::new(AtomicBool::new(true));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let (tx, rx) = mpsc::channel::<Bytes>(256);
let (reader, writer) = stream.into_split();
let online_w = online.clone();
let task_txb = shared_txb.clone();
tokio::spawn(local_write_loop(writer, rx, online_w, task_txb));
let online_r = online.clone();
let task_rxb = shared_rxb.clone();
let name = config.name.clone();
let read_task = tokio::spawn(async move {
local_read_loop(reader, id, transport_tx, online_r, task_rxb).await;
});
Ok(InterfaceHandle {
Ok(wire_local_stream(
id,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
tx,
read_task,
})
config.name.clone(),
None,
reader,
writer,
transport_tx,
false,
))
}
}
@@ -404,49 +414,16 @@ 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,
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,
};
let handle = wire_local_stream(
client_id,
client_name,
Some(0),
reader,
writer,
transport_tx.clone(),
true,
);
if handle_tx.send(handle).await.is_err() {
tracing::warn!("local handle registry closed");
break;
@@ -461,27 +438,7 @@ 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,
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(name, online, tx, read_task))
}
pub async fn spawn_local_client_impl(
@@ -493,41 +450,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,
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,
))
}
}
+1
View File
@@ -189,6 +189,7 @@ pub async fn spawn_pipe_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
File diff suppressed because it is too large. Load diff
+178 -78
View File
@@ -176,6 +176,10 @@ pub struct RNodeMultiConfig {
pub flow_control: bool,
/// Up to `MAX_SUBINTERFACES` radios on this device.
pub subinterfaces: Vec<SubInterfaceConfig>,
/// Station-ID beacon, parent-level: when due, the callsign is sent on
/// all subinterfaces (Python RNodeMultiInterface.py:849-859).
pub id_interval: Option<u64>,
pub id_callsign: Option<Vec<u8>>,
}
impl RNodeMultiConfig {
@@ -186,6 +190,8 @@ impl RNodeMultiConfig {
baud_rate: 115200,
flow_control: false,
subinterfaces: Vec::new(),
id_interval: None,
id_callsign: None,
}
}
}
@@ -265,13 +271,38 @@ struct SubInterfaceSignal {
last_snr: Option<f32>,
}
/// Device-level + per-sub online state shared by the writer and reader tasks.
#[derive(Clone)]
struct OnlineFlags {
device: Arc<AtomicBool>,
subs: Arc<Vec<Arc<AtomicBool>>>,
}
impl OnlineFlags {
/// Device failure takes every sub-interface down with it.
fn trip_device(&self) {
self.device.store(false, Ordering::SeqCst);
for sub in self.subs.iter() {
sub.store(false, Ordering::SeqCst);
}
}
/// True while the device is up and at least one sub remains registered —
/// once false the shared reader exits and releases the serial port.
fn device_running(&self) -> bool {
self.device.load(Ordering::SeqCst) && self.subs.iter().any(|sub| sub.load(Ordering::SeqCst))
}
}
const RNODE_READ_TIMEOUT_MS: u64 = 100;
/// Spawn one RNodeMulti over a single serial port.
///
/// Returns one `InterfaceHandle` per configured sub-interface. Each handle has
/// its own tx channel and `InterfaceId`; all of them share one serial
/// connection and one online flag, so the whole device goes up or down atomically.
/// its own tx channel, `InterfaceId`, and online flag; all of them share one
/// serial connection. Tearing down one sub leaves the others running; the
/// shared reader exits (releasing the port) when the device fails or every
/// sub has been deregistered.
///
/// `ids.len()` must equal `config.subinterfaces.len()`.
pub async fn spawn_rnode_multi_interface(
@@ -351,6 +382,19 @@ pub async fn spawn_rnode_multi_interface(
let num_subs = config.subinterfaces.len();
// Per-sub online flags: deregistering one sub must not kill the shared
// device, but the reader must release the serial port once ALL subs are
// gone; device-level failure trips every sub flag.
let sub_onlines: Arc<Vec<Arc<AtomicBool>>> = Arc::new(
(0..num_subs)
.map(|_| Arc::new(AtomicBool::new(true)))
.collect(),
);
let flags = OnlineFlags {
device: online.clone(),
subs: sub_onlines.clone(),
};
// All sub-interface handles funnel into one writer so CMD_SEL_INT framing
// stays ordered relative to each data frame.
let (write_tx, mut write_rx) = mpsc::channel::<WriteRequest>(256);
@@ -410,11 +454,12 @@ pub async fn spawn_rnode_multi_interface(
);
// The real read loop is shared by all sub-interfaces; each handle just
// needs a JoinHandle that exits when the device goes offline.
let online_sub = online.clone();
// needs a JoinHandle that exits when its sub or the device goes offline.
let online_sub = sub_onlines[i].clone();
let device_sub = online.clone();
let sub_read_task = tokio::spawn(async move {
loop {
if !online_sub.load(Ordering::SeqCst) {
if !online_sub.load(Ordering::SeqCst) || !device_sub.load(Ordering::SeqCst) {
break;
}
tokio::time::sleep(Duration::from_millis(500)).await;
@@ -423,6 +468,7 @@ pub async fn spawn_rnode_multi_interface(
handles.push(InterfaceHandle {
id: ids[i],
parent_id: None,
name: sub_name,
mode: sub_cfg.mode,
direction: InterfaceDirection {
@@ -433,7 +479,7 @@ pub async fn spawn_rnode_multi_interface(
},
bitrate,
mtu: rns_wire::constants::MTU as u32,
online: online.clone(),
online: sub_onlines[i].clone(),
rxb: Some(rxb),
txb: Some(txb),
tx: sub_tx,
@@ -448,15 +494,81 @@ pub async fn spawn_rnode_multi_interface(
.try_clone()
.map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti clone: {}", e)))?;
let online_w = online.clone();
let flags_w = flags.clone();
let ready = Arc::new(AtomicBool::new(true));
let ready_w = ready.clone();
// Python RNodeMultiInterface.py:281-291 — oversized callsigns disable
// beaconing; when due, the callsign goes out on all subinterfaces.
let beacon: Option<(Duration, Bytes)> = config
.id_interval
.zip(config.id_callsign.clone())
.filter(|(_, callsign)| {
let ok = callsign.len() <= rnode::CALLSIGN_MAX_LEN;
if !ok {
tracing::error!(
name = %config.name,
len = callsign.len(),
"id_callsign exceeds {} bytes, beaconing disabled",
rnode::CALLSIGN_MAX_LEN
);
}
ok
})
.map(|(interval, callsign)| (Duration::from_secs(interval), Bytes::from(callsign)));
let beacon_vports: Vec<u8> = config.subinterfaces.iter().map(|s| s.vport).collect();
tokio::spawn(async move {
let mut port_w = port_write;
while let Some(req) = write_rx.recv().await {
let mut first_tx: Option<tokio::time::Instant> = None;
loop {
let req = if let Some((interval, ref callsign)) = beacon {
match tokio::time::timeout(Duration::from_secs(1), write_rx.recv()).await {
Ok(Some(req)) => req,
Ok(None) => break,
Err(_) => {
if first_tx.is_none_or(|t| t.elapsed() < interval)
|| !online_w.load(Ordering::SeqCst)
{
continue;
}
tracing::debug!(
"RNodeMulti transmitting station-ID beacon on all subinterfaces"
);
first_tx = None;
let mut frames = Vec::new();
for &vport in &beacon_vports {
frames
.extend_from_slice(&build_subinterface_data_frame(vport, callsign));
}
match crate::serial_io::blocking_write_all(port_w, frames).await {
Ok(p) => {
port_w = p;
continue;
}
Err(_) => {
flags_w.trip_device();
break;
}
}
}
}
} else {
match write_rx.recv().await {
Some(req) => req,
None => break,
}
};
if !online_w.load(Ordering::SeqCst) {
break;
}
if let Some((_, ref callsign)) = beacon {
if req.data == *callsign {
first_tx = None;
} else if first_tx.is_none() {
first_tx = Some(tokio::time::Instant::now());
}
}
if req.flow_control {
// Bound CMD_READY wait at ~5 s so a stuck TNC can't block tx.
@@ -471,32 +583,20 @@ pub async fn spawn_rnode_multi_interface(
}
let frame = build_subinterface_data_frame(req.index, &req.data);
let online_ref = online_w.clone();
let result = tokio::task::spawn_blocking(move || {
use std::io::Write;
port_w.write_all(&frame)?;
port_w.flush()?;
Ok::<_, std::io::Error>(port_w)
})
.await;
match result {
Ok(Ok(p)) => {
match crate::serial_io::blocking_write_all(port_w, frame).await {
Ok(p) => {
port_w = p;
}
Ok(Err(e)) => {
tracing::warn!(error = %e, "RNodeMulti write error");
online_ref.store(false, Ordering::SeqCst);
break;
}
Err(e) => {
tracing::warn!(error = %e, "RNodeMulti write task panicked");
tracing::warn!(error = %e, "RNodeMulti write error");
flags_w.trip_device();
break;
}
}
}
});
let online_r = online.clone();
let flags_r = flags;
let ready_r = ready;
let parent_name = config.name.clone();
@@ -527,22 +627,12 @@ pub async fn spawn_rnode_multi_interface(
let mut interfaces_buf: Vec<u8> = Vec::new();
loop {
if !online_r.load(Ordering::SeqCst) {
if !flags_r.device_running() {
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 {
@@ -572,7 +662,7 @@ pub async fn spawn_rnode_multi_interface(
parent = %parent_name,
"transport channel closed"
);
online_r.store(false, Ordering::SeqCst);
flags_r.trip_device();
return;
}
} else {
@@ -596,7 +686,7 @@ pub async fn spawn_rnode_multi_interface(
rnode::CMD_STAT_RSSI => {
if !frame.is_empty() {
let rssi = frame[0] as i8 as f32;
let rssi = rnode::decode_rssi_byte(frame[0]);
if let Some(local_idx) =
vport_map.get(selected_index).copied().flatten()
{
@@ -606,7 +696,7 @@ pub async fn spawn_rnode_multi_interface(
}
rnode::CMD_STAT_SNR => {
if !frame.is_empty() {
let snr = frame[0] as i8 as f32 / 4.0;
let snr = rnode::decode_snr_byte(frame[0]);
if let Some(local_idx) =
vport_map.get(selected_index).copied().flatten()
{
@@ -801,39 +891,16 @@ pub async fn spawn_rnode_multi_interface(
}
}
CMD_ERROR => {
if !frame.is_empty() {
match frame[0] {
ERROR_INITRADIO => {
tracing::error!(
parent = %parent_name,
"RNodeMulti hardware initialisation error"
);
}
ERROR_TXFAILED => {
tracing::error!(
parent = %parent_name,
"RNodeMulti hardware TX error"
);
}
code => {
tracing::error!(
parent = %parent_name,
code = format!("0x{:02X}", code),
"RNodeMulti hardware error"
);
}
}
}
}
// No CMD_ERROR arm: 0x90 collides with CMD_INT5_DATA
// and is consumed by the vport demux above — same
// collision as Python RNodeMultiInterface.
rnode::CMD_RESET => {
if frame.first().copied() == Some(0xF8) {
tracing::error!(
parent = %parent_name,
"RNodeMulti device reset detected"
);
online_r.store(false, Ordering::SeqCst);
flags_r.trip_device();
return;
}
}
@@ -848,22 +915,13 @@ pub async fn spawn_rnode_multi_interface(
}
}
}
Ok(Err((_p, e))) => {
Err(e) => {
tracing::warn!(
parent = %parent_name,
error = %e,
"RNodeMulti read error"
);
online_r.store(false, Ordering::SeqCst);
return;
}
Err(e) => {
tracing::warn!(
parent = %parent_name,
error = %e,
"RNodeMulti read task panicked"
);
online_r.store(false, Ordering::SeqCst);
flags_r.trip_device();
return;
}
}
@@ -893,6 +951,48 @@ mod tests {
assert!(cfg.subinterfaces.iter().all(|sub| !sub.flow_control));
}
/// T1-3: the shared serial reader runs while the device is up and at
/// least one sub-interface remains registered. Deregistering one sub
/// must NOT stop the device; deregistering all must (port release);
/// device failure trips every sub flag.
#[test]
fn test_online_flags_reader_exit_semantics() {
let flags = OnlineFlags {
device: Arc::new(AtomicBool::new(true)),
subs: Arc::new(vec![
Arc::new(AtomicBool::new(true)),
Arc::new(AtomicBool::new(true)),
]),
};
assert!(flags.device_running());
// One sub deregistered (actor flips its flag): device keeps serving.
flags.subs[0].store(false, Ordering::SeqCst);
assert!(flags.device_running());
// Last sub deregistered: reader must exit and release the port.
flags.subs[1].store(false, Ordering::SeqCst);
assert!(!flags.device_running());
// Device failure path: every sub flag goes down with the device.
let flags2 = OnlineFlags {
device: Arc::new(AtomicBool::new(true)),
subs: Arc::new(vec![Arc::new(AtomicBool::new(true))]),
};
flags2.trip_device();
assert!(!flags2.device.load(Ordering::SeqCst));
assert!(!flags2.subs[0].load(Ordering::SeqCst));
assert!(!flags2.device_running());
}
/// The multi reader decodes STAT_RSSI/STAT_SNR via the shared rnode
/// helpers — Python formula: RSSI = raw byte − 157, SNR = signed × 0.25.
#[test]
fn test_multi_rssi_snr_decode_matches_python() {
assert_eq!(rnode::decode_rssi_byte(67), -90.0);
assert_eq!(rnode::decode_snr_byte(0xF6), -2.5);
}
#[test]
fn test_subinterface_init_sequence() {
let sub_cfg = SubInterfaceConfig::new("radio0", 0, 868_000_000);
+38 -34
View File
@@ -46,6 +46,36 @@ 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,
@@ -84,25 +114,13 @@ pub async fn spawn_serial_interface(
while let Some(data) = rx.recv().await {
txb_w.fetch_add(data.len() as u64, std::sync::atomic::Ordering::Relaxed);
let framed = hdlc::frame(&data);
let online_ref = online_w.clone();
let result = tokio::task::spawn_blocking(move || {
use std::io::Write;
port_w.write_all(&framed)?;
port_w.flush()?;
Ok::<_, std::io::Error>(port_w)
})
.await;
match result {
Ok(Ok(p)) => {
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 +138,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 +163,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 +174,7 @@ pub async fn spawn_serial_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
+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)),
}
}
+102 -54
View File
@@ -1,61 +1,77 @@
//! Shared TCP socket tuning for [`crate::tcp`] and [`crate::backbone`].
//! Shared TCP socket tuning for [`crate::tcp`], [`crate::backbone`],
//! [`crate::i2p`], and [`crate::rnode`] (TCP transport).
//! `set_keepalive`: portable SO_KEEPALIVE. `set_keepalive_tuned`: adds Linux
//! TCP_KEEPIDLE/INTVL/CNT + TCP_USER_TIMEOUT.
//! TCP_KEEPIDLE/INTVL/CNT + TCP_USER_TIMEOUT. All helpers are generic over
//! the raw-fd/raw-socket borrow, so they accept tokio and std streams alike.
//! `iface_addr_for`: kernel iface name → IpAddr for Backbone `device =` key.
use std::net::IpAddr;
use std::time::Duration;
use tokio::net::TcpStream;
/// Enable portable `SO_KEEPALIVE`; for tuned, use [`set_keepalive_tuned`].
/// 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)
}
/// Platform bound for streams the tuning helpers accept: anything exposing
/// the raw socket handle (tokio `TcpStream`, std `TcpStream`, …).
#[cfg(unix)]
pub trait RawStream: std::os::fd::AsRawFd {}
#[cfg(unix)]
impl<T: std::os::fd::AsRawFd> RawStream for T {}
#[cfg(windows)]
pub trait RawStream: std::os::windows::io::AsRawSocket {}
#[cfg(windows)]
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))
}
/// Tuned keepalive: idle/interval/retries + Linux TCP_USER_TIMEOUT. Best-effort.
#[cfg(unix)]
pub fn set_keepalive_tuned(
stream: &TcpStream,
pub fn set_keepalive_tuned<S: RawStream>(
stream: &S,
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);
with_socket2(stream, |sock| {
apply_tuned_keepalive(sock, idle, intvl, retries, user_timeout)
});
}
#[cfg(windows)]
pub fn set_keepalive_tuned(
stream: &TcpStream,
idle: Duration,
intvl: Duration,
retries: u32,
user_timeout: Duration,
) {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_ref().as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
/// Raise TCP send/recv buffers; best-effort.
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(
@@ -88,23 +104,24 @@ 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);
}
#[cfg(windows)]
pub fn set_socket_buffers(stream: &TcpStream, size: usize) {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_ref().as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
let _ = sock.set_recv_buffer_size(size);
let _ = sock.set_send_buffer_size(size);
/// Resolve interface name to 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
}
})
}
/// Resolve interface name to `IpAddr`; `None` if missing. Caller falls back
@@ -143,7 +160,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() {
@@ -177,6 +194,37 @@ 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();
let addr = listener.local_addr().unwrap();
let accept = std::thread::spawn(move || listener.accept().unwrap().0);
let client = std::net::TcpStream::connect(addr).unwrap();
let server = accept.join().unwrap();
set_keepalive(&server).expect("server set_keepalive");
set_keepalive(&client).expect("client set_keepalive");
set_keepalive_tuned(
&server,
Duration::from_secs(5),
Duration::from_secs(2),
12,
Duration::from_secs(24),
);
set_keepalive_tuned(
&client,
Duration::from_secs(5),
Duration::from_secs(2),
12,
Duration::from_secs(24),
);
set_socket_buffers(&server, 131_072);
set_socket_buffers(&client, 131_072);
}
#[test]
fn iface_addr_for_loopback_resolves() {
// Loopback name varies by OS; iterate candidates.
+169 -34
View File
@@ -15,15 +15,27 @@ 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;
/// Tuned keepalive (idle/interval/count + Linux `TCP_USER_TIMEOUT`) for plain
/// TCP client and accepted sockets, matching Python `set_timeouts_linux`.
pub(crate) fn set_tcp_keepalive_tuned(stream: &TcpStream) {
crate::socket_tuning::set_keepalive_tuned(
stream,
std::time::Duration::from_secs(TCP_KEEPIDLE as u64),
std::time::Duration::from_secs(TCP_KEEPINTVL as u64),
TCP_KEEPCNT,
std::time::Duration::from_secs(DEFAULT_TCP_USER_TIMEOUT as u64),
);
}
#[derive(Debug, Clone)]
pub struct TcpClientConfig {
pub name: String,
@@ -33,6 +45,8 @@ pub struct TcpClientConfig {
pub connect_timeout_secs: u64,
pub max_reconnect_tries: Option<usize>,
pub mode: InterfaceMode,
/// Override HW MTU for link MTU discovery (Python `fixed_mtu`, >= 500).
pub fixed_mtu: Option<u32>,
}
impl TcpClientConfig {
@@ -45,6 +59,7 @@ impl TcpClientConfig {
connect_timeout_secs: DEFAULT_CONNECT_TIMEOUT,
max_reconnect_tries: None,
mode: InterfaceMode::Full,
fixed_mtu: None,
}
}
}
@@ -57,6 +72,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 +86,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 +124,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,7 +175,7 @@ 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,
@@ -261,12 +285,12 @@ 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 online = Arc::new(AtomicBool::new(false));
let online2 = online.clone();
@@ -274,6 +298,7 @@ pub async fn spawn_tcp_client(
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));
@@ -303,6 +328,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 +346,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 +358,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);
// Nagle off for low-latency packets; larger buffers for bulk transfers.
let _ = stream.set_nodelay(true);
@@ -391,6 +422,7 @@ pub async fn spawn_tcp_client(
let bitrate: u64 = 10_000_000;
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -400,7 +432,8 @@ 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),
@@ -419,6 +452,7 @@ pub async fn spawn_tcp_client(
async fn spawn_tcp_accepted(
stream: TcpStream,
id: InterfaceId,
parent_id: InterfaceId,
name: String,
transport_tx: mpsc::Sender<TransportMessage>,
kiss_framing: bool,
@@ -433,9 +467,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);
let _ = stream.set_nodelay(true);
set_socket_buffers(&stream, 131072);
@@ -459,6 +491,7 @@ async fn spawn_tcp_accepted(
let bitrate: u64 = 10_000_000;
InterfaceHandle {
id,
parent_id: Some(parent_id),
name,
mode,
direction: InterfaceDirection {
@@ -486,7 +519,17 @@ 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 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");
@@ -510,6 +553,7 @@ pub async fn spawn_tcp_server(
let handle = spawn_tcp_accepted(
stream,
client_id,
id,
client_name,
transport_tx.clone(),
kiss_framing,
@@ -533,6 +577,7 @@ pub async fn spawn_tcp_server(
let bitrate: u64 = 10_000_000;
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -570,6 +615,95 @@ mod tests {
assert!(!config.prefer_ipv6);
}
/// T1-2 regression: the client/accept paths must apply the TUNED keepalive
/// (idle 5s + 12 probes × 2s ≈ 29s dead-peer parity with Python), not just
/// SO_KEEPALIVE. Reads the options back via getsockopt.
#[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 stream in [&client, &server] {
set_tcp_keepalive_tuned(stream);
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, TCP_KEEPIDLE as i32);
assert_eq!(
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPINTVL),
TCP_KEEPINTVL as i32
);
assert_eq!(
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPCNT),
TCP_KEEPCNT as i32
);
}
#[cfg(target_os = "linux")]
assert_eq!(
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_USER_TIMEOUT),
(DEFAULT_TCP_USER_TIMEOUT * 1000) as i32
);
}
}
/// 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();
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 msg {
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";
@@ -629,8 +763,9 @@ mod tests {
connect_timeout_secs: 5,
max_reconnect_tries: Some(1),
mode: InterfaceMode::Full,
fixed_mtu: 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();
@@ -713,11 +848,10 @@ mod tests {
connect_timeout_secs: 1,
max_reconnect_tries: Some(2),
mode: InterfaceMode::Full,
fixed_mtu: None,
};
let handle = spawn_tcp_client(config, 99, transport_tx, None)
.await
.unwrap();
let handle = spawn_tcp_client(config, 99, transport_tx).await.unwrap();
// Two failed tries with 5s waits each; 20s headroom.
let result =
@@ -756,8 +890,9 @@ mod tests {
connect_timeout_secs: 5,
max_reconnect_tries: Some(1),
mode: InterfaceMode::Full,
fixed_mtu: 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();
+53 -62
View File
@@ -9,6 +9,9 @@ pub type InterfaceId = u64;
/// Handle returned by every `spawn_*`: write channel, status flag, and read task.
pub struct InterfaceHandle {
pub id: InterfaceId,
/// Parent interface for dynamically spawned children such as accepted TCP,
/// Backbone or I2P peers.
pub parent_id: Option<InterfaceId>,
pub name: String,
pub mode: InterfaceMode,
pub direction: InterfaceDirection,
@@ -21,12 +24,6 @@ pub struct InterfaceHandle {
pub read_task: tokio::task::JoinHandle<()>,
}
/// Optional per-interface IFAC (Interface Authentication Code) configuration.
pub struct IfacConfig {
pub ifac_key: [u8; 64],
pub ifac_size: usize,
}
/// Interface operating mode. Byte values are on-wire constants.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
@@ -39,6 +36,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;
@@ -54,6 +53,7 @@ pub const DISCOVER_PATHS_FOR: &[InterfaceMode] = &[
InterfaceMode::AccessPoint,
InterfaceMode::Gateway,
InterfaceMode::Roaming,
InterfaceMode::Internal,
];
impl InterfaceMode {
@@ -65,6 +65,7 @@ impl InterfaceMode {
0x04 => Some(Self::Roaming),
0x05 => Some(Self::Boundary),
0x06 => Some(Self::Gateway),
0x07 => Some(Self::Internal),
_ => None,
}
}
@@ -79,50 +80,6 @@ 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.
pub fn optimise_mtu(bitrate: u64) -> Option<u32> {
if bitrate >= 1_000_000_000 {
@@ -154,21 +111,39 @@ pub fn optimise_mtu(bitrate: u64) -> Option<u32> {
pub const NAME_HASH_LENGTH: usize = 10;
// Ingress control constants — must match Reticulum reference.
pub const IA_FREQ_SAMPLES: usize = 128;
pub const OA_FREQ_SAMPLES: usize = 128;
pub const IA_FREQ_SAMPLES: usize = 48;
pub const OA_FREQ_SAMPLES: usize = 48;
pub const IP_FREQ_SAMPLES: usize = 48;
pub const OP_FREQ_SAMPLES: usize = 48;
pub const AR_MINFREQ_HZ: f64 = 0.1;
pub const PR_MINFREQ_HZ: f64 = 0.1;
pub const AR_FREQ_DECAY: f64 = 1.0 / AR_MINFREQ_HZ;
pub const PR_FREQ_DECAY: f64 = 1.0 / PR_MINFREQ_HZ;
pub const MAX_HELD_ANNOUNCES: usize = 256;
/// Duration a new interface stays in "new" state (seconds).
pub const IC_NEW_TIME: f64 = 7200.0;
/// Burst threshold for new interfaces (announces/sec).
pub const IC_BURST_FREQ_NEW: f64 = 6.0;
pub const IC_BURST_FREQ_NEW: f64 = 3.0;
/// Burst threshold for established interfaces (announces/sec).
pub const IC_BURST_FREQ: f64 = 35.0;
pub const IC_BURST_FREQ: f64 = 10.0;
/// Burst threshold for new interfaces (path requests/sec).
pub const IC_PR_BURST_FREQ_NEW: f64 = 3.0;
/// Burst threshold for established interfaces (path requests/sec).
pub const IC_PR_BURST_FREQ: f64 = 8.0;
/// Burst detection window duration (seconds).
pub const IC_BURST_HOLD: f64 = 60.0;
pub const IC_BURST_HOLD: f64 = 15.0;
/// Penalty duration after a detected burst (seconds).
pub const IC_BURST_PENALTY: f64 = 15.0;
/// Interval between released held announces (seconds).
pub const IC_HELD_RELEASE_INTERVAL: f64 = 2.0;
pub const IC_HELD_RELEASE_INTERVAL: f64 = 5.0;
/// Minimum samples required before incoming frequency is considered defined.
pub const IC_DEQUE_MIN_SAMPLE: usize = 2;
/// Minimum samples required for burst clearing / PR egress limiting.
pub const IC_BURST_MIN_SAMPLES: usize = 6;
/// Optional outgoing path-request limiter threshold (requests/sec).
pub const EC_PR_FREQ: f64 = 5.0;
/// Whether outgoing path-request limiting is active by default.
pub const EGRESS_CONTROL: bool = false;
#[derive(Debug, thiserror::Error)]
pub enum InterfaceError {
@@ -203,6 +178,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]
@@ -213,7 +189,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);
}
@@ -228,6 +206,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));
}
@@ -239,13 +218,25 @@ mod tests {
#[test]
fn test_ingress_control_constants() {
assert_eq!(IA_FREQ_SAMPLES, 128);
assert_eq!(OA_FREQ_SAMPLES, 128);
assert_eq!(IC_BURST_FREQ, 35.0);
assert_eq!(IC_BURST_FREQ_NEW, 6.0);
assert_eq!(IC_BURST_HOLD, 60.0);
assert_eq!(IA_FREQ_SAMPLES, 48);
assert_eq!(OA_FREQ_SAMPLES, 48);
assert_eq!(IP_FREQ_SAMPLES, 48);
assert_eq!(OP_FREQ_SAMPLES, 48);
assert_eq!(AR_MINFREQ_HZ, 0.1);
assert_eq!(PR_MINFREQ_HZ, 0.1);
assert_eq!(AR_FREQ_DECAY, 10.0);
assert_eq!(PR_FREQ_DECAY, 10.0);
assert_eq!(IC_BURST_FREQ, 10.0);
assert_eq!(IC_BURST_FREQ_NEW, 3.0);
assert_eq!(IC_PR_BURST_FREQ, 8.0);
assert_eq!(IC_PR_BURST_FREQ_NEW, 3.0);
assert_eq!(IC_BURST_HOLD, 15.0);
assert_eq!(IC_BURST_PENALTY, 15.0);
assert_eq!(IC_NEW_TIME, 7200.0);
assert_eq!(IC_HELD_RELEASE_INTERVAL, 2.0);
assert_eq!(IC_HELD_RELEASE_INTERVAL, 5.0);
assert_eq!(IC_DEQUE_MIN_SAMPLE, 2);
assert_eq!(IC_BURST_MIN_SAMPLES, 6);
assert_eq!(EC_PR_FREQ, 5.0);
const { assert!(!EGRESS_CONTROL) };
}
}
+56 -2
View File
@@ -54,7 +54,28 @@ 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");
// 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() {
if 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 +94,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 +166,7 @@ pub async fn spawn_udp_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -184,6 +206,38 @@ 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.read_task.abort();
}
#[test]
fn test_udp_config_defaults() {
let cfg = UdpInterfaceConfig::new("udp0");
+21
View File
@@ -58,6 +58,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 +114,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;
@@ -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());
+21 -6
View File
@@ -149,6 +149,17 @@ mod tests {
use super::*;
use std::thread;
fn instant_before_now(elapsed: Duration) -> Instant {
if let Some(instant) = Instant::now().checked_sub(elapsed) {
instant
} else {
thread::sleep(elapsed);
Instant::now()
.checked_sub(elapsed)
.expect("elapsed duration should be representable after waiting")
}
}
#[test]
fn test_rtt_scaling() {
let mut ks = KeepaliveState::new(true);
@@ -225,11 +236,13 @@ mod tests {
#[test]
fn test_jitter_desynchronizes_keepalives() {
let links: Vec<KeepaliveState> = (0..20)
.map(|_| {
.map(|i| {
let mut ks = KeepaliveState::new(true);
ks.update_from_rtt(Duration::from_millis(500));
ks.keepalive_interval = Duration::from_secs_f64(KEEPALIVE_MIN);
ks.jitter_offset = Duration::from_millis(500);
ks.jitter_negative = i % 2 == 0;
// Push last_inbound just past the interval boundary.
ks.last_inbound = Instant::now() - ks.keepalive_interval;
ks.last_inbound = instant_before_now(ks.keepalive_interval);
ks
})
.collect();
@@ -237,10 +250,12 @@ mod tests {
let firing: usize = links.iter().filter(|ks| ks.should_send_keepalive()).count();
let links_past: Vec<KeepaliveState> = (0..20)
.map(|_| {
.map(|i| {
let mut ks = KeepaliveState::new(true);
ks.update_from_rtt(Duration::from_millis(500));
ks.last_inbound = Instant::now() - ks.keepalive_interval * 2;
ks.keepalive_interval = Duration::from_secs_f64(KEEPALIVE_MIN);
ks.jitter_offset = Duration::from_millis(500);
ks.jitter_negative = i % 2 == 0;
ks.last_inbound = instant_before_now(Duration::from_secs(6));
ks
})
.collect();
+139 -55
View File
@@ -145,6 +145,9 @@ pub struct Link {
pub establishment_rate: Option<f64>,
/// Expected in-flight data rate (bits/sec), refreshed after each resource transfer.
pub expected_rate: Option<f64>,
/// Path length in hops: initiator sets it at creation (Link.py:282), the
/// destination side from the LRRTT packet at activation (Link.py:525).
pub expected_hops: Option<u8>,
pub destination_hash: [u8; 16],
@@ -238,6 +241,7 @@ impl Link {
establishment_cost,
establishment_rate: None,
expected_rate: None,
expected_hops: Some(hops),
destination_hash,
remote_identity_pub: None,
identified: false,
@@ -385,6 +389,49 @@ impl Link {
destination_hash: [u8; 16],
hops: u8,
) -> Result<(Self, Vec<u8>), HandshakeError> {
let identity_ed25519_pub = identity_signing_key.public_key().to_bytes();
Self::new_responder_inner(
request_data,
&identity_ed25519_pub,
destination_hash,
hops,
Some(identity_signing_key),
|signed_data| Some(identity_signing_key.sign(signed_data)),
)
}
/// Create an inbound link proof using an external signer (e.g. YubiKey/PIV).
pub fn new_responder_with<F>(
request_data: &[u8],
identity_ed25519_pub: &[u8; 32],
destination_hash: [u8; 16],
hops: u8,
sign_fn: F,
) -> Result<(Self, Vec<u8>), HandshakeError>
where
F: FnOnce(&[u8]) -> Option<[u8; 64]>,
{
Self::new_responder_inner(
request_data,
identity_ed25519_pub,
destination_hash,
hops,
None,
sign_fn,
)
}
fn new_responder_inner<F>(
request_data: &[u8],
identity_ed25519_pub: &[u8; 32],
destination_hash: [u8; 16],
hops: u8,
identity_signing_key: Option<&Ed25519PrivateKey>,
sign_fn: F,
) -> Result<(Self, Vec<u8>), HandshakeError>
where
F: FnOnce(&[u8]) -> Option<[u8; 64]>,
{
let request = LinkRequestData::unpack(request_data)?;
let link_id = compute_link_id(&destination_hash, request_data);
@@ -404,16 +451,21 @@ impl Link {
// The proof binds the link to the responder's long-term identity key, not
// its ephemeral one — that's what lets the initiator authenticate us.
let identity_ed25519_pub = identity_signing_key.public_key().to_bytes();
let signalling =
SignallingData::new(request.signalling.mode, rns_wire::constants::MTU as u32);
let proof = LinkProofData::create(
identity_signing_key,
&responder_keys.x25519_pub.to_bytes(),
&identity_ed25519_pub,
&link_id,
let responder_x25519_pub = responder_keys.x25519_pub.to_bytes();
let sig_bytes = signalling.pack();
let mut signed_data = Vec::with_capacity(16 + 32 + 32 + 3);
signed_data.extend_from_slice(&link_id);
signed_data.extend_from_slice(&responder_x25519_pub);
signed_data.extend_from_slice(identity_ed25519_pub);
signed_data.extend_from_slice(&sig_bytes);
let signature = sign_fn(&signed_data).ok_or(HandshakeError::InvalidSignature)?;
let proof = LinkProofData {
signature,
responder_x25519_pub,
signalling,
);
};
let proof_data = proof.pack();
let timeout_secs = ESTABLISHMENT_TIMEOUT_PER_HOP * (hops.max(1) as f64) + KEEPALIVE_DEFAULT;
@@ -429,9 +481,7 @@ impl Link {
ephemeral_keys: Some(responder_keys),
peer_x25519_pub: Some(request.peer_x25519_pub),
peer_ed25519_pub: Some(request.peer_ed25519_pub),
sig_prv: Some(Ed25519PrivateKey::from_bytes(
&identity_signing_key.to_bytes(),
)),
sig_prv: identity_signing_key.map(|key| Ed25519PrivateKey::from_bytes(&key.to_bytes())),
session_keys: Some(session_keys),
request_time: now,
rtt: None,
@@ -450,6 +500,8 @@ impl Link {
establishment_cost,
establishment_rate: None,
expected_rate: None,
// Populated by the runtime from the LRRTT packet hops (Link.py:525).
expected_hops: None,
destination_hash,
remote_identity_pub: None,
identified: false,
@@ -538,21 +590,9 @@ impl Link {
identity_pub_key: &[u8; 64],
identity_signing_key: &Ed25519PrivateKey,
) -> Result<Vec<u8>, LinkCryptoError> {
if !self.is_initiator || self.state != LinkState::Active {
return Err(LinkCryptoError::EncryptionFailed);
}
let mut signed_data = Vec::with_capacity(16 + 64);
signed_data.extend_from_slice(&self.link_id);
signed_data.extend_from_slice(identity_pub_key);
let signature = identity_signing_key.sign(&signed_data);
let mut proof_data = Vec::with_capacity(128);
proof_data.extend_from_slice(identity_pub_key);
proof_data.extend_from_slice(&signature);
self.encrypt(&proof_data)
self.identify_with_fallible(identity_pub_key, |message| {
Some(identity_signing_key.sign(message))
})
}
/// Identify with an external signer (e.g. hardware identity).
@@ -565,6 +605,18 @@ impl Link {
) -> Result<Vec<u8>, LinkCryptoError>
where
F: FnOnce(&[u8]) -> [u8; 64],
{
self.identify_with_fallible(identity_pub_key, |message| Some(sign_fn(message)))
}
/// Identify with an external signer that can be unavailable.
pub fn identify_with_fallible<F>(
&self,
identity_pub_key: &[u8; 64],
sign_fn: F,
) -> Result<Vec<u8>, LinkCryptoError>
where
F: FnOnce(&[u8]) -> Option<[u8; 64]>,
{
if !self.is_initiator || self.state != LinkState::Active {
return Err(LinkCryptoError::EncryptionFailed);
@@ -574,7 +626,7 @@ impl Link {
signed_data.extend_from_slice(&self.link_id);
signed_data.extend_from_slice(identity_pub_key);
let signature = sign_fn(&signed_data);
let signature = sign_fn(&signed_data).ok_or(LinkCryptoError::EncryptionFailed)?;
let mut proof_data = Vec::with_capacity(128);
proof_data.extend_from_slice(identity_pub_key);
@@ -878,17 +930,7 @@ impl Link {
packet_hash: &[u8; 32],
identity_signing_key: &Ed25519PrivateKey,
) -> Result<Vec<u8>, LinkCryptoError> {
if self.state != LinkState::Active && self.state != LinkState::Stale {
return Err(LinkCryptoError::EncryptionFailed);
}
let signature = identity_signing_key.sign(packet_hash);
let mut proof = Vec::with_capacity(96);
proof.extend_from_slice(packet_hash);
proof.extend_from_slice(&signature);
Ok(proof)
self.prove_packet_with_fallible(packet_hash, |hash| Some(identity_signing_key.sign(hash)))
}
/// Sign a received link packet with this link's ephemeral signing key.
@@ -899,23 +941,13 @@ impl Link {
&self,
packet_hash: &[u8; 32],
) -> Result<Vec<u8>, LinkCryptoError> {
if self.state != LinkState::Active && self.state != LinkState::Stale {
return Err(LinkCryptoError::EncryptionFailed);
}
let signature = if let Some(signature) = self.sign(packet_hash) {
signature
} else if let Some(ephemeral_keys) = self.ephemeral_keys.as_ref() {
ephemeral_keys.ed25519_prv.sign(packet_hash)
} else {
return Err(LinkCryptoError::EncryptionFailed);
};
let mut proof = Vec::with_capacity(96);
proof.extend_from_slice(packet_hash);
proof.extend_from_slice(&signature);
Ok(proof)
self.prove_packet_with_fallible(packet_hash, |hash| {
self.sign(hash).or_else(|| {
self.ephemeral_keys
.as_ref()
.map(|keys| keys.ed25519_prv.sign(hash))
})
})
}
/// Variant of [`Link::prove_packet`] for external signers.
@@ -926,12 +958,24 @@ impl Link {
) -> Result<Vec<u8>, LinkCryptoError>
where
F: FnOnce(&[u8]) -> [u8; 64],
{
self.prove_packet_with_fallible(packet_hash, |hash| Some(sign_fn(hash)))
}
/// Variant of [`Link::prove_packet_with`] for signers that can be unavailable.
pub fn prove_packet_with_fallible<F>(
&self,
packet_hash: &[u8; 32],
sign_fn: F,
) -> Result<Vec<u8>, LinkCryptoError>
where
F: FnOnce(&[u8]) -> Option<[u8; 64]>,
{
if self.state != LinkState::Active && self.state != LinkState::Stale {
return Err(LinkCryptoError::EncryptionFailed);
}
let signature = sign_fn(packet_hash);
let signature = sign_fn(packet_hash).ok_or(LinkCryptoError::EncryptionFailed)?;
let mut proof = Vec::with_capacity(96);
proof.extend_from_slice(packet_hash);
@@ -1000,12 +1044,22 @@ impl Link {
self.outgoing_resources.retain(|h| h != resource_hash);
}
/// `bytes` is the link payload after the context byte (ciphertext), the
/// same unit as `record_rx` — Packet.py:291 txbytes += len(ciphertext).
pub fn record_tx(&mut self, bytes: usize) {
self.tx_bytes += bytes as u64;
self.tx_count += 1;
self.keepalive.record_outbound();
}
/// Count an outbound keepalive beat (Python counts them too, Packet.py:291)
/// without touching `last_outbound` — that would defer `is_stale` forever.
pub fn record_tx_keepalive(&mut self, bytes: usize) {
self.tx_bytes += bytes as u64;
self.tx_count += 1;
}
/// `bytes` is the link payload after the context byte (Link.py:929).
pub fn record_rx(&mut self, bytes: usize) {
self.rx_bytes += bytes as u64;
self.rx_count += 1;
@@ -2160,6 +2214,36 @@ mod tests {
assert_eq!(rx_c, 1);
}
/// Keepalive beats count into traffic stats (Packet.py:291) but must not
/// refresh `last_outbound`, or an initiator pinging a dead peer would
/// never go stale.
#[test]
fn test_record_tx_keepalive_counts_without_outbound_refresh() {
let (mut link, _, _) = make_active_link();
assert!(link.keepalive.last_outbound.is_none());
link.record_tx_keepalive(1);
let (tx_b, _, tx_c, _) = link.traffic_stats();
assert_eq!(tx_b, 1);
assert_eq!(tx_c, 1);
assert!(link.keepalive.last_outbound.is_none());
}
/// Initiator knows expected_hops at creation (Link.py:282); the responder
/// side stays unset until the runtime observes the LRRTT hops (Link.py:525).
#[test]
fn test_expected_hops_initiator_only_at_creation() {
let dest_hash = [0xAB; 16];
let identity_key = Ed25519PrivateKey::generate();
let (initiator, request_data) = Link::new_initiator(dest_hash, 3);
let (responder, _proof) =
Link::new_responder(&request_data, &identity_key, dest_hash, 3).unwrap();
assert_eq!(initiator.expected_hops, Some(3));
assert_eq!(responder.expected_hops, None);
}
#[test]
fn test_phy_stats() {
let (mut link, _, _) = make_active_link();
+235 -7
View File
@@ -198,7 +198,9 @@ impl WindowState {
pub fn grow(&mut self, rate: usize) {
if self.window < self.window_max {
self.window += 1;
if (self.window - self.window_min) > (WINDOW_FLEXIBILITY - 1) {
// saturating: a very-slow demotion can clamp `window` below `window_min` (Python's
// signed comparison is false there; a plain sub underflows).
if self.window.saturating_sub(self.window_min) > (WINDOW_FLEXIBILITY - 1) {
self.window_min += 1;
}
}
@@ -236,7 +238,7 @@ impl WindowState {
if self.window_max > self.window_min {
self.window_max -= 1;
}
if self.window_max - self.window > WINDOW_FLEXIBILITY - 1 {
if self.window_max.saturating_sub(self.window) > WINDOW_FLEXIBILITY - 1 {
self.window_max -= 1;
}
}
@@ -571,6 +573,16 @@ impl InboundResource {
return Err(ResourceError::TooLarge);
}
// `total_parts` is attacker-controlled wire input; unchecked it sizes the
// parts Vec directly (24 B per slot — a remote multi-GB alloc bomb). Real
// transfers satisfy total_parts == ceil(total_size / sdu); MIN_PART_SIZE
// is a generous lower bound on any negotiated SDU (real MDU ≈ 475).
const MIN_PART_SIZE: usize = 32;
let max_parts = total_size.div_ceil(MIN_PART_SIZE).saturating_add(16);
if total_parts > max_parts {
return Err(ResourceError::TooLarge);
}
Ok(Self {
state: ResourceState::Transferring,
parts: vec![None; total_parts],
@@ -1253,6 +1265,7 @@ pub struct OutboundTransfer {
/// Scopes the search range when servicing RESOURCE_REQ lookups.
pub receiver_min_consecutive_height: usize,
pub sent_parts: usize,
sent_part_indices: HashSet<usize>,
req_hashlist: HashSet<[u8; 32]>,
}
@@ -1301,6 +1314,7 @@ impl OutboundTransfer {
window_max_sent: 0,
receiver_min_consecutive_height: 0,
sent_parts: 0,
sent_part_indices: HashSet::new(),
req_hashlist: HashSet::new(),
}
}
@@ -1351,6 +1365,9 @@ impl OutboundTransfer {
if let Some(part_data) = part_data {
self.last_part_sent = Some(Instant::now());
self.resource.state = ResourceState::Transferring;
if self.sent_part_indices.insert(part_idx) {
self.sent_parts += 1;
}
if self.window_cursor >= window_end {
// Last part in the window is now in flight; stop
@@ -1548,6 +1565,9 @@ impl OutboundTransfer {
{
if let Some(part_data) = self.resource.get_part(i) {
actions.push(TransferAction::SendPart(i, part_data.to_vec()));
if self.sent_part_indices.insert(i) {
self.sent_parts += 1;
}
sent_count += 1;
}
}
@@ -1736,13 +1756,16 @@ impl OutboundTransfer {
buf
}
/// Fraction of parts confirmed, in `0.0..=1.0`.
/// Fraction of unique parts transmitted, in `0.0..=1.0`.
///
/// Upstream Reticulum reports initiator-side progress from `sent_parts`,
/// while receiver HMUs/proofs still decide completion. This keeps UI
/// progress useful on large resources before a full segment proof arrives.
pub fn progress(&self) -> f64 {
let confirmed = self.confirmed_parts.iter().filter(|&&c| c).count();
if self.resource.num_parts() == 0 {
return 1.0;
}
confirmed as f64 / self.resource.num_parts() as f64
self.sent_parts.min(self.resource.num_parts()) as f64 / self.resource.num_parts() as f64
}
}
@@ -2104,10 +2127,19 @@ impl InboundTransfer {
let hashmap_max_len =
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU);
// Parse hashes from the hashmap data and insert into our map_hashes
// Parse hashes from the hashmap data and insert into our map_hashes.
// `segment` is wire-supplied: indices are bounded by total_parts
// (Python preallocates hashmap to total_parts, so out-of-range
// writes are impossible there) — anything beyond is hostile.
let hashes_count = hashmap_data.len() / MAPHASH_LEN;
for i in 0..hashes_count {
let idx = i + segment * hashmap_max_len;
let idx = match segment
.checked_mul(hashmap_max_len)
.and_then(|base| base.checked_add(i))
{
Some(idx) if idx < self.resource.total_parts => idx,
_ => break,
};
let start = i * MAPHASH_LEN;
let end = start + MAPHASH_LEN;
if end <= hashmap_data.len() {
@@ -2567,6 +2599,31 @@ mod tests {
assert!(ws.window_min > initial_min);
}
// Regression: a very-slow demotion can clamp `window` below an already-raised `window_min`;
// the next promoted grow must not underflow `window - window_min` (Python's signed comparison
// is simply false there).
#[test]
fn window_grow_survives_demote_then_promote() {
let mut w = WindowState::new();
for _ in 0..6 {
w.grow(1000);
}
assert_eq!((w.window, w.window_min, w.window_max), (10, 7, 10));
for _ in 0..VERY_SLOW_RATE_THRESHOLD {
w.grow(RATE_VERY_SLOW - 1);
}
assert_eq!(
(w.window, w.window_min, w.window_max),
(WINDOW_MAX_VERY_SLOW, 7, WINDOW_MAX_VERY_SLOW)
);
for _ in 0..FAST_RATE_THRESHOLD + 1 {
w.grow(RATE_FAST + 1);
}
assert_eq!(w.window_max, WINDOW_MAX_FAST);
assert_eq!(w.window, 5);
assert_eq!(w.window_min, 7); // unchanged: window has not outgrown the band
}
#[test]
fn test_link_resource_outbound_creation() {
let link_id = [0xAA; 16];
@@ -2750,6 +2807,54 @@ mod tests {
assert_eq!(proof.len(), 64); // resource_hash(32) + expected_proof(32)
}
#[test]
fn test_inbound_rejects_part_count_inconsistent_with_size() {
// AF-2026-04.1: wire-controlled num_parts must not size the parts Vec
// unchecked — total_size=1024 with 10M parts is a ~240 MB alloc bomb.
let result = InboundTransfer::from_advertisement(
10_000_000,
1024,
1000,
[0xAA; RANDOM_HASH_SIZE],
[0xBB; 32],
ResourceFlags::default(),
Vec::new(),
Duration::from_millis(100),
);
assert!(matches!(result, Err(ResourceError::TooLarge)));
// Same bound at the InboundResource layer directly.
let result = InboundResource::new(
usize::MAX,
1024,
1000,
[0xAA; RANDOM_HASH_SIZE],
[0xBB; 32],
ResourceFlags::default(),
Vec::new(),
);
assert!(matches!(result, Err(ResourceError::TooLarge)));
}
#[test]
fn test_inbound_accepts_max_legitimate_part_count() {
// Worst legitimate case: max-size transfer split at the real SDU.
let max_total_size =
MAX_EFFICIENT_SIZE + RANDOM_HASH_SIZE + rns_crypto::TOKEN_OVERHEAD + 16;
let parts = max_total_size.div_ceil(SDU);
let result = InboundResource::new(
parts,
max_total_size,
MAX_EFFICIENT_SIZE,
[0xAA; RANDOM_HASH_SIZE],
[0xBB; 32],
ResourceFlags::default(),
Vec::new(),
);
assert!(result.is_ok());
assert_eq!(result.unwrap().total_parts, parts);
}
#[test]
fn test_inbound_transfer_hmu_generation() {
let data = vec![0u8; 2000]; // Multiple parts
@@ -2821,6 +2926,55 @@ mod tests {
assert_eq!(transfer.progress(), 0.0);
}
#[test]
fn test_transfer_progress_tracks_unique_sent_parts() {
let data = vec![0x55; SDU * 2 + 100];
let mut sender =
OutboundTransfer::new(data.clone(), false, Duration::from_millis(50)).unwrap();
assert!(sender.resource.num_parts() > 1);
assert!(matches!(
sender.tick(),
TransferAction::SendAdvertisement(_)
));
let first_progress = match sender.tick() {
TransferAction::SendPart(_, _) => sender.progress(),
other => panic!("expected first part, got {other:?}"),
};
assert!(first_progress > 0.0);
assert!(first_progress < 1.0);
let mut receiver = InboundTransfer::from_advertisement(
sender.resource.num_parts(),
sender.resource.total_size,
data.len(),
sender.resource.random_hash,
sender.resource.resource_hash,
ResourceFlags {
compressed: false,
..Default::default()
},
sender.resource.map_hashes.clone(),
Duration::from_millis(50),
)
.unwrap();
let TransferAction::SendRequest(request) = receiver.request_next() else {
panic!("expected receiver request");
};
let first_count = sender.sent_parts;
let _ = sender.handle_request(&request);
let after_request = sender.sent_parts;
let _ = sender.handle_request(&request);
assert!(after_request >= first_count);
assert_eq!(
sender.sent_parts, after_request,
"duplicate requests must not inflate visible send progress"
);
}
#[test]
fn test_full_transfer_roundtrip() {
// Simulate a complete transfer: sender → receiver
@@ -4023,6 +4177,80 @@ mod tests {
assert!(matches!(action, TransferAction::SendRequest(_)));
}
#[test]
fn test_hashmap_update_rejects_out_of_range_segment() {
// Wire-supplied `segment` must not grow map_hashes past total_parts.
let data = vec![0u8; 2000];
let outbound = OutboundResource::new(data.clone(), false, None).unwrap();
let total_parts = outbound.num_parts();
let mut inbound = InboundTransfer::from_advertisement(
total_parts,
outbound.total_size,
data.len(),
outbound.random_hash,
outbound.resource_hash,
ResourceFlags {
compressed: false,
..Default::default()
},
outbound.map_hashes[..2].to_vec(),
Duration::from_millis(100),
)
.unwrap();
// Hostile segment index: would previously push ~segment*74 zero
// entries into map_hashes. Must be ignored without growth or panic.
inbound.hashmap_update(1_000_000, &outbound.map_hashes[0]);
assert_eq!(inbound.resource.map_hashes.len(), 2);
// Overflowing segment*hashmap_max_len must not panic either.
inbound.hashmap_update(usize::MAX, &outbound.map_hashes[0]);
assert_eq!(inbound.resource.map_hashes.len(), 2);
}
#[test]
fn test_hashmap_update_second_segment_bounded_by_total_parts() {
// Resource large enough that its hashmap spans >1 segment: segment 1
// writes land, but never past total_parts even if overfull.
let hashmap_max_len =
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU);
let data = vec![0xCD; (hashmap_max_len + 12) * SDU];
let outbound = OutboundResource::new(data.clone(), false, None).unwrap();
let total_parts = outbound.num_parts();
assert!(total_parts > hashmap_max_len);
let mut inbound = InboundTransfer::from_advertisement(
total_parts,
outbound.total_size,
data.len(),
outbound.random_hash,
outbound.resource_hash,
ResourceFlags {
compressed: false,
..Default::default()
},
outbound.map_hashes[..hashmap_max_len].to_vec(),
Duration::from_millis(100),
)
.unwrap();
// Segment 1 carrying a deliberately overfull hash list: valid tail
// entries land, writes stop exactly at total_parts.
let mut overfull = Vec::new();
for i in hashmap_max_len..total_parts {
overfull.extend_from_slice(&outbound.map_hashes[i]);
}
overfull.extend_from_slice(&[0xEE; MAPHASH_LEN * 8]);
inbound.hashmap_update(1, &overfull);
assert_eq!(inbound.resource.map_hashes.len(), total_parts);
assert_eq!(
inbound.resource.map_hashes[total_parts - 1],
outbound.map_hashes[total_parts - 1]
);
}
#[test]
fn test_full_transfer_with_request_next() {
// Full transfer using the request_next mechanism instead of
+20 -1
View File
@@ -14,12 +14,31 @@ thiserror = { workspace = true }
tracing = { workspace = true }
hex = { workspace = true }
zeroize = { workspace = true }
aes = { workspace = true }
des = { workspace = true }
toml = "0.8"
# X.509 attestation-chain verification (always compiled, not behind `hardware`).
x509-cert = { version = "0.2", features = ["pem"] }
rsa = "0.9"
# `oid` feature: lets RSA PKCS#1 v1.5 VerifyingKey<Sha256/Sha512> build the DigestInfo prefix.
sha2 = { workspace = true, features = ["oid"] }
der = "0.7"
const-oid = "0.9"
# BIP-39 recoverable backup: 12-word mnemonic -> deterministic Reticulum identity.
bip39 = "2"
hkdf = "0.12"
[dev-dependencies]
rns-crypto = { workspace = true, features = ["std"] }
rns-identity = { workspace = true }
rns-link = { path = "../rns-link" }
rns-link = { workspace = true }
# Synthetic-chain test fixtures.
x509-cert = { version = "0.2", features = ["pem", "builder"] }
# `sha2` feature provides RsaSignatureAssociatedOid for the cert builder's signer.
rsa = { version = "0.9", features = ["sha2"] }
rand = { workspace = true }
[features]
default = []
-23
View File
@@ -1,23 +0,0 @@
# RatKey Hardware Status
RatKey hardware identity support is intentionally not release-grade until it is
verified against real devices. The mock-backed tests cover public identity
shape, signing, ECDH, decrypt flow, and fail-closed key mismatch behavior, but
they do not prove PIV transport, touch/PIN policy, or X.509 chain verification.
Required before hardware RatKey is documented as supported:
- Replace the mock-only `HardwareIdentity` session storage with a real PIV
backend abstraction and YubiKey/Nitrokey implementations.
- Verify signing and ECDH against physical YubiKeys, including disconnect,
wrong PIN, touch timeout, and slot mismatch cases.
- Implement cryptographic attestation certificate chain verification against
the bundled Yubico roots and intermediates.
- Decide and document the ratchet policy for hardware identities. PIV cannot
hold Reticulum ratchet private keys, so enforced-ratchet decrypt currently
fails closed.
- Add hardware-gated tests that are skipped by default but run when a device is
explicitly selected by environment/config.
Until those items pass on real devices, CLI/UI surfaces must label hardware
RatKey support as experimental.
@@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIDSDCCAjCgAwIBAgIUUcmMXzRIFOgGTK0Tb3gEuZYZkBIwDQYJKoZIhvcNAQEL
BQAwJDEiMCAGA1UEAwwZWXViaWNvIEF0dGVzdGF0aW9uIFJvb3QgMTAgFw0yNDEy
MDEwMDAwMDBaGA85OTk5MTIzMTIzNTk1OVowLjEsMCoGA1UEAwwjWXViaWNvIEF0
dGVzdGF0aW9uIEludGVybWVkaWF0ZSBBIDEwggEiMA0GCSqGSIb3DQEBAQUAA4IB
DwAwggEKAoIBAQDm555bWY9WW+tOY0rIWHldh+aNanoCZCFh7Gk3YZrQmPUw0hkS
G6qYHQtP+fZyS33VErvg+BQqnmumgNhfxFrkwEZELeidBcC8C4Ag4nqqiPWpzsvI
17NcxYlInLNLFcZY/+gOiN6ZOTihO5/vBZMbj9riaAcqliYmNGJPgTcMGaEAyMzE
MNy2nm6Ep+pjP5aF6gi21t/UQFsuJ1j2Rj/ynM/SdRt+ecal5OYotxHkFbL9vvv2
A2Ov5ITZClw4bOS9npypQimOZ5QAYytmYaQpWl/pMYz6zSj8RqkVDNEJGqNfTKA2
ivLYwX6lSttMPapg0J84l9X0voVN/FpS4VCVAgMBAAGjZjBkMB0GA1UdDgQWBBQg
KFAhG6RaW+hTy52dxeT8bC96HzAfBgNVHSMEGDAWgBTS7u9aIo06bVwjlz3yhdUm
8SV7kjASBgNVHRMBAf8ECDAGAQH/AgECMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG
9w0BAQsFAAOCAQEAYMzgLrJLIr0OovQnAZrRIGuabiHSUKSmbLRWpRkWeAtsChDE
HpXcJ/bgDNKYWoHqQ8xRUjB4CyepYevc3YlrG8o7zHxpfVcaoL5SeuJkzHxKn4bT
aSp9+Mvwamnp64kZMiNbFLknfP9kYKoRHkMWheRJ1UsP1z4ScmkCeILfsMs6vqov
qjWClFsJpBcsluYHWF7bBJ1n4Rwg+ATEopY4IgGv6Zvwc+A9r+AT2hqpoSkYoAl+
ANYwgslOf9sJe0V+TA9YY/UlaBmPPTd0//r9wvcePWZkPjKoAC/zUNhfDbh4LV8G
Hs3lyX2XomL/LNc8JYzyIaDEhGQveoPhh/tr1g==
-----END CERTIFICATE-----
@@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIDSDCCAjCgAwIBAgIUDqERw+4RnGSggxgUewJFEPDRZ3YwDQYJKoZIhvcNAQEL
BQAwJDEiMCAGA1UEAwwZWXViaWNvIEF0dGVzdGF0aW9uIFJvb3QgMTAgFw0yNDEy
MDEwMDAwMDBaGA85OTk5MTIzMTIzNTk1OVowLjEsMCoGA1UEAwwjWXViaWNvIEF0
dGVzdGF0aW9uIEludGVybWVkaWF0ZSBCIDEwggEiMA0GCSqGSIb3DQEBAQUAA4IB
DwAwggEKAoIBAQDI7XnH+ZvDwMCQU8M8ZeV5qscublvVYaaRt3Ybaxn9godLx5sw
H0lXrdgjh5h7FpVgCgYYX7E4bl1vbzULemrMWT8N3WMGUe8QAJbBeioV7W/E+hTZ
P/0SKJVa3ewKBo6ULeMnfQZDrVORAk8wTLq2v5Llj5vMj7JtOotKa9J7nHS8kLmz
XXSaj0SwEPh5OAZUTNV4zs1bvoTAQQWrL4/J9QuKt6WCFE5nUNiRQcEbVF8mlqK2
bx2z6okVltyDVLCxYbpUTELvY1usR3DTGPUoIClOm4crpwnDRLVHvjYePGBB//pE
yzxA/gcScxjwaH1ZUw9bnSbHyurKqbTa1KvjAgMBAAGjZjBkMB0GA1UdDgQWBBTq
t0KQngx7ZHrbVHwDunxOn9ihYTAfBgNVHSMEGDAWgBTS7u9aIo06bVwjlz3yhdUm
8SV7kjASBgNVHRMBAf8ECDAGAQH/AgECMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG
9w0BAQsFAAOCAQEAqQaCWMxTGqVVX7Sk7kkJmUueTSYKuU6+KBBSgwIRnlw9K7He
1IpxZ0hdwpPNikKjmcyFgFPzhImwHJgxxuT90Pw3vYOdcJJNktDg35PXOfzSn15c
FAx1RO0mPTmIb8dXiEWOpzoXvdwXDM41ZaCDYMT7w4IQtMyvE7xUBZq2bjtAnq/N
DUA7be4H8H3ipC+/+NKlUrcUh+j48K67WI0u1m6FeQueBA7n06j825rqDqsaLs9T
b7KAHAw8PmrWaNPG2kjKerxPEfecivlFawp2RWZvxrVtn3TV2SBxyCJCkXsND05d
CErVHSJIs+BdtTVNY9AwtyPmnyb0v4mSTzvWdw==
-----END CERTIFICATE-----
@@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIDSTCCAjGgAwIBAgIUSiefkiKiicP9B63XwO7fKqevCkQwDQYJKoZIhvcNAQEL
BQAwLjEsMCoGA1UEAwwjWXViaWNvIEF0dGVzdGF0aW9uIEludGVybWVkaWF0ZSBB
IDEwIBcNMjQxMjAxMDAwMDAwWhgPOTk5OTEyMzEyMzU5NTlaMCUxIzAhBgNVBAMM
Gll1YmljbyBQSVYgQXR0ZXN0YXRpb24gQSAxMIIBIjANBgkqhkiG9w0BAQEFAAOC
AQ8AMIIBCgKCAQEAyGCyrZjNrdPfChdDe4JWd+4TMLr8nbugcKJz12egglWi7oy5
L9GT99/if9i1OrONdpEt0YrCa+qMb+dJJ0WUa8M5zXYnUDpn72vhFjH+Anb9P9+v
+ZrRqaj/jnR/MYP7NpVpeLHiH2dRCe/PX/NH1XE41GvdUEncDtqUUGaXUea0DfDY
McRDpPT2Qn5e8rn9FjzDA37SbOVuws5VlFTDzDdqR0FnqeWeIW0DFu17rzCqXcaB
VRDnQLTc5EEPDTpiRrQE/Ag+7Wg9ieLrueos75YMQ1EIkfjL49OBVogU1A7kwRGv
OnG8l7sYaY8LZ2b5FROe2hKqmsIy600qjn6b/QIDAQABo2YwZDAdBgNVHQ4EFgQU
hAuLXXtpQVBkcsbqyFlj6LVAadgwHwYDVR0jBBgwFoAUIChQIRukWlvoU8udncXk
/Gwveh8wEgYDVR0TAQH/BAgwBgEB/wIBATAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZI
hvcNAQELBQADggEBAFxL/2oFjxkLh2KVnFKdhy7Nf7MmEfYXDDFSx1rFDn445jHO
UP5kxQPbZc9r53jdvL5W0SQBqBjqA95PYh0r1CPMFsFJdiFXli8Hf3NQ0bTkeFSN
G3LsQCOKMb+o2WjYU3vHkRVjKgKGLxysxxKxGfMUcXdJ0qM6ZVeRHehC2zy7XuI6
TQn7/V0ZHXjk7So7dUV55xQde094/3cCTnh9Q3j2aqMjkGx6tDboCsz/+W+tne7W
nMHG92ZiAAmOkP2bABjan461Qty/qBXPHomkfjqNbjUTluPXiMLYKCXHIyKwdkX6
cphouSMU3QOTsb35Y2PeWNk54xu+Eds/3nhRMso=
-----END CERTIFICATE-----
@@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIDSTCCAjGgAwIBAgIUWVf2oJG+t1qP8t8TicWgJ2KYan4wDQYJKoZIhvcNAQEL
BQAwLjEsMCoGA1UEAwwjWXViaWNvIEF0dGVzdGF0aW9uIEludGVybWVkaWF0ZSBC
IDEwIBcNMjQxMjAxMDAwMDAwWhgPOTk5OTEyMzEyMzU5NTlaMCUxIzAhBgNVBAMM
Gll1YmljbyBQSVYgQXR0ZXN0YXRpb24gQiAxMIIBIjANBgkqhkiG9w0BAQEFAAOC
AQ8AMIIBCgKCAQEAv7WBL9/5AKxSpCMoL63183WqRtFrOHY7tdyuGtoidoYWQrxV
aV9S+ZwH0aynh0IzD5A/PvCtuxdtL5w2cAI3tgsborOlEert4IZ904CZQfq3ooar
1an/wssbtMpPOQkC3MQiqrUyHlFS2BTbuwbBXY66lSVX/tGRuUgnBdfBJtcQKS6M
O4bU5ndPQqhGPyzcyY1LvlfzK7KJ1r/bixCRFqjhJRnPs0Czpg6rkRrFgC6cd5bK
1UgTsJy+3wrIqkv4CeV3EhSVnhnQjZgIrdIcI5WZ8T1Oq3OhMlWmY0K0dy/oZdP/
bpbG2qbyHLa6gprLT/qChQWLmffxn6D2DAB1zQIDAQABo2YwZDAdBgNVHQ4EFgQU
M0Nt3QHo7eGzaKMZn2SmXT74vpcwHwYDVR0jBBgwFoAU6rdCkJ4Me2R621R8A7p8
Tp/YoWEwEgYDVR0TAQH/BAgwBgEB/wIBATAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZI
hvcNAQELBQADggEBAI0HwoS84fKMUyIof1LdUXvyeAMmEwW7+nVETvxNNlTMuwv7
zPJ4XZAm9Fv95tz9CqZBj6l1PAPQn6Zht9LQA92OF7W7buuXuxuusBTgLM0C1iX2
CGXqY/k/uSNvi3ZYfrpd44TIrfrr8bCG9ux7B5ZCRqb8adDUm92Yz3lK1aX2M6Cw
jC9IZVTXQWhLyP8Ys3p7rb20CO2jJzV94deJ/+AsEb+bnCQImPat1GDKwrBosar+
BxtU7k6kgkxZ0G384O59GFXqnwkbw2b5HhORvOsX7nhOUhePFufzi1vT1g8Tzbwr
+TUfTwo2biKHHcI762KGtp8o6Bcv5y8WgExFuWY=
-----END CERTIFICATE-----
@@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIDRjCCAjCgAwIBAgIUM6Hs259YBTYRAMg98ZZlv/CDyO0wCwYJKoZIhvcNAQEL
MC4xLDAqBgNVBAMMI1l1YmljbyBBdHRlc3RhdGlvbiBJbnRlcm1lZGlhdGUgQiAx
MCAXDTI1MDgwMTAwMDAwMFoYDzk5OTkxMjMxMjM1OTU5WjAmMSQwIgYDVQQDDBtZ
dWJpY28gUElWIEF0dGVzdGF0aW9uIEIyIDEwggEiMA0GCSqGSIb3DQEBAQUAA4IB
DwAwggEKAoIBAQCxqNa82XHPD/QMqYffF8K4a9aoJIV7SU9NKXu3hBh+6nF0/HPP
UtSu/ChTdPoCk1Li2Sz7gkWzijJVCCSo6uRgRT2sUoTb8xjKo80N5QxAC3TVNRpA
lGh4Ba5KxamnXrf6s78tB73oTlTkMBUehVwvbQZGRpst00w58SxDP0nF7rO6qF+h
8M+kV4ycd8zUssMq6yxWhDAUZ+gT4l0SwvBEvUiJ8q7phFGJPyMjrKy1bifC50GW
xdLLJq7WRswaNxOsQ8hqJVRsoQ9pnZDCvo2WRkTzi3UrPPp5Soyy+aUOlNs0gwFu
07H75Gnswet+wffpeDFXZM2ITH3SN0LrpairAgMBAAGjZjBkMB0GA1UdDgQWBBSe
IRwEGD3d5SgceJxQn/ztOZHuVjAfBgNVHSMEGDAWgBTqt0KQngx7ZHrbVHwDunxO
n9ihYTASBgNVHRMBAf8ECDAGAQH/AgEBMA4GA1UdDwEB/wQEAwIBhjALBgkqhkiG
9w0BAQsDggEBAKK+IxeMsYsfqbLZ/Ld82tHWddLLlbXBaQojmRSDNHlBGbOvuQZg
rnbafjIEyb+Uv1+TdJnn5cV1P/MBSfJLBPqBuhKZ3lk4460CWRmcIKsxVRe0V5+V
bGCzLKpWtlrEBVkFTSbBQk4FQNVYw5pR4UzRIambsRyyGsyN0gppGyxyCqAR8/Od
GI+sUWh+VxFSlSpvaDT9GBGBN6eG0WMAZlEdu9k/tphesazHeK6MvXP6tBnb4DCd
09DUZeon7D8m1drYyw5kOjqgm1E3HPkNx4856iTdY7nAuVQ++i0hUhaJpc/5HZbw
wdlqXnmZ+XRIGSDLn2KKoxSWziowEvlU+04=
-----END CERTIFICATE-----
+397 -2
View File
@@ -10,9 +10,11 @@ pub const PIV_AID: &[u8] = &[0xA0, 0x00, 0x00, 0x03, 0x08, 0x00, 0x00, 0x10, 0x0
pub const INS_SELECT: u8 = 0xA4;
pub const INS_VERIFY: u8 = 0x20;
pub const INS_CHANGE_REFERENCE: u8 = 0x24;
pub const INS_RESET_RETRY: u8 = 0x2C;
pub const INS_GENERAL_AUTHENTICATE: u8 = 0x87;
pub const INS_GENERATE_ASYMMETRIC: u8 = 0x47;
pub const INS_GET_DATA: u8 = 0xCB;
pub const INS_RESET_PIV: u8 = 0xFB;
pub const INS_GET_METADATA: u8 = 0xF7;
pub const INS_ATTEST: u8 = 0xF9;
pub const INS_IMPORT_KEY: u8 = 0xFE;
@@ -30,6 +32,13 @@ pub const SLOT_SIGNATURE: u8 = 0x9C;
pub const SLOT_KEY_MANAGEMENT: u8 = 0x9D;
pub const SLOT_CARD_AUTH: u8 = 0x9E;
pub const SLOT_ATTESTATION: u8 = 0xF9;
pub const SLOT_CARD_MANAGEMENT: u8 = 0x9B;
// Management-key algorithm (key reference 9B). AES-192 is the YubiKey 5.7 default.
pub const MGMT_ALG_TDES: u8 = 0x03;
pub const MGMT_ALG_AES128: u8 = 0x08;
pub const MGMT_ALG_AES192: u8 = 0x0A;
pub const MGMT_ALG_AES256: u8 = 0x0C;
pub const PIN_POLICY_NEVER: u8 = 0x01;
pub const PIN_POLICY_ONCE: u8 = 0x02;
@@ -42,26 +51,80 @@ pub const TOUCH_POLICY_CACHED: u8 = 0x03;
const TAG_DYNAMIC_AUTH: u8 = 0x7C;
const TAG_AUTH_RESPONSE: u8 = 0x82;
const TAG_AUTH_CHALLENGE: u8 = 0x81;
/// Management-key auth witness (same byte as `TAG_GEN_ALGORITHM`, different context).
const TAG_AUTH_WITNESS: u8 = 0x80;
const TAG_AUTH_EXPONENTIATION: u8 = 0x85;
const TAG_GEN_ALGORITHM: u8 = 0x80;
const TAG_PIN_POLICY: u8 = 0xAA;
const TAG_TOUCH_POLICY: u8 = 0xAB;
const TAG_OBJECT_ID: u8 = 0x5C;
const TAG_ECC_POINT: u8 = 0x86;
/// GET METADATA public-key field (Yubico).
const TAG_METADATA_PUBLIC_KEY: u8 = 0x04;
/// Cert object ID for slot 9A (Authentication).
pub const OBJ_ID_9A: &[u8] = &[0x5F, 0xC1, 0x05];
/// Cert object ID for slot 9D (Key Management).
pub const OBJ_ID_9D: &[u8] = &[0x5F, 0xC1, 0x0B];
/// Object ID for the device attestation (slot F9) intermediate certificate.
pub const OBJ_ID_F9: &[u8] = &[0x5F, 0xFF, 0x01];
pub fn slot_to_object_id(slot: u8) -> Option<&'static [u8]> {
match slot {
0x9A => Some(OBJ_ID_9A),
0x9D => Some(OBJ_ID_9D),
SLOT_ATTESTATION => Some(OBJ_ID_F9),
_ => None,
}
}
/// Extract the certificate DER from a PIV GET DATA cert object response, which
/// wraps the cert as `53 L { 70 L <certDER> 71 .. FE .. }`. Falls back to the raw
/// buffer if it already looks like a bare certificate (`30` SEQUENCE).
pub fn parse_certificate_object(resp: &[u8]) -> Option<Vec<u8>> {
let content = read_ber_tlv(resp, 0x53).unwrap_or(resp);
if let Some(cert) = read_ber_tlv(content, 0x70) {
return Some(cert.to_vec());
}
match resp.first() {
Some(0x30) => Some(resp.to_vec()),
_ => None,
}
}
/// First top-level BER-TLV with `tag` in `buf`, returning its value. Handles
/// short-form and 1-/2-byte long-form lengths; single-byte tags only.
fn read_ber_tlv(buf: &[u8], tag: u8) -> Option<&[u8]> {
let mut i = 0;
while i + 1 < buf.len() {
let t = buf[i];
let len_byte = buf[i + 1];
i += 2;
let len = if len_byte < 0x80 {
len_byte as usize
} else {
let n = (len_byte & 0x7f) as usize;
if n == 0 || n > 2 || i + n > buf.len() {
return None;
}
let mut l = 0usize;
for _ in 0..n {
l = (l << 8) | buf[i] as usize;
i += 1;
}
l
};
if i + len > buf.len() {
return None;
}
if t == tag {
return Some(&buf[i..i + len]);
}
i += len;
}
None
}
// ISO 7816-4 APDU: CLA INS P1 P2 [Lc] [Data]. CLA=0x00 (no chaining, no secure messaging).
fn build_apdu(ins: u8, p1: u8, p2: u8, data: &[u8]) -> Vec<u8> {
let mut apdu = Vec::with_capacity(5 + data.len());
@@ -110,15 +173,19 @@ pub fn select_piv() -> Vec<u8> {
/// PIN is ASCII, 0xFF-padded to 8 bytes (NIST SP 800-73-4 §2.4.3).
pub fn verify_pin(pin: &str) -> Vec<u8> {
use zeroize::Zeroize;
let mut pin_data = [0xFFu8; 8];
let pin_bytes = pin.as_bytes();
let copy_len = pin_bytes.len().min(8);
pin_data[..copy_len].copy_from_slice(&pin_bytes[..copy_len]);
build_apdu(INS_VERIFY, 0x00, 0x80, &pin_data)
let cmd = build_apdu(INS_VERIFY, 0x00, 0x80, &pin_data);
pin_data.zeroize();
cmd
}
// CHANGE REFERENCE DATA.
pub fn change_pin(old_pin: &str, new_pin: &str) -> Vec<u8> {
use zeroize::Zeroize;
let mut data = [0xFFu8; 16];
let old_bytes = old_pin.as_bytes();
let new_bytes = new_pin.as_bytes();
@@ -126,7 +193,31 @@ pub fn change_pin(old_pin: &str, new_pin: &str) -> Vec<u8> {
let new_len = new_bytes.len().min(8);
data[..old_len].copy_from_slice(&old_bytes[..old_len]);
data[8..8 + new_len].copy_from_slice(&new_bytes[..new_len]);
build_apdu(INS_CHANGE_REFERENCE, 0x00, 0x80, &data)
let cmd = build_apdu(INS_CHANGE_REFERENCE, 0x00, 0x80, &data);
data.zeroize();
cmd
}
/// RESET RETRY COUNTER: unblock a locked PIN with the PUK and set a new PIN.
pub fn reset_retry(puk: &str, new_pin: &str) -> Vec<u8> {
use zeroize::Zeroize;
let mut data = [0xFFu8; 16];
let puk_bytes = puk.as_bytes();
let new_bytes = new_pin.as_bytes();
let puk_len = puk_bytes.len().min(8);
let new_len = new_bytes.len().min(8);
data[..puk_len].copy_from_slice(&puk_bytes[..puk_len]);
data[8..8 + new_len].copy_from_slice(&new_bytes[..new_len]);
let cmd = build_apdu(INS_RESET_RETRY, 0x00, 0x80, &data);
data.zeroize();
cmd
}
/// RESET PIV: erase all PIV data and restore factory PIV secrets.
///
/// YubiKey only accepts this command after both the PIN and PUK are blocked.
pub fn reset_piv() -> Vec<u8> {
build_apdu(INS_RESET_PIV, 0x00, 0x00, &[])
}
// GENERATE ASYMMETRIC KEY PAIR (Ed25519/X25519).
@@ -147,6 +238,63 @@ pub fn generate_key(
build_apdu(INS_GENERATE_ASYMMETRIC, 0x00, slot, &data)
}
// Yubico private-key import elements: Ed25519 = 0x07, X25519 = 0x08.
const TAG_IMPORT_ED25519: u8 = 0x07;
const TAG_IMPORT_X25519: u8 = 0x08;
/// IMPORT ASYMMETRIC KEY (Ed25519, slot). Requires management-key auth. For
/// recoverable provisioning — the key was derived off-device from a seed phrase.
pub fn import_ed25519(
slot: u8,
private_key: &[u8; 32],
pin_policy: Option<u8>,
touch_policy: Option<u8>,
) -> Vec<u8> {
import_key(
slot,
ALG_ED25519,
TAG_IMPORT_ED25519,
private_key,
pin_policy,
touch_policy,
)
}
/// IMPORT ASYMMETRIC KEY (X25519, slot). Requires management-key auth.
pub fn import_x25519(
slot: u8,
private_key: &[u8; 32],
pin_policy: Option<u8>,
touch_policy: Option<u8>,
) -> Vec<u8> {
import_key(
slot,
ALG_X25519,
TAG_IMPORT_X25519,
private_key,
pin_policy,
touch_policy,
)
}
fn import_key(
slot: u8,
alg: u8,
key_tag: u8,
private_key: &[u8; 32],
pin_policy: Option<u8>,
touch_policy: Option<u8>,
) -> Vec<u8> {
let mut data = tlv(key_tag, private_key);
if let Some(pp) = pin_policy {
data.extend_from_slice(&tlv(TAG_PIN_POLICY, &[pp]));
}
if let Some(tp) = touch_policy {
data.extend_from_slice(&tlv(TAG_TOUCH_POLICY, &[tp]));
}
build_apdu(INS_IMPORT_KEY, alg, slot, &data)
}
/// GENERAL AUTHENTICATE Ed25519 sign. Send raw message — device does SHA-512 internally; no pre-hash.
pub fn sign_ed25519(slot: u8, message: &[u8]) -> Vec<u8> {
let challenge = tlv(TAG_AUTH_CHALLENGE, message);
@@ -194,6 +342,64 @@ pub fn attest_key(slot: u8) -> Vec<u8> {
build_apdu(INS_ATTEST, slot, 0x00, &[])
}
// --- Management-key authentication (slot 9B, witness/challenge mutual auth) ---
/// Step 1: request an encrypted witness from the card. `mgmt_alg` is the
/// management-key algorithm (P1).
pub fn auth_witness_request(mgmt_alg: u8) -> Vec<u8> {
let inner = tlv(TAG_AUTH_WITNESS, &[]);
let data = tlv(TAG_DYNAMIC_AUTH, &inner);
build_apdu(
INS_GENERAL_AUTHENTICATE,
mgmt_alg,
SLOT_CARD_MANAGEMENT,
&data,
)
}
/// Step 3: return the decrypted witness plus our own challenge.
pub fn auth_witness_response(mgmt_alg: u8, decrypted_witness: &[u8], challenge: &[u8]) -> Vec<u8> {
let mut inner = tlv(TAG_AUTH_WITNESS, decrypted_witness);
inner.extend_from_slice(&tlv(TAG_AUTH_CHALLENGE, challenge));
let data = tlv(TAG_DYNAMIC_AUTH, &inner);
build_apdu(
INS_GENERAL_AUTHENTICATE,
mgmt_alg,
SLOT_CARD_MANAGEMENT,
&data,
)
}
/// Extract the witness (tag 0x80) from a witness-request response.
pub fn parse_auth_witness(data: &[u8]) -> Result<Vec<u8>, RatkeyError> {
find_tlv_value(data, TAG_AUTH_WITNESS)
.map(<[u8]>::to_vec)
.ok_or(RatkeyError::Apdu {
sw1: 0x6A,
sw2: 0x80,
})
}
/// Extract the card's encrypted challenge (tag 0x82) from a witness-response reply.
pub fn parse_auth_response(data: &[u8]) -> Result<Vec<u8>, RatkeyError> {
find_tlv_value(data, TAG_AUTH_RESPONSE)
.map(<[u8]>::to_vec)
.ok_or(RatkeyError::Apdu {
sw1: 0x6A,
sw2: 0x80,
})
}
/// Algorithm byte (tag 0x01) from a GET METADATA response (e.g. slot 9B mgmt key).
pub fn parse_metadata_algorithm(metadata: &[u8]) -> Result<u8, RatkeyError> {
find_tlv_value(metadata, 0x01)
.and_then(|v| v.first().copied())
.ok_or(RatkeyError::Apdu {
sw1: 0x6A,
sw2: 0x80,
})
}
pub fn check_response(response: &[u8]) -> Result<&[u8], RatkeyError> {
if response.len() < 2 {
return Err(RatkeyError::Apdu {
@@ -293,6 +499,31 @@ pub fn parse_ecdh_response(data: &[u8]) -> Result<[u8; 32], RatkeyError> {
Ok(out)
}
/// GET METADATA public key: field tag 0x04, then EC point tag 0x86 → 32 bytes.
/// `find_tlv_value` recurses into a `7F49` wrapper if present, so both the
/// bare (`86 20 ..`) and wrapped (`7F49 .. 86 20 ..`) encodings resolve.
/// Yubico 5.3+ extension; Nitrokey 3 does not implement GET METADATA.
pub fn parse_metadata_public_key(metadata: &[u8]) -> Result<[u8; 32], RatkeyError> {
let pubkey_field =
find_tlv_value(metadata, TAG_METADATA_PUBLIC_KEY).ok_or(RatkeyError::Apdu {
sw1: 0x6A,
sw2: 0x80,
})?;
let point = find_tlv_value(pubkey_field, TAG_ECC_POINT).ok_or(RatkeyError::Apdu {
sw1: 0x6A,
sw2: 0x80,
})?;
if point.len() != 32 {
return Err(RatkeyError::InvalidHwid(format!(
"expected 32-byte public key in metadata, got {} bytes",
point.len()
)));
}
let mut out = [0u8; 32];
out.copy_from_slice(point);
Ok(out)
}
// Recurse into 7C / AC / 53 / any 2-byte tag (7F49 etc) to find a single-byte tag.
fn find_tlv_value(data: &[u8], target_tag: u8) -> Option<&[u8]> {
let mut pos = 0;
@@ -507,6 +738,34 @@ mod tests {
assert_eq!(apdu, vec![0x00, 0xF9, 0x9A, 0x00]);
}
#[test]
fn test_get_data_slot_f9_attestation() {
let apdu = get_data(SLOT_ATTESTATION).unwrap();
assert_eq!(
apdu,
vec![0x00, 0xCB, 0x3F, 0xFF, 0x05, 0x5C, 0x03, 0x5F, 0xFF, 0x01]
);
}
#[test]
fn test_parse_certificate_object() {
// A 200-byte "cert" (DER SEQUENCE header) forces long-form lengths, wrapped
// as the PIV cert object: 53 L { 70 L <cert> 71 01 00 FE 00 }.
let mut cert = vec![0x30, 0x81, 0xC5];
cert.extend(std::iter::repeat_n(0xAB, 197));
let mut inner = vec![0x70, 0x81, cert.len() as u8];
inner.extend_from_slice(&cert);
inner.extend_from_slice(&[0x71, 0x01, 0x00, 0xFE, 0x00]);
let mut obj = vec![0x53, 0x81, inner.len() as u8];
obj.extend_from_slice(&inner);
assert_eq!(parse_certificate_object(&obj).unwrap(), cert);
// Bare DER (no PIV wrapper) is returned as-is.
assert_eq!(parse_certificate_object(&cert).unwrap(), cert);
// Non-cert payload yields nothing.
assert!(parse_certificate_object(&[0x00, 0x01, 0x02]).is_none());
}
#[test]
fn test_get_metadata() {
let apdu = get_metadata(SLOT_AUTHENTICATION);
@@ -571,6 +830,29 @@ mod tests {
);
}
#[test]
fn test_reset_retry() {
let apdu = reset_retry("12345678", "654321");
assert_eq!(apdu[0], 0x00); // CLA
assert_eq!(apdu[1], 0x2C); // INS = RESET RETRY
assert_eq!(apdu[2], 0x00); // P1
assert_eq!(apdu[3], 0x80); // P2 = PIN
assert_eq!(apdu[4], 0x10); // Lc = 16
assert_eq!(
&apdu[5..13],
&[0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38]
);
assert_eq!(
&apdu[13..21],
&[0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0xFF, 0xFF]
);
}
#[test]
fn test_reset_piv() {
assert_eq!(reset_piv(), vec![0x00, 0xFB, 0x00, 0x00]);
}
#[test]
fn test_check_response_success() {
let response = vec![0xAA, 0xBB, 0x90, 0x00];
@@ -632,6 +914,119 @@ mod tests {
assert_eq!(secret, [0xCC; 32]);
}
#[test]
fn test_auth_witness_request() {
let apdu = auth_witness_request(MGMT_ALG_AES192);
assert_eq!(
apdu,
vec![0x00, 0x87, 0x0A, 0x9B, 0x04, 0x7C, 0x02, 0x80, 0x00]
);
}
#[test]
fn test_auth_witness_response_carries_witness() {
let witness = [0xAA; 16];
let challenge = [0xBB; 16];
let apdu = auth_witness_response(MGMT_ALG_AES192, &witness, &challenge);
assert_eq!(apdu[1], 0x87); // INS GENERAL AUTHENTICATE
assert_eq!(apdu[2], 0x0A); // P1 = AES-192
assert_eq!(apdu[3], 0x9B); // P2 = mgmt slot
assert_eq!(apdu[5], 0x7C); // dynamic auth template
assert_eq!(parse_auth_witness(&apdu[5..]).unwrap(), witness.to_vec());
}
#[test]
fn test_parse_auth_witness() {
let mut resp = vec![0x7C, 0x12, 0x80, 0x10];
resp.extend_from_slice(&[0xCC; 16]);
assert_eq!(parse_auth_witness(&resp).unwrap(), vec![0xCC; 16]);
}
#[test]
fn test_parse_auth_response() {
let mut resp = vec![0x7C, 0x12, 0x82, 0x10];
resp.extend_from_slice(&[0xDD; 16]);
assert_eq!(parse_auth_response(&resp).unwrap(), vec![0xDD; 16]);
}
#[test]
fn test_parse_metadata_algorithm() {
let meta = vec![0x01, 0x01, MGMT_ALG_AES192];
assert_eq!(parse_metadata_algorithm(&meta).unwrap(), MGMT_ALG_AES192);
}
#[test]
fn test_import_ed25519() {
let key = [0x11; 32];
let apdu = import_ed25519(
SLOT_AUTHENTICATION,
&key,
Some(PIN_POLICY_ONCE),
Some(TOUCH_POLICY_NEVER),
);
assert_eq!(apdu[1], 0xFE); // INS IMPORT KEY
assert_eq!(apdu[2], 0xE0); // P1 = Ed25519
assert_eq!(apdu[3], 0x9A); // P2 = slot
assert_eq!(apdu[5], 0x07); // Ed25519 private-key element tag
assert_eq!(apdu[6], 0x20); // 32-byte length
assert_eq!(&apdu[7..39], &key);
assert_eq!(
&apdu[39..45],
&[0xAA, 0x01, PIN_POLICY_ONCE, 0xAB, 0x01, TOUCH_POLICY_NEVER]
);
}
#[test]
fn test_import_x25519_tag() {
let apdu = import_x25519(SLOT_KEY_MANAGEMENT, &[0x22; 32], None, None);
assert_eq!(apdu[1], 0xFE);
assert_eq!(apdu[2], 0xE1); // X25519
assert_eq!(apdu[3], 0x9D);
assert_eq!(apdu[5], 0x08); // X25519 private-key element tag
assert_eq!(apdu[6], 0x20);
}
#[test]
fn test_parse_metadata_public_key_bare() {
// Slot metadata: 01(algo) 02(policy) 03(origin) 04(pubkey = 86 20 <32>).
// Layout pending confirmation against a real YubiKey GET METADATA response.
let mut meta = vec![
0x01,
0x01,
ALG_ED25519,
0x02,
0x02,
PIN_POLICY_ONCE,
TOUCH_POLICY_ALWAYS,
0x03,
0x01,
0x01,
0x04,
0x22,
0x86,
0x20,
];
meta.extend_from_slice(&[0xAB; 32]);
assert_eq!(parse_metadata_public_key(&meta).unwrap(), [0xAB; 32]);
}
#[test]
fn test_parse_metadata_public_key_7f49_wrapped() {
// Same, but the point is wrapped in a 7F49 template (04 25 7F49 22 86 20 <32>).
let mut meta = vec![
0x01, 0x01, ALG_X25519, 0x04, 0x25, 0x7F, 0x49, 0x22, 0x86, 0x20,
];
meta.extend_from_slice(&[0xCD; 32]);
assert_eq!(parse_metadata_public_key(&meta).unwrap(), [0xCD; 32]);
}
#[test]
fn test_parse_metadata_public_key_missing_field() {
// No 0x04 field present.
let meta = vec![0x01, 0x01, ALG_ED25519, 0x03, 0x01, 0x01];
assert!(parse_metadata_public_key(&meta).is_err());
}
#[test]
fn test_parse_generate_response_wrong_size() {
let mut response = vec![0x7F, 0x49, 0x12, 0x86, 0x10];
+692 -31
View File
@@ -1,20 +1,51 @@
//! YubiKey PIV attestation verification. Bundled root CAs — never fetched.
//! YubiKey PIV attestation verification. Bundled root CAs — never fetched at runtime.
//!
//! Legacy chain (firmware < 5.7.4):
//! Yubico PIV Root CA Serial 263751 → device intermediate (slot F9) → per-key attestation cert.
//! per-key attestation cert → device intermediate (slot F9)
//! → `Yubico PIV Root CA Serial 263751` (bundled root).
//!
//! New chain (firmware >= 5.7.4):
//! Yubico Attestation Root 1 → Intermediate A/B 1 → PIV Attestation A/B 1
//! → device intermediate (slot F9) → per-key attestation cert.
//! per-key attestation cert → device intermediate (slot F9)
//! → `Yubico PIV Attestation {A,B,B2} 1` (bundled intermediate)
//! → `Yubico Attestation Intermediate {A,B} 1` (bundled intermediate)
//! → `Yubico Attestation Root 1` (bundled root).
//! The two tiers of intermediate CAs are not present on the device; they are
//! bundled here from Yubico's published attestation PKI (yubico-intermediate.pem).
//! Both A and B branches plus the 2025 B2 PIV intermediate are bundled, so any
//! firmware-5.7.4+ YubiKey PIV attestation chains to the bundled root.
//!
//! Nitrokey 3 does not support PIV attestation (firmware 1.8) — verification skipped.
//!
//! Chain verification status: structural + OID extraction only. The
//! `verified` flag remains false until X.509 path validation is exercised
//! against real devices. See crates/rns-ratkey/HARDWARE_STATUS.md.
//! ## What `chain_verified == true` means here
//!
//! Every link from the per-key attestation cert up to (and including) a bundled
//! trust anchor has a valid RSA PKCS#1 v1.5 signature (issuer public key over the
//! child's TBS bytes), the terminal issuer's DER SHA-256 matches a pinned
//! fingerprint constant, and every certificate in the walked path is inside its
//! notBefore/notAfter validity window at verification time.
//!
//! ## Explicit non-goals (NOT checked)
//!
//! Revocation (CRL/OCSP), name constraints, basicConstraints/keyUsage/pathlen
//! enforcement, and the remainder of RFC 5280 path validation are intentionally
//! out of scope. The root's own self-signature is not verified — the root is
//! trusted by pinned fingerprint plus validity window. All required chain links
//! are sha256WithRSAEncryption; the per-cert signature OID is still inspected so
//! a sha512WithRSA link would be honored rather than silently mis-verified.
use crate::error::RatkeyError;
use const_oid::ObjectIdentifier;
use der::Encode;
use rsa::RsaPublicKey;
use rsa::pkcs1::DecodeRsaPublicKey;
use rsa::pkcs1v15::{Signature as RsaSignature, VerifyingKey};
use rsa::signature::Verifier;
use sha2::{Digest, Sha256, Sha512};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use x509_cert::Certificate;
use x509_cert::der::Decode;
/// Yubico PIV Root CA (legacy, firmware < 5.7.4). Subject: "Yubico PIV Root CA Serial 263751".
pub const YUBICO_PIV_ROOT_CA_LEGACY_PEM: &str =
include_str!("../certs/yubico-piv-root-ca-legacy.pem");
@@ -23,9 +54,22 @@ pub const YUBICO_PIV_ROOT_CA_LEGACY_PEM: &str =
pub const YUBICO_ATTESTATION_ROOT_1_PEM: &str =
include_str!("../certs/yubico-attestation-root-1.pem");
// New-PKI intermediates (firmware >= 5.7.4). Bundled from Yubico's published
// yubico-intermediate.pem. A, B, and the 2025 B2 PIV branches are all covered.
const YUBICO_ATTESTATION_INTERMEDIATE_A_1_PEM: &str =
include_str!("../certs/yubico-attestation-intermediate-a-1.pem");
const YUBICO_ATTESTATION_INTERMEDIATE_B_1_PEM: &str =
include_str!("../certs/yubico-attestation-intermediate-b-1.pem");
const YUBICO_PIV_ATTESTATION_A_1_PEM: &str =
include_str!("../certs/yubico-piv-attestation-a-1.pem");
const YUBICO_PIV_ATTESTATION_B_1_PEM: &str =
include_str!("../certs/yubico-piv-attestation-b-1.pem");
const YUBICO_PIV_ATTESTATION_B2_1_PEM: &str =
include_str!("../certs/yubico-piv-attestation-b2-1.pem");
/// SHA-256 fingerprint of the legacy Yubico PIV Root CA (belt-and-suspenders vs PEM swap).
pub const YUBICO_LEGACY_ROOT_SHA256: &str =
"63ece914e54dd87915f34033c85af4c0696ba1512f8add66ced73833120785b546";
"63ece914e54dd87915f34033c85af4c0696ba1512f8add66ced738331207b546";
/// SHA-256 fingerprint of the new Yubico Attestation Root 1 (belt-and-suspenders vs PEM swap).
pub const YUBICO_NEW_ROOT_SHA256: &str =
@@ -46,6 +90,13 @@ pub const OID_USAGE_POLICY: &[u8] = &[0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xC4,
/// Form factor (1 byte).
pub const OID_FORM_FACTOR: &[u8] = &[0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xC4, 0x0A, 0x03, 0x09];
// Signature algorithm OIDs (PKCS#1).
const OID_SHA256_RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");
const OID_SHA512_RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.13");
// Guard against issuer cycles in a malformed/hostile pool.
const MAX_CHAIN_DEPTH: usize = 8;
#[derive(Debug, Clone)]
pub struct AttestationInfo {
pub firmware_version: Option<(u8, u8, u8)>,
@@ -73,8 +124,12 @@ pub struct AttestationVerification {
pub description: String,
}
/// Verify chain: attestation cert (from ATTEST) + device intermediate (slot F9).
/// Currently structural + OID extraction only.
/// Verify chain: attestation cert (from ATTEST F9) + device intermediate (slot F9).
///
/// Sets `verified`/`chain_verified == true` only when every signature from the
/// per-key cert up to a bundled, fingerprint-pinned Yubico root validates and
/// all walked certs are inside their validity window. See module docs for the
/// precise meaning and the explicit non-goals.
pub fn verify_attestation(
attestation_cert_der: &[u8],
device_cert_der: &[u8],
@@ -82,9 +137,8 @@ pub fn verify_attestation(
let info = extract_attestation_info(attestation_cert_der, device_cert_der)?;
let metadata_extracted = info.firmware_version.is_some();
let chain_verified = false;
let root_ca = if let Some((major, minor, patch)) = info.firmware_version {
if major > 5 || (major == 5 && minor >= 7 && patch >= 4) {
if major > 5 || (major == 5 && (minor > 7 || (minor == 7 && patch >= 4))) {
"new".to_string()
} else {
"legacy".to_string()
@@ -93,17 +147,17 @@ pub fn verify_attestation(
"unknown".to_string()
};
let description = if metadata_extracted {
let (maj, min, pat) = info.firmware_version.unwrap_or((0, 0, 0));
format!(
"YubiKey firmware {maj}.{min}.{pat}{}; attestation chain not cryptographically verified",
info.serial_number
.map(|s| format!(", serial {s}"))
.unwrap_or_default()
)
} else {
"could not extract YubiKey attestation metadata".to_string()
};
let anchors = bundled_trust_anchors();
let pool = bundled_intermediate_pool();
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let chain_result = verify_chain(attestation_cert_der, device_cert_der, &anchors, &pool, now);
let chain_verified = chain_result.is_ok();
let description = build_description(metadata_extracted, &info, &chain_result);
Ok(AttestationVerification {
verified: chain_verified,
@@ -115,11 +169,268 @@ pub fn verify_attestation(
})
}
fn build_description(
metadata_extracted: bool,
info: &AttestationInfo,
chain_result: &Result<(), ChainError>,
) -> String {
let prefix = if metadata_extracted {
let (maj, min, pat) = info.firmware_version.unwrap_or((0, 0, 0));
format!(
"YubiKey firmware {maj}.{min}.{pat}{}",
info.serial_number
.map(|s| format!(", serial {s}"))
.unwrap_or_default()
)
} else {
"could not extract YubiKey attestation metadata".to_string()
};
match chain_result {
Ok(()) => {
format!("{prefix}; attestation chain cryptographically verified to bundled Yubico root")
}
Err(e) => format!("{prefix}; attestation chain not verified: {e}"),
}
}
/// YubiKey 5 (firmware >= 4.3.0) only. Nitrokey 3 has no PIV attestation.
pub fn supports_attestation(device_type: &str) -> bool {
device_type == "yubikey5"
}
// ---------------------------------------------------------------------------
// Chain verification
// ---------------------------------------------------------------------------
/// A parsed trust anchor. Only included after its DER SHA-256 matched a pinned
/// fingerprint constant (see `bundled_trust_anchors`), so reaching one is the
/// terminal trust condition.
#[derive(Clone)]
struct TrustAnchor {
cert: Certificate,
}
#[derive(Debug)]
enum ChainError {
ParseLeaf,
ParseDevice,
IssuerNotFound,
SignatureInvalid,
Expired,
UnsupportedSignatureAlg(String),
BadPublicKey,
DepthExceeded,
}
impl std::fmt::Display for ChainError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ChainError::ParseLeaf => write!(f, "attestation certificate did not parse as X.509"),
ChainError::ParseDevice => {
write!(f, "device (slot F9) certificate did not parse as X.509")
}
ChainError::IssuerNotFound => {
write!(
f,
"no bundled/known issuer found for a certificate in the chain"
)
}
ChainError::SignatureInvalid => write!(f, "a certificate signature failed to verify"),
ChainError::Expired => write!(f, "a certificate is outside its validity window"),
ChainError::UnsupportedSignatureAlg(oid) => {
write!(f, "unsupported certificate signature algorithm {oid}")
}
ChainError::BadPublicKey => write!(f, "issuer public key could not be decoded as RSA"),
ChainError::DepthExceeded => write!(f, "chain exceeded maximum depth"),
}
}
}
/// Bundled, fingerprint-pinned roots. A cert is only a valid terminal if its DER
/// SHA-256 matches one of these constants — guarding against a swapped PEM.
fn bundled_trust_anchors() -> Vec<TrustAnchor> {
let mut anchors = Vec::new();
for (pem, fp) in [
(YUBICO_PIV_ROOT_CA_LEGACY_PEM, YUBICO_LEGACY_ROOT_SHA256),
(YUBICO_ATTESTATION_ROOT_1_PEM, YUBICO_NEW_ROOT_SHA256),
] {
if let Some(der) = pem_to_der(pem) {
if hex::encode(Sha256::digest(&der)) == fp {
if let Ok(cert) = Certificate::from_der(&der) {
anchors.push(TrustAnchor { cert });
}
}
}
}
anchors
}
/// Bundled intermediate CAs (new-PKI A/B/B2 branches). Searchable issuers only —
/// never terminal trust anchors.
fn bundled_intermediate_pool() -> Vec<Certificate> {
[
YUBICO_ATTESTATION_INTERMEDIATE_A_1_PEM,
YUBICO_ATTESTATION_INTERMEDIATE_B_1_PEM,
YUBICO_PIV_ATTESTATION_A_1_PEM,
YUBICO_PIV_ATTESTATION_B_1_PEM,
YUBICO_PIV_ATTESTATION_B2_1_PEM,
]
.into_iter()
.filter_map(|pem| pem_to_der(pem).and_then(|der| Certificate::from_der(&der).ok()))
.collect()
}
/// Walk from the leaf up to a pinned anchor, verifying each signature and every
/// cert's validity window. `now` is seconds since the Unix epoch.
fn verify_chain(
attestation_cert_der: &[u8],
device_cert_der: &[u8],
anchors: &[TrustAnchor],
intermediates: &[Certificate],
now: Duration,
) -> Result<(), ChainError> {
let leaf = Certificate::from_der(attestation_cert_der).map_err(|_| ChainError::ParseLeaf)?;
let device = Certificate::from_der(device_cert_der).map_err(|_| ChainError::ParseDevice)?;
// Searchable issuers: the device F9 cert plus all bundled intermediates.
let mut searchable: Vec<&Certificate> = Vec::with_capacity(intermediates.len() + 1);
searchable.push(&device);
for c in intermediates {
searchable.push(c);
}
check_validity(&leaf, now)?;
let mut current = leaf.clone();
let mut current_der = attestation_cert_der.to_vec();
for _ in 0..MAX_CHAIN_DEPTH {
// Terminal: is `current` signed by a pinned anchor?
for anchor in anchors {
// `anchor` is trusted only because its DER SHA-256 matched a pinned
// constant in bundled_trust_anchors(); its self-signature is not checked.
if names_match(
&anchor.cert.tbs_certificate.subject,
&current.tbs_certificate.issuer,
) && verify_signature(&current, &anchor.cert).is_ok()
{
check_validity(&anchor.cert, now)?;
return Ok(());
}
}
// A self-issued cert that is not a pinned anchor is an untrusted root:
// the chain terminates here without reaching a trust anchor. (Anchors are
// checked above, so reaching this point means it is not pinned.)
if names_match(
&current.tbs_certificate.subject,
&current.tbs_certificate.issuer,
) {
return Err(ChainError::IssuerNotFound);
}
// Otherwise advance one link via a searchable (non-anchor) issuer.
let issuer = searchable.iter().copied().find(|cand| {
names_match(
&cand.tbs_certificate.subject,
&current.tbs_certificate.issuer,
) && verify_signature(&current, cand).is_ok()
});
match issuer {
Some(issuer_cert) => {
check_validity(issuer_cert, now)?;
let issuer_der = issuer_cert
.to_der()
.map_err(|_| ChainError::IssuerNotFound)?;
// Cycle guard: a non-self-issued cert pointing back at itself.
if issuer_der == current_der {
return Err(ChainError::IssuerNotFound);
}
current = issuer_cert.clone();
current_der = issuer_der;
}
None => {
// No pinned anchor and no searchable issuer signs `current`.
// Distinguish "issuer present but bad signature" for diagnostics.
let issuer_present = anchors.iter().any(|a| {
names_match(
&a.cert.tbs_certificate.subject,
&current.tbs_certificate.issuer,
)
}) || searchable.iter().any(|c| {
names_match(&c.tbs_certificate.subject, &current.tbs_certificate.issuer)
});
return Err(if issuer_present {
ChainError::SignatureInvalid
} else {
ChainError::IssuerNotFound
});
}
}
}
Err(ChainError::DepthExceeded)
}
/// RFC 5280 distinguished-name match via canonical DER encoding of the Name.
fn names_match(a: &x509_cert::name::Name, b: &x509_cert::name::Name) -> bool {
match (a.to_der(), b.to_der()) {
(Ok(da), Ok(db)) => da == db,
_ => false,
}
}
/// Verify `child`'s signature using `issuer`'s public key (RSA PKCS#1 v1.5).
fn verify_signature(child: &Certificate, issuer: &Certificate) -> Result<(), ChainError> {
let tbs = child
.tbs_certificate
.to_der()
.map_err(|_| ChainError::SignatureInvalid)?;
let sig_bytes = child
.signature
.as_bytes()
.ok_or(ChainError::SignatureInvalid)?;
let sig = RsaSignature::try_from(sig_bytes).map_err(|_| ChainError::SignatureInvalid)?;
let spki_key = issuer
.tbs_certificate
.subject_public_key_info
.subject_public_key
.as_bytes()
.ok_or(ChainError::BadPublicKey)?;
let pubkey = RsaPublicKey::from_pkcs1_der(spki_key).map_err(|_| ChainError::BadPublicKey)?;
let alg = child.signature_algorithm.oid;
if alg == OID_SHA256_RSA {
VerifyingKey::<Sha256>::new(pubkey)
.verify(&tbs, &sig)
.map_err(|_| ChainError::SignatureInvalid)
} else if alg == OID_SHA512_RSA {
VerifyingKey::<Sha512>::new(pubkey)
.verify(&tbs, &sig)
.map_err(|_| ChainError::SignatureInvalid)
} else {
Err(ChainError::UnsupportedSignatureAlg(alg.to_string()))
}
}
/// Reject certs outside their notBefore/notAfter window at time `now`.
fn check_validity(cert: &Certificate, now: Duration) -> Result<(), ChainError> {
let nb = cert.tbs_certificate.validity.not_before.to_unix_duration();
let na = cert.tbs_certificate.validity.not_after.to_unix_duration();
if now < nb || now > na {
Err(ChainError::Expired)
} else {
Ok(())
}
}
// ---------------------------------------------------------------------------
// OID metadata extraction (byte-scan; unchanged behavior)
// ---------------------------------------------------------------------------
fn extract_attestation_info(
attestation_cert_der: &[u8],
device_cert_der: &[u8],
@@ -379,8 +690,9 @@ mod tests {
}
#[test]
fn test_verify_attestation_synthetic() {
// Build a minimal attestation cert with firmware OID
fn test_verify_attestation_synthetic_metadata() {
// Minimal attestation cert with firmware OID; not a real X.509 cert, so the
// chain cannot verify — exercises metadata extraction + graceful chain failure.
let mut attest_der = Vec::new();
let mut inner = Vec::new();
inner.push(0x06);
@@ -394,7 +706,6 @@ mod tests {
attest_der.push(inner.len() as u8);
attest_der.extend_from_slice(&inner);
// Minimal device cert (just a SEQUENCE)
let device_der = vec![0x30, 0x00];
let result = verify_attestation(&attest_der, &device_der).unwrap();
@@ -403,11 +714,7 @@ mod tests {
assert!(!result.chain_verified);
assert_eq!(result.root_ca, "legacy"); // 5.7.1 < 5.7.4
assert!(result.description.contains("5.7.1"));
assert!(
result
.description
.contains("not cryptographically verified")
);
assert!(result.description.contains("not verified"));
}
#[test]
@@ -434,6 +741,25 @@ mod tests {
assert_eq!(result.root_ca, "new"); // 5.7.4 → new root CA
}
#[test]
fn test_verify_attestation_future_firmware_uses_new_root_label() {
let mut attest_der = Vec::new();
let mut inner = Vec::new();
inner.push(0x06);
inner.push(OID_FIRMWARE_VERSION.len() as u8);
inner.extend_from_slice(OID_FIRMWARE_VERSION);
inner.push(0x04);
inner.push(0x03);
inner.extend_from_slice(&[0x05, 0x08, 0x00]); // 5.8.0
attest_der.push(0x30);
attest_der.push(inner.len() as u8);
attest_der.extend_from_slice(&inner);
let result = verify_attestation(&attest_der, &[0x30, 0x00]).unwrap();
assert_eq!(result.root_ca, "new");
}
#[test]
fn test_verify_attestation_empty_cert() {
let result = verify_attestation(&[], &[]).unwrap();
@@ -442,4 +768,339 @@ mod tests {
assert!(!result.chain_verified);
assert_eq!(result.root_ca, "unknown");
}
// Real on-device vectors captured from a YubiKey 5.7.4 (serial 35284666) via
// `rnid-rs hw attest`: the slot-9A per-key attestation cert + the slot-F9
// device intermediate. Proves the verifier chains a real device's ATTEST
// output to a bundled, fingerprint-pinned Yubico root — the regression guard
// for the hardware validation, runnable in CI without a device.
// Both certs are notAfter=9999-12-31 (Yubico attestation certs do not expire),
// so the validity-window check in `verify_chain` will not rot this vector.
#[test]
fn test_real_yubikey_attestation_chain_verifies() {
let attest = include_bytes!("../tests/fixtures/9a_attest.der");
let device = include_bytes!("../tests/fixtures/f9_device.der");
let v = verify_attestation(attest, device).unwrap();
assert!(
v.chain_verified,
"real-device chain must verify: {}",
v.description
);
assert!(v.verified);
assert_eq!(v.root_ca, "new");
assert_eq!(v.info.firmware_version, Some((5, 7, 4)));
assert_eq!(v.info.serial_number, Some(35284666));
}
// ---------------------------------------------------------------------
// Pinned-fingerprint guards: compute the SHA-256 with our own code path
// (pem_to_der + sha2) and assert it equals the pinned constant. Catches a
// swapped PEM and validates the hand-rolled base64 against the same DER the
// x509 parser consumes.
// ---------------------------------------------------------------------
#[test]
fn test_legacy_root_fingerprint_matches_constant() {
let der = pem_to_der(YUBICO_PIV_ROOT_CA_LEGACY_PEM).expect("decode legacy root");
assert_eq!(hex::encode(Sha256::digest(&der)), YUBICO_LEGACY_ROOT_SHA256);
}
#[test]
fn test_new_root_fingerprint_matches_constant() {
let der = pem_to_der(YUBICO_ATTESTATION_ROOT_1_PEM).expect("decode new root");
assert_eq!(hex::encode(Sha256::digest(&der)), YUBICO_NEW_ROOT_SHA256);
}
#[test]
fn test_bundled_anchors_and_pool_parse() {
let anchors = bundled_trust_anchors();
assert_eq!(anchors.len(), 2, "both pinned roots must parse and match");
let pool = bundled_intermediate_pool();
assert_eq!(pool.len(), 5, "five PIV-chain intermediates bundled");
}
#[test]
fn test_real_intermediate_chains_to_pinned_root() {
// The bundled PIV Attestation A 1 cert chains to the bundled Attestation
// Root 1 via the bundled Intermediate A 1. Verify the new-PKI links work
// against the real published certs (using PIV Attestation A 1 as the
// synthetic "leaf"/"device" entry point).
let anchors = bundled_trust_anchors();
let pool = bundled_intermediate_pool();
// Use Intermediate A 1 as the leaf; its issuer is the pinned root.
let int_a = pem_to_der(YUBICO_ATTESTATION_INTERMEDIATE_A_1_PEM).unwrap();
let now = Duration::from_secs(1_900_000_000); // ~2030, inside all windows
let res = verify_chain(&int_a, &int_a, &anchors, &pool, now);
assert!(
res.is_ok(),
"real intermediate must chain to pinned root: {res:?}"
);
}
// ---------------------------------------------------------------------
// Synthetic chains. Build our own root → sub-CA → leaf with the x509
// builder, then exercise verify_chain directly with injected anchors.
// ---------------------------------------------------------------------
use rsa::RsaPrivateKey;
use rsa::pkcs1v15::SigningKey;
use std::str::FromStr;
use x509_cert::builder::{Builder, CertificateBuilder, Profile};
use x509_cert::name::Name;
use x509_cert::serial_number::SerialNumber;
use x509_cert::spki::SubjectPublicKeyInfoOwned;
use x509_cert::time::{Time, Validity};
struct Node {
cert: Certificate,
der: Vec<u8>,
}
fn gen_key() -> RsaPrivateKey {
let mut rng = rand::thread_rng();
RsaPrivateKey::new(&mut rng, 1024).expect("rsa keygen")
}
fn spki_of(key: &RsaPrivateKey) -> SubjectPublicKeyInfoOwned {
use rsa::pkcs1::EncodeRsaPublicKey;
let pub_der = key.to_public_key().to_pkcs1_der().unwrap();
// Wrap PKCS#1 RSAPublicKey in an rsaEncryption SubjectPublicKeyInfo.
use x509_cert::spki::AlgorithmIdentifierOwned;
SubjectPublicKeyInfoOwned {
algorithm: AlgorithmIdentifierOwned {
oid: ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1"),
parameters: Some(der::Any::null()),
},
subject_public_key: x509_cert::der::asn1::BitString::from_bytes(pub_der.as_bytes())
.unwrap(),
}
}
fn far_validity() -> Validity {
// Wide window covering "now".
Validity::from_now(Duration::from_secs(60 * 60 * 24 * 365 * 20)).unwrap()
}
/// Build a cert with `subject`, signed by `signer_key` under `issuer` name.
fn build_cert(
profile: Profile,
subject: &str,
subject_key: &RsaPrivateKey,
signer_key: &RsaPrivateKey,
validity: Validity,
serial: u32,
) -> Node {
let signer = SigningKey::<Sha256>::new(signer_key.clone());
let builder = CertificateBuilder::new(
profile,
SerialNumber::from(serial),
validity,
Name::from_str(subject).unwrap(),
spki_of(subject_key),
&signer,
)
.expect("builder");
let cert: Certificate = builder.build::<RsaSignature>().expect("build/sign");
let der = cert.to_der().expect("encode");
Node { cert, der }
}
/// Root self-signed; sub-CA signed by root; leaf signed by sub-CA. Returns
/// (leaf, sub_ca, root) so callers can inject the root as anchor and the
/// sub-CA into the searchable pool.
fn synthetic_chain() -> (Node, Node, Node) {
let root_key = gen_key();
let sub_key = gen_key();
let leaf_key = gen_key();
let root = build_cert(
Profile::Root,
"CN=Test Root",
&root_key,
&root_key,
far_validity(),
1,
);
let sub = build_cert(
Profile::SubCA {
issuer: Name::from_str("CN=Test Root").unwrap(),
path_len_constraint: Some(1),
},
"CN=Test SubCA",
&sub_key,
&root_key,
far_validity(),
2,
);
let leaf = build_cert(
Profile::Leaf {
issuer: Name::from_str("CN=Test SubCA").unwrap(),
enable_key_agreement: false,
enable_key_encipherment: false,
},
"CN=Test Leaf",
&leaf_key,
&sub_key,
far_validity(),
3,
);
(leaf, sub, root)
}
fn anchor_of(node: &Node) -> TrustAnchor {
TrustAnchor {
cert: node.cert.clone(),
}
}
fn now() -> Duration {
SystemTime::now().duration_since(UNIX_EPOCH).unwrap()
}
#[test]
fn test_synthetic_chain_verifies() {
let (leaf, sub, root) = synthetic_chain();
// Device slot = sub-CA here; intermediates = [sub].
let res = verify_chain(
&leaf.der,
&sub.der,
&[anchor_of(&root)],
std::slice::from_ref(&sub.cert),
now(),
);
assert!(res.is_ok(), "valid synthetic chain must verify: {res:?}");
}
#[test]
fn test_tampered_signature_fails() {
let (leaf, sub, root) = synthetic_chain();
// Flip one byte in the leaf signature, re-encode.
let mut tampered = leaf.cert.clone();
let mut sig = tampered.signature.as_bytes().unwrap().to_vec();
sig[0] ^= 0x01;
tampered.signature = x509_cert::der::asn1::BitString::from_bytes(&sig).unwrap();
let tampered_der = tampered.to_der().unwrap();
let res = verify_chain(
&tampered_der,
&sub.der,
&[anchor_of(&root)],
std::slice::from_ref(&sub.cert),
now(),
);
assert!(
matches!(res, Err(ChainError::SignatureInvalid)),
"got {res:?}"
);
}
#[test]
fn test_expired_cert_fails() {
let root_key = gen_key();
let sub_key = gen_key();
let leaf_key = gen_key();
let root = build_cert(
Profile::Root,
"CN=Test Root",
&root_key,
&root_key,
far_validity(),
1,
);
let sub = build_cert(
Profile::SubCA {
issuer: Name::from_str("CN=Test Root").unwrap(),
path_len_constraint: Some(1),
},
"CN=Test SubCA",
&sub_key,
&root_key,
far_validity(),
2,
);
// Leaf already expired: notBefore..notAfter both in the past.
let expired = Validity {
not_before: Time::UtcTime(
x509_cert::der::asn1::UtcTime::from_unix_duration(Duration::from_secs(
1_000_000_000,
))
.unwrap(),
),
not_after: Time::UtcTime(
x509_cert::der::asn1::UtcTime::from_unix_duration(Duration::from_secs(
1_100_000_000,
))
.unwrap(),
),
};
let leaf = build_cert(
Profile::Leaf {
issuer: Name::from_str("CN=Test SubCA").unwrap(),
enable_key_agreement: false,
enable_key_encipherment: false,
},
"CN=Test Leaf",
&leaf_key,
&sub_key,
expired,
3,
);
let res = verify_chain(
&leaf.der,
&sub.der,
&[anchor_of(&root)],
std::slice::from_ref(&sub.cert),
now(),
);
assert!(matches!(res, Err(ChainError::Expired)), "got {res:?}");
}
#[test]
fn test_wrong_root_fails_on_pin() {
// Build a fully valid chain, but the actual signing root is NOT pinned.
// Put the bogus root in the SEARCHABLE pool (so issuer-by-name succeeds and
// its signature verifies) but NOT in the anchor set. Verification must fail
// because no walked cert reaches a pinned terminal — exercises pin rejection,
// not a mere "issuer not found".
let (leaf, sub, bogus_root) = synthetic_chain();
// A second, unrelated key serves as the only *pinned* anchor — it signs
// nothing in this chain.
let other_root_key = gen_key();
let other_root = build_cert(
Profile::Root,
"CN=Unrelated Pinned Root",
&other_root_key,
&other_root_key,
far_validity(),
9,
);
let res = verify_chain(
&leaf.der,
&sub.der,
&[anchor_of(&other_root)], // pinned set: unrelated root only
&[sub.cert.clone(), bogus_root.cert.clone()], // searchable: real signer present
now(),
);
// The real signing root is reachable by name+signature but is not pinned,
// so the walk terminates without a pinned anchor.
assert!(
matches!(res, Err(ChainError::IssuerNotFound)),
"wrong-root chain must be rejected at the pin, got {res:?}"
);
}
#[test]
fn test_unknown_issuer_fails() {
let (leaf, _sub, root) = synthetic_chain();
// No sub-CA in the pool: leaf's issuer is unfindable.
let res = verify_chain(&leaf.der, &leaf.der, &[anchor_of(&root)], &[], now());
assert!(
matches!(res, Err(ChainError::IssuerNotFound)),
"got {res:?}"
);
}
}
+152
View File
@@ -0,0 +1,152 @@
//! Bridges a PIV token to an `rns_identity::Identity` via the `LocalKeyBackend`
//! seam. The PIV session runs on a dedicated thread — pcsc handles want serial
//! APDU access and are not `Sync` — so the backend handle holds only channel
//! senders and is therefore `Send + Sync`, usable directly from the async runtime.
use std::sync::mpsc::{self, Sender};
use std::sync::{Arc, Mutex};
use std::thread;
use rns_identity::identity::{Identity, LocalKeyBackend};
use crate::apdu::{SLOT_AUTHENTICATION, SLOT_KEY_MANAGEMENT};
use crate::error::RatkeyError;
use crate::hwid::HwidConfig;
use crate::session::PivSession;
use crate::transport::PcscTransport;
enum Cmd {
Sign {
message: Vec<u8>,
reply: Sender<Option<[u8; 64]>>,
},
Ecdh {
peer_pub: [u8; 32],
reply: Sender<Option<[u8; 32]>>,
},
/// Re-select the PIV applet to drop the on-card PIN cache. Acknowledged so
/// callers (lock-on-quit / timeout) can block until the card is re-locked.
Lock { reply: Sender<()> },
}
/// `LocalKeyBackend` over a PIV token. Each call round-trips a request to the
/// card-service thread and blocks for the device's reply (PIV ops are ~10-50ms).
pub struct HardwareBackend {
cmd_tx: Mutex<Sender<Cmd>>,
}
impl LocalKeyBackend for HardwareBackend {
fn sign_ed25519(&self, message: &[u8]) -> Option<[u8; 64]> {
let (reply, rx) = mpsc::channel();
self.cmd_tx
.lock()
.ok()?
.send(Cmd::Sign {
message: message.to_vec(),
reply,
})
.ok()?;
rx.recv().ok().flatten()
}
fn ecdh(&self, peer_pub: &[u8; 32]) -> Option<[u8; 32]> {
let (reply, rx) = mpsc::channel();
self.cmd_tx
.lock()
.ok()?
.send(Cmd::Ecdh {
peer_pub: *peer_pub,
reply,
})
.ok()?;
rx.recv().ok().flatten()
}
fn lock(&self) {
let (reply, rx) = mpsc::channel();
if let Ok(tx) = self.cmd_tx.lock()
&& tx.send(Cmd::Lock { reply }).is_ok()
{
let _ = rx.recv();
}
}
}
/// Connect to the token described by `hwid`, verify the on-device keys match it
/// (fail-closed), unlock with `pin`, and return an `Identity` whose private
/// operations run on the device. The PIV session lives on a worker thread that
/// exits when the returned identity (and its backend) is dropped.
pub fn load_hardware_identity(hwid: &HwidConfig, pin: &str) -> Result<Identity, RatkeyError> {
let ed_pub = hwid.ed25519_pub_bytes()?;
let x_pub = hwid.x25519_pub_bytes()?;
let pin = pin.to_string();
let (cmd_tx, cmd_rx) = mpsc::channel::<Cmd>();
let (ready_tx, ready_rx) = mpsc::channel::<Result<(), RatkeyError>>();
thread::Builder::new()
.name("ratkey-piv".to_string())
.spawn(move || {
let mut session = match PivSession::<PcscTransport>::connect() {
Ok(s) => s,
Err(e) => {
let _ = ready_tx.send(Err(e));
return;
}
};
// Fail closed: the device's slot keys must match the .hwid.
match (
session.read_public_key(SLOT_AUTHENTICATION),
session.read_public_key(SLOT_KEY_MANAGEMENT),
) {
(Ok(de), Ok(dx)) if de == ed_pub && dx == x_pub => {}
(Ok(_), Ok(_)) => {
let _ = ready_tx.send(Err(RatkeyError::KeyMismatch));
return;
}
(Err(e), _) | (_, Err(e)) => {
let _ = ready_tx.send(Err(e));
return;
}
}
if let Err(e) = session.verify_pin(&pin) {
let _ = ready_tx.send(Err(e));
return;
}
let _ = ready_tx.send(Ok(()));
// Serve sign/ECDH until the backend is dropped (sender closed).
while let Ok(cmd) = cmd_rx.recv() {
match cmd {
Cmd::Sign { message, reply } => {
let _ =
reply.send(session.sign_ed25519(SLOT_AUTHENTICATION, &message).ok());
}
Cmd::Ecdh { peer_pub, reply } => {
let _ =
reply.send(session.ecdh_x25519(SLOT_KEY_MANAGEMENT, &peer_pub).ok());
}
Cmd::Lock { reply } => {
let locked = session.lock().is_ok();
tracing::debug!(locked, "PIV applet re-selected (PIN cache dropped)");
let _ = reply.send(());
}
}
}
})
.map_err(|e| RatkeyError::Io(std::io::Error::other(e.to_string())))?;
// Wait for the worker to connect, match, and unlock before handing back.
ready_rx.recv().map_err(|_| RatkeyError::NoDevice)??;
let mut pub64 = [0u8; 64];
pub64[..32].copy_from_slice(&x_pub);
pub64[32..].copy_from_slice(&ed_pub);
Identity::from_backend(
&pub64,
Arc::new(HardwareBackend {
cmd_tx: Mutex::new(cmd_tx),
}),
)
.map_err(|e| RatkeyError::InvalidHwid(format!("cannot build identity: {e}")))
}
+12 -6
View File
@@ -1,9 +1,4 @@
//! PC/SC reader enumeration; filters to YubiKey 5 / Nitrokey 3 by reader name.
use pcsc::{Card, Context, Protocols, Scope, ShareMode};
use tracing::{debug, info, warn};
use crate::error::RatkeyError;
//! Device classification (always available) + PC/SC reader enumeration (behind `hardware`).
#[derive(Debug, Clone)]
pub struct DeviceInfo {
@@ -47,6 +42,14 @@ pub fn detect_device_type(reader_name: &str) -> DeviceType {
}
}
#[cfg(feature = "hardware")]
use crate::error::RatkeyError;
#[cfg(feature = "hardware")]
use pcsc::{Card, Context, Protocols, Scope, ShareMode};
#[cfg(feature = "hardware")]
use tracing::{debug, info, warn};
#[cfg(feature = "hardware")]
pub fn list_readers() -> Result<Vec<String>, RatkeyError> {
let ctx = Context::establish(Scope::User)?;
@@ -64,6 +67,7 @@ pub fn list_readers() -> Result<Vec<String>, RatkeyError> {
Ok(names)
}
#[cfg(feature = "hardware")]
pub fn detect_devices() -> Result<Vec<DeviceInfo>, RatkeyError> {
let readers = list_readers()?;
let mut devices = Vec::new();
@@ -101,6 +105,7 @@ pub fn detect_devices() -> Result<Vec<DeviceInfo>, RatkeyError> {
Ok(devices)
}
#[cfg(feature = "hardware")]
fn try_connect_piv(reader_name: &str) -> Result<DeviceInfo, RatkeyError> {
use crate::apdu;
@@ -150,6 +155,7 @@ fn try_connect_piv(reader_name: &str) -> Result<DeviceInfo, RatkeyError> {
/// Best-effort serial/firmware read. Yubico proprietary INS — Nitrokey 3 returns (None, None).
/// APDU errors are tolerated; never fails a connection.
#[cfg(feature = "hardware")]
pub(crate) fn read_identity(card: &Card, device_type: DeviceType) -> (Option<u32>, Option<String>) {
use crate::apdu;
+15 -2
View File
@@ -11,10 +11,20 @@ pub enum RatkeyError {
#[error("PIN verification failed ({remaining} attempts remaining)")]
PinFailed { remaining: u8 },
/// PIN locked (retry counter exhausted); PUK required to unlock.
#[error("PIN locked — device requires PUK to unlock")]
/// PIN locked (retry counter exhausted); PIV reset or recovery-code unlock required.
#[error("PIN locked — reset the PIV application to recover")]
PinLocked,
#[error("PIV recovery code failed ({remaining} attempts remaining)")]
PukFailed { remaining: u8 },
/// Recovery counter exhausted; PIV reset is required.
#[error("PIV recovery counter locked — reset the PIV application to recover")]
PukLocked,
#[error("PIV reset requires both retry counters to be blocked")]
ResetRequiresBlockedPinAndPuk,
#[error("PIN required — call verify_pin() first")]
PinRequired,
@@ -36,6 +46,9 @@ pub enum RatkeyError {
#[error("key mismatch: hardware public key does not match .hwid file")]
KeyMismatch,
#[error("management key authentication failed")]
ManagementAuthFailed,
#[cfg(feature = "hardware")]
#[error("PC/SC error: {0}")]
Pcsc(#[from] pcsc::Error),
+367 -79
View File
@@ -1,5 +1,6 @@
//! `HardwareIdentity`: public-key-only `Identity` + PIV session for private ops.
//! Wire-compatible with software identities.
//! `HardwareIdentity`: a public-key-only `Identity` whose private ops are served
//! by an `IdentityBackend` (real PIV session or mock). Wire-compatible with
//! software identities.
use std::path::Path;
@@ -7,71 +8,128 @@ use rns_crypto::hkdf::derive_key_64;
use rns_crypto::token;
use rns_identity::identity::Identity;
use crate::apdu::{SLOT_AUTHENTICATION as SLOT_9A, SLOT_KEY_MANAGEMENT as SLOT_9D};
use crate::error::RatkeyError;
use crate::hwid::HwidConfig;
use crate::mock::{MockPivSession, SLOT_9A, SLOT_9D};
use crate::mock::MockPivSession;
use crate::session::PivSession;
use crate::transport::PivTransport;
/// The private-key operations `HardwareIdentity` needs from a token. Implemented
/// by `PivSession<T>` (any transport) and `MockPivSession`, so the runtime
/// identity is backend-agnostic.
pub trait IdentityBackend {
fn sign_ed25519(&mut self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError>;
fn ecdh_x25519(&mut self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError>;
fn read_ed25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError>;
fn read_x25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError>;
fn is_connected(&self) -> bool;
/// Re-lock the session (require PIN again on the next op).
fn lock(&mut self) -> Result<(), RatkeyError>;
}
// Inherent methods take precedence over trait methods, so these delegate without recursing.
impl<T: PivTransport> IdentityBackend for PivSession<T> {
fn sign_ed25519(&mut self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError> {
self.sign_ed25519(slot, message)
}
fn ecdh_x25519(&mut self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError> {
self.ecdh_x25519(slot, peer_pub)
}
fn read_ed25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> {
self.read_public_key(slot)
}
fn read_x25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> {
self.read_public_key(slot)
}
fn is_connected(&self) -> bool {
self.is_connected()
}
fn lock(&mut self) -> Result<(), RatkeyError> {
self.lock()
}
}
impl IdentityBackend for MockPivSession {
fn sign_ed25519(&mut self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError> {
self.sign_ed25519(slot, message)
}
fn ecdh_x25519(&mut self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError> {
self.ecdh_x25519(slot, peer_pub)
}
fn read_ed25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> {
MockPivSession::read_ed25519_public(self, slot)
}
fn read_x25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> {
MockPivSession::read_x25519_public(self, slot)
}
fn is_connected(&self) -> bool {
self.is_connected()
}
fn lock(&mut self) -> Result<(), RatkeyError> {
self.lock();
Ok(())
}
}
pub struct HardwareIdentity {
pub identity: Identity,
pub config: HwidConfig,
ed25519_pub: [u8; 32],
x25519_pub: [u8; 32],
// Mock session storage keeps the current API testable until the real PIV
// backend is wired. See crates/rns-ratkey/HARDWARE_STATUS.md.
mock_session: Option<MockPivSession>,
backend: Box<dyn IdentityBackend>,
}
impl HardwareIdentity {
pub fn from_hwid_mock(
/// Build from a `.hwid` config + a backend. Fail-closed: the device's slot
/// public keys must match the published identity.
pub fn from_hwid(
config: HwidConfig,
session: MockPivSession,
mut backend: Box<dyn IdentityBackend>,
) -> Result<Self, RatkeyError> {
let ed25519_pub = config.ed25519_pub_bytes()?;
let x25519_pub = config.x25519_pub_bytes()?;
// Fail closed: published identity hash must map to keys actually on the device.
let session_ed = session.read_ed25519_public(SLOT_9A)?;
let session_x = session.read_x25519_public(SLOT_9D)?;
let session_ed = backend.read_ed25519_public(SLOT_9A)?;
let session_x = backend.read_x25519_public(SLOT_9D)?;
if session_ed != ed25519_pub || session_x != x25519_pub {
return Err(RatkeyError::KeyMismatch);
}
let mut pub_key_bytes = [0u8; 64];
pub_key_bytes[..32].copy_from_slice(&x25519_pub);
pub_key_bytes[32..].copy_from_slice(&ed25519_pub);
let identity = Identity::from_public_key(&pub_key_bytes)
.map_err(|e| RatkeyError::InvalidHwid(format!("cannot create identity: {e}")))?;
let identity = build_identity(&ed25519_pub, &x25519_pub)?;
Ok(Self {
identity,
config,
ed25519_pub,
x25519_pub,
mock_session: Some(session),
backend,
})
}
pub fn from_file_mock(path: &Path, session: MockPivSession) -> Result<Self, RatkeyError> {
pub fn from_file(path: &Path, backend: Box<dyn IdentityBackend>) -> Result<Self, RatkeyError> {
let config = HwidConfig::from_file(path)?;
Self::from_hwid_mock(config, session)
Self::from_hwid(config, backend)
}
/// Test-only: build without `.hwid`; skips key-mismatch guard.
pub fn from_keys_mock(
/// Test / first-bring-up: build without a `.hwid` and skip the key-mismatch
/// guard, so sign/ECDH can be validated independently of metadata pubkey
/// readback.
pub fn from_keys(
ed25519_pub: [u8; 32],
x25519_pub: [u8; 32],
session: MockPivSession,
backend: Box<dyn IdentityBackend>,
) -> Result<Self, RatkeyError> {
let identity = build_identity(&ed25519_pub, &x25519_pub)?;
let config = HwidConfig {
identity: crate::hwid::HwidIdentity {
hash: String::new(),
hash: hex::encode(identity.hash),
nickname: "test".to_string(),
created_at: 0,
},
device: crate::hwid::HwidDevice {
device_type: session.device_type.clone(),
serial: session.serial,
firmware: session.firmware.clone(),
device_type: "unknown".to_string(),
serial: 0,
firmware: "unknown".to_string(),
},
keys: crate::hwid::HwidKeys {
ed25519_pub: hex::encode(ed25519_pub),
@@ -91,22 +149,12 @@ impl HardwareIdentity {
backup: Default::default(),
};
let mut pub_key_bytes = [0u8; 64];
pub_key_bytes[..32].copy_from_slice(&x25519_pub);
pub_key_bytes[32..].copy_from_slice(&ed25519_pub);
let identity = Identity::from_public_key(&pub_key_bytes)
.map_err(|e| RatkeyError::InvalidHwid(format!("cannot create identity: {e}")))?;
let mut config = config;
// Hash is derived from the Identity so the .hwid stays consistent.
config.identity.hash = hex::encode(identity.hash);
Ok(Self {
identity,
config,
ed25519_pub,
x25519_pub,
mock_session: Some(session),
backend,
})
}
@@ -136,13 +184,11 @@ impl HardwareIdentity {
}
pub fn sign(&mut self, message: &[u8]) -> Result<[u8; 64], RatkeyError> {
let session = self.mock_session.as_mut().ok_or(RatkeyError::NoDevice)?;
session.sign_ed25519(SLOT_9A, message)
self.backend.sign_ed25519(SLOT_9A, message)
}
pub fn ecdh(&mut self, peer_pub_bytes: &[u8; 32]) -> Result<[u8; 32], RatkeyError> {
let session = self.mock_session.as_mut().ok_or(RatkeyError::NoDevice)?;
session.ecdh_x25519(SLOT_9D, peer_pub_bytes)
self.backend.ecdh_x25519(SLOT_9D, peer_pub_bytes)
}
/// Ciphertext = ephemeral_pub(32) || AES-256-CBC token. Mirrors `Identity::decrypt`
@@ -190,23 +236,38 @@ impl HardwareIdentity {
}
pub fn is_connected(&self) -> bool {
self.mock_session.as_ref().is_some_and(|s| s.is_connected())
self.backend.is_connected()
}
/// Re-lock the session; the next sign/ECDH will require the PIN again.
/// The app calls this on its session timeout and on quit.
pub fn lock(&mut self) -> Result<(), RatkeyError> {
self.backend.lock()
}
}
fn build_identity(ed25519_pub: &[u8; 32], x25519_pub: &[u8; 32]) -> Result<Identity, RatkeyError> {
let mut pub_key_bytes = [0u8; 64];
pub_key_bytes[..32].copy_from_slice(x25519_pub);
pub_key_bytes[32..].copy_from_slice(ed25519_pub);
Identity::from_public_key(&pub_key_bytes)
.map_err(|e| RatkeyError::InvalidHwid(format!("cannot create identity: {e}")))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mock::{SLOT_9A as MOCK_9A, SLOT_9D as MOCK_9D};
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
use rns_identity::identity::Identity;
#[test]
fn test_from_keys_mock() {
fn test_from_keys() {
let session = MockPivSession::with_keys();
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
let hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
let hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
assert_eq!(hw.ed25519_public(), &ed_pub);
assert_eq!(hw.x25519_public(), &x_pub);
assert!(!hw.hash_hex().is_empty());
@@ -215,9 +276,9 @@ mod tests {
#[test]
fn test_sign_and_verify() {
let session = MockPivSession::with_keys();
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
let message = b"ratkey hardware identity test";
let sig = hw.sign(message).unwrap();
@@ -231,9 +292,9 @@ mod tests {
let ed_seed = [0x42u8; 32];
let x_secret = [0x43u8; 32];
let session = MockPivSession::with_key_bytes(&ed_seed, &x_secret);
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
let mut prv_bytes = [0u8; 64];
prv_bytes[..32].copy_from_slice(&x_secret);
@@ -256,9 +317,9 @@ mod tests {
#[test]
fn test_ecdh_with_software_peer() {
let session = MockPivSession::with_keys();
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
let peer_prv = X25519PrivateKey::generate();
let peer_pub = peer_prv.public_key();
@@ -277,9 +338,9 @@ mod tests {
let ed_seed = [0x42u8; 32];
let x_secret = [0x43u8; 32];
let session = MockPivSession::with_key_bytes(&ed_seed, &x_secret);
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
let mut prv_bytes = [0u8; 64];
prv_bytes[..32].copy_from_slice(&x_secret);
@@ -296,9 +357,9 @@ mod tests {
#[test]
fn test_encrypt_from_other_identity() {
let session = MockPivSession::with_keys();
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
let _sender = Identity::new();
@@ -310,27 +371,16 @@ mod tests {
#[test]
fn test_disconnect_fails_operations() {
let session = MockPivSession::with_keys();
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
let mut session = MockPivSession::with_keys();
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
session.disconnect();
assert!(hw.is_connected());
hw.mock_session.as_mut().unwrap().disconnect();
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
assert!(!hw.is_connected());
assert!(matches!(hw.sign(b"test"), Err(RatkeyError::Disconnected)));
}
#[test]
fn test_key_mismatch_rejected() {
// from_keys_mock does not cross-check; the .hwid path does (test_hwid_key_mismatch).
let session = MockPivSession::with_keys();
let wrong_ed = [0xFFu8; 32];
let wrong_x = [0xFFu8; 32];
let _result = HardwareIdentity::from_keys_mock(wrong_ed, wrong_x, session);
}
#[test]
fn test_hwid_key_mismatch() {
let session = MockPivSession::with_keys();
@@ -363,7 +413,245 @@ mod tests {
backup: Default::default(),
};
let result = HardwareIdentity::from_hwid_mock(config, session);
let result = HardwareIdentity::from_hwid(config, Box::new(session));
assert!(matches!(result, Err(RatkeyError::KeyMismatch)));
}
// --- Real backend path over a canned-APDU transport ---------------------
// MockPivSession implements IdentityBackend directly and never touches
// PivSession. These exercise the production path (PivSession ops + its
// IdentityBackend impl + read_public_key→parse + slot routing) without a
// device. Caveat: the fake uses the *assumed* metadata layout, so it
// validates glue, not the real byte layout — that stays hardware-only.
use crate::detect::DeviceType;
use crate::session::DeviceMeta;
use crate::transport::PivTransport;
struct FakeTransport {
ed_pub: [u8; 32],
x_pub: [u8; 32],
sig: [u8; 64],
secret: [u8; 32],
}
impl FakeTransport {
fn metadata(key: &[u8; 32]) -> Vec<u8> {
// 01(algo) 04(pubkey = 86 20 <32>) + SW 90 00
let mut v = vec![0x01, 0x01, 0xE0, 0x04, 0x22, 0x86, 0x20];
v.extend_from_slice(key);
v.extend_from_slice(&[0x90, 0x00]);
v
}
}
impl PivTransport for FakeTransport {
fn transmit(&mut self, apdu: &[u8]) -> Result<Vec<u8>, RatkeyError> {
let (ins, p1, p2) = (apdu[1], apdu[2], apdu[3]);
match ins {
0xA4 => Ok(vec![0x90, 0x00]), // SELECT (applet / re-lock)
0x20 => Ok(vec![0x90, 0x00]), // VERIFY PIN
0x87 if p1 == 0xE0 => {
assert_eq!(p2, 0x9A, "sign must target slot 9A");
let mut v = vec![0x7C, 0x42, 0x82, 0x40];
v.extend_from_slice(&self.sig);
v.extend_from_slice(&[0x90, 0x00]);
Ok(v)
}
0x87 if p1 == 0xE1 => {
assert_eq!(p2, 0x9D, "ECDH must target slot 9D");
let mut v = vec![0x7C, 0x22, 0x82, 0x20];
v.extend_from_slice(&self.secret);
v.extend_from_slice(&[0x90, 0x00]);
Ok(v)
}
0xF7 => {
// GET METADATA: key keyed by requested slot, so a wrong-slot
// read returns the wrong key.
let key = match p2 {
0x9A => &self.ed_pub,
0x9D => &self.x_pub,
other => panic!("unexpected metadata slot 0x{other:02X}"),
};
Ok(Self::metadata(key))
}
other => panic!("unexpected INS 0x{other:02X}"),
}
}
fn is_connected(&self) -> bool {
true
}
}
fn fake_meta() -> DeviceMeta {
DeviceMeta {
device_type: DeviceType::YubiKey5,
serial: Some(1),
firmware: Some("5.7.4".to_string()),
}
}
#[test]
fn test_pivsession_ops_over_fake_transport() {
let ed_pub = [0x11u8; 32];
let x_pub = [0x22u8; 32];
let sig = [0x33u8; 64];
let secret = [0x44u8; 32];
let fake = FakeTransport {
ed_pub,
x_pub,
sig,
secret,
};
let mut session = PivSession::new(fake, fake_meta());
assert_eq!(session.sign_ed25519(SLOT_9A, b"msg").unwrap(), sig);
assert_eq!(session.ecdh_x25519(SLOT_9D, &[0u8; 32]).unwrap(), secret);
// read_public_key routes the slot and runs the metadata parser.
assert_eq!(session.read_public_key(SLOT_9A).unwrap(), ed_pub);
assert_eq!(session.read_public_key(SLOT_9D).unwrap(), x_pub);
// lock() re-selects the applet (SELECT APDU) without error.
session.lock().unwrap();
}
#[test]
fn test_lock_requires_pin_again() {
// End-to-end session lock on the mock path: sign works, lock, then the
// next op needs the PIN again.
let session = MockPivSession::with_keys();
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
assert!(hw.sign(b"m").is_ok());
hw.lock().unwrap();
assert!(matches!(hw.sign(b"m"), Err(RatkeyError::PinRequired)));
}
#[test]
fn test_hardware_identity_from_hwid_over_real_backend() {
// Closest mock-free representation of the runtime path: HardwareIdentity
// over a real PivSession backend — guard reads pubkeys via metadata, then
// sign dispatches to slot 9A.
let ed_prv = rns_crypto::ed25519::Ed25519PrivateKey::from_bytes(&[0x42u8; 32]);
let ed_pub = ed_prv.public_key().to_bytes();
let x_prv = X25519PrivateKey::from_bytes(&[0x43u8; 32]);
let x_pub = x_prv.public_key().to_bytes();
let sig = [0x33u8; 64];
let fake = FakeTransport {
ed_pub,
x_pub,
sig,
secret: [0x44u8; 32],
};
let session = PivSession::new(fake, fake_meta());
let config = HwidConfig {
identity: crate::hwid::HwidIdentity {
hash: "test".to_string(),
nickname: "fake".to_string(),
created_at: 0,
},
device: crate::hwid::HwidDevice {
device_type: "yubikey5".to_string(),
serial: 1,
firmware: "5.7.4".to_string(),
},
keys: crate::hwid::HwidKeys {
ed25519_pub: hex::encode(ed_pub),
x25519_pub: hex::encode(x_pub),
},
slots: crate::hwid::HwidSlots {
signing: "9A".to_string(),
encryption: "9D".to_string(),
},
policy: crate::hwid::HwidPolicy {
pin_cache_timeout: 300,
touch_signing: "always".to_string(),
touch_encryption: "cached".to_string(),
},
attestation: Default::default(),
app: Default::default(),
backup: Default::default(),
};
let mut hw = HardwareIdentity::from_hwid(config, Box::new(session)).unwrap();
assert_eq!(hw.sign(b"announce").unwrap(), sig);
}
// --- Management-key auth over a card-simulating transport ----------------
// Plays the card side of witness/challenge so the protocol direction (host
// must DECRYPT the witness, not encrypt it) is exercised without hardware.
struct MgmtFakeTransport {
alg: u8,
key: Vec<u8>,
witness: [u8; 16],
}
fn wrap_7c(tag: u8, payload: &[u8]) -> Vec<u8> {
let mut v = vec![0x7C, (payload.len() + 2) as u8, tag, payload.len() as u8];
v.extend_from_slice(payload);
v.extend_from_slice(&[0x90, 0x00]); // SW OK
v
}
impl PivTransport for MgmtFakeTransport {
fn transmit(&mut self, apdu: &[u8]) -> Result<Vec<u8>, RatkeyError> {
let (ins, p2) = (apdu[1], apdu[3]);
match (ins, p2) {
(0xF7, 0x9B) => Ok(vec![0x01, 0x01, self.alg, 0x90, 0x00]), // metadata: alg
(0x87, 0x9B) => {
let data = &apdu[5..];
let witness_field = crate::apdu::parse_auth_witness(data).unwrap();
if witness_field.is_empty() {
// witness request → return the witness encrypted with the key
let enc =
crate::mgmt::ecb_encrypt(self.alg, &self.key, &self.witness).unwrap();
Ok(wrap_7c(0x80, &enc))
} else if witness_field.as_slice() == self.witness {
// correct decrypted witness → encrypt the host's challenge
let challenge = &data[data.len() - 16..];
let enc = crate::mgmt::ecb_encrypt(self.alg, &self.key, challenge).unwrap();
Ok(wrap_7c(0x82, &enc))
} else {
// wrong witness → card rejects (security status not satisfied)
Ok(vec![0x69, 0x82])
}
}
_ => panic!("unexpected mgmt apdu ins=0x{ins:02X} p2=0x{p2:02X}"),
}
}
fn is_connected(&self) -> bool {
true
}
}
#[test]
fn test_authenticate_management_key_success() {
let key = vec![0x5Au8; 24]; // AES-192
let fake = MgmtFakeTransport {
alg: crate::apdu::MGMT_ALG_AES192,
key: key.clone(),
witness: [0x77; 16],
};
let mut session = PivSession::new(fake, fake_meta());
session.authenticate_management_key(&key).unwrap();
}
#[test]
fn test_authenticate_management_key_wrong_key() {
// Host's wrong key → decrypted witness mismatches → card rejects → mapped error.
let fake = MgmtFakeTransport {
alg: crate::apdu::MGMT_ALG_AES192,
key: vec![0x5Au8; 24],
witness: [0x77; 16],
};
let mut session = PivSession::new(fake, fake_meta());
let wrong = vec![0x00u8; 24];
assert!(matches!(
session.authenticate_management_key(&wrong),
Err(RatkeyError::ManagementAuthFailed)
));
}
}
+22 -6
View File
@@ -1,24 +1,40 @@
//! Hardware-backed identity (YubiKey 5, Nitrokey 3) via PIV. Ed25519 sign + X25519
//! ECDH keys live on-device; only public keys and results leave the token.
//! Wire-compatible with software identities. `hardware` feature enables real PIV via `pcsc`.
//! Wire-compatible with software identities.
//!
//! The PIV protocol logic (`PivSession`, `apdu`) is transport-agnostic; the
//! `PivTransport` seam isolates platform access. The `hardware` feature adds the
//! PC/SC transport (`PcscTransport`) and its `connect()` entry points. Mobile
//! NFC/USB transports implement `PivTransport` from the application layer.
pub mod apdu;
pub mod attestation;
#[cfg(feature = "hardware")]
pub mod backend;
pub mod detect;
pub mod error;
pub mod hardware;
pub mod hwid;
pub mod mgmt;
pub mod mock;
pub mod pin;
pub mod provision;
#[cfg(feature = "hardware")]
pub mod detect;
#[cfg(feature = "hardware")]
pub mod seed;
pub mod session;
pub mod transport;
pub use error::RatkeyError;
pub use hardware::HardwareIdentity;
pub use hardware::{HardwareIdentity, IdentityBackend};
pub use hwid::HwidConfig;
pub use mock::MockPivSession;
pub use pin::PinCache;
pub use provision::{ProvisionConfig, ProvisionResult};
pub use session::{DeviceMeta, PivSession};
pub use transport::PivTransport;
#[cfg(feature = "hardware")]
pub use backend::{HardwareBackend, load_hardware_identity};
#[cfg(feature = "hardware")]
pub use session::PcscPivSession;
#[cfg(feature = "hardware")]
pub use transport::PcscTransport;
+203
View File
@@ -0,0 +1,203 @@
//! PIV management-key crypto: ECB single/multi-block for the witness/challenge
//! mutual authentication. Dispatch is on the management-key *algorithm* byte, not
//! the key length — AES-192 and TDES both use 24-byte keys, but differ in block
//! size (AES 16, TDES 8). TDES (3DES EDE3) is the pre-5.7 YubiKey factory default.
use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit, generic_array::GenericArray};
use aes::{Aes128, Aes192, Aes256};
use des::TdesEde3;
use crate::apdu;
use crate::error::RatkeyError;
const AES_BLOCK: usize = 16;
const DES_BLOCK: usize = 8;
/// Required key length for a management-key algorithm, or `None` if unsupported.
pub fn key_len(alg: u8) -> Option<usize> {
match alg {
apdu::MGMT_ALG_TDES => Some(24), // 3DES EDE3: three 8-byte DES subkeys
apdu::MGMT_ALG_AES128 => Some(16),
apdu::MGMT_ALG_AES192 => Some(24),
apdu::MGMT_ALG_AES256 => Some(32),
_ => None,
}
}
/// ECB block size (challenge length) for a supported algorithm.
pub fn block_len(alg: u8) -> Option<usize> {
match alg {
apdu::MGMT_ALG_TDES => Some(DES_BLOCK),
apdu::MGMT_ALG_AES128 | apdu::MGMT_ALG_AES192 | apdu::MGMT_ALG_AES256 => Some(AES_BLOCK),
_ => None,
}
}
fn check(alg: u8, key: &[u8], data: &[u8]) -> Result<(), RatkeyError> {
let n = key_len(alg).ok_or_else(|| {
RatkeyError::UnsupportedDevice(format!("unsupported management-key algorithm 0x{alg:02X}"))
})?;
if key.len() != n {
return Err(RatkeyError::InvalidHwid(format!(
"management key length {} does not match algorithm 0x{alg:02X} (expected {n})",
key.len()
)));
}
let block = block_len(alg).expect("supported alg has a block size");
if data.is_empty() || data.len() % block != 0 {
return Err(RatkeyError::InvalidHwid(format!(
"management-key ECB input not block-aligned: {} bytes (block {block})",
data.len()
)));
}
Ok(())
}
pub fn ecb_encrypt(alg: u8, key: &[u8], data: &[u8]) -> Result<Vec<u8>, RatkeyError> {
check(alg, key, data)?;
let mut out = data.to_vec();
process(alg, key, &mut out, false)?;
Ok(out)
}
pub fn ecb_decrypt(alg: u8, key: &[u8], data: &[u8]) -> Result<Vec<u8>, RatkeyError> {
check(alg, key, data)?;
let mut out = data.to_vec();
process(alg, key, &mut out, true)?;
Ok(out)
}
fn process(alg: u8, key: &[u8], buf: &mut [u8], decrypt: bool) -> Result<(), RatkeyError> {
macro_rules! run {
($cipher:ty, $block:expr) => {{
let cipher = <$cipher>::new_from_slice(key)
.map_err(|_| RatkeyError::InvalidHwid("invalid management key".to_string()))?;
for chunk in buf.chunks_mut($block) {
let block = GenericArray::from_mut_slice(chunk);
if decrypt {
cipher.decrypt_block(block);
} else {
cipher.encrypt_block(block);
}
}
}};
}
match alg {
apdu::MGMT_ALG_TDES => run!(TdesEde3, DES_BLOCK),
apdu::MGMT_ALG_AES128 => run!(Aes128, AES_BLOCK),
apdu::MGMT_ALG_AES192 => run!(Aes192, AES_BLOCK),
apdu::MGMT_ALG_AES256 => run!(Aes256, AES_BLOCK),
_ => {
return Err(RatkeyError::UnsupportedDevice(format!(
"unsupported management-key algorithm 0x{alg:02X}"
)));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
// FIPS-197 Appendix C.2 AES-192 known-answer vector.
const KAT_KEY: [u8; 24] = [
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
];
const KAT_PT: [u8; 16] = [
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee,
0xff,
];
const KAT_CT: [u8; 16] = [
0xdd, 0xa9, 0x7c, 0xa4, 0x86, 0x4c, 0xdf, 0xe0, 0x6e, 0xaf, 0x70, 0xa0, 0xec, 0x0d, 0x71,
0x91,
];
#[test]
fn test_aes192_kat_encrypt() {
assert_eq!(
ecb_encrypt(apdu::MGMT_ALG_AES192, &KAT_KEY, &KAT_PT).unwrap(),
KAT_CT.to_vec()
);
}
#[test]
fn test_aes192_kat_decrypt() {
assert_eq!(
ecb_decrypt(apdu::MGMT_ALG_AES192, &KAT_KEY, &KAT_CT).unwrap(),
KAT_PT.to_vec()
);
}
// 3DES EDE3 with three identical 8-byte subkeys reduces to single-DES, so the
// canonical FIPS-81 single-DES ECB vector is a known-answer for our EDE3 path:
// DES(0x0123456789ABCDEF, "Now is t") = 0x3FA40E8A984D4815.
const TDES_KAT_KEY: [u8; 24] = [
0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD,
0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF,
];
const TDES_KAT_PT: [u8; 8] = [0x4E, 0x6F, 0x77, 0x20, 0x69, 0x73, 0x20, 0x74];
const TDES_KAT_CT: [u8; 8] = [0x3F, 0xA4, 0x0E, 0x8A, 0x98, 0x4D, 0x48, 0x15];
#[test]
fn test_round_trip_all_aes() {
for (alg, klen) in [
(apdu::MGMT_ALG_AES128, 16usize),
(apdu::MGMT_ALG_AES192, 24),
(apdu::MGMT_ALG_AES256, 32),
] {
let key = vec![0x5Au8; klen];
let pt = [0x42u8; 16];
let ct = ecb_encrypt(alg, &key, &pt).unwrap();
assert_ne!(ct, pt.to_vec());
assert_eq!(ecb_decrypt(alg, &key, &ct).unwrap(), pt.to_vec());
}
}
#[test]
fn test_wrong_key_length_rejected() {
// AES-192 with a 16-byte key (would silently be AES-128 if not checked).
assert!(ecb_encrypt(apdu::MGMT_ALG_AES192, &[0u8; 16], &[0u8; 16]).is_err());
}
#[test]
fn test_tdes_kat() {
assert_eq!(key_len(apdu::MGMT_ALG_TDES), Some(24));
assert_eq!(block_len(apdu::MGMT_ALG_TDES), Some(8));
assert_eq!(
ecb_encrypt(apdu::MGMT_ALG_TDES, &TDES_KAT_KEY, &TDES_KAT_PT).unwrap(),
TDES_KAT_CT.to_vec()
);
assert_eq!(
ecb_decrypt(apdu::MGMT_ALG_TDES, &TDES_KAT_KEY, &TDES_KAT_CT).unwrap(),
TDES_KAT_PT.to_vec()
);
}
#[test]
fn test_tdes_round_trip_distinct_keys() {
// Three distinct subkeys exercise the real EDE3 / DED3 inverse, not the
// degenerate single-DES reduction.
let mut key = [0u8; 24];
for (i, b) in key.iter_mut().enumerate() {
*b = (i as u8).wrapping_mul(7).wrapping_add(1);
}
let pt = [0x42u8; 8];
let ct = ecb_encrypt(apdu::MGMT_ALG_TDES, &key, &pt).unwrap();
assert_ne!(ct, pt.to_vec());
assert_eq!(
ecb_decrypt(apdu::MGMT_ALG_TDES, &key, &ct).unwrap(),
pt.to_vec()
);
}
#[test]
fn test_non_block_aligned_rejected() {
assert!(ecb_encrypt(apdu::MGMT_ALG_AES192, &KAT_KEY, &[0u8; 15]).is_err());
assert!(ecb_encrypt(apdu::MGMT_ALG_AES192, &KAT_KEY, &[]).is_err());
// TDES uses an 8-byte block: 8 is valid, 7 is not.
assert!(ecb_encrypt(apdu::MGMT_ALG_TDES, &TDES_KAT_KEY, &[0u8; 8]).is_ok());
assert!(ecb_encrypt(apdu::MGMT_ALG_TDES, &TDES_KAT_KEY, &[0u8; 7]).is_err());
}
}
+133
View File
@@ -46,6 +46,8 @@ impl SlotState {
#[derive(Debug, Clone)]
pub enum MockOperation {
PinVerify { success: bool },
PinUnblock { success: bool },
ResetPiv { success: bool },
GenerateEd25519 { slot: u8 },
GenerateX25519 { slot: u8 },
SignEd25519 { slot: u8, data_len: usize },
@@ -56,8 +58,10 @@ pub enum MockOperation {
pub struct MockPivSession {
slots: HashMap<u8, SlotState>,
pin: String,
puk: String,
pin_verified: bool,
pin_retries: u8,
puk_retries: u8,
max_retries: u8,
connected: bool,
/// True: `TouchPolicy::Always` slots reject ops. `simulate_touch()` clears.
@@ -77,8 +81,10 @@ impl MockPivSession {
Self {
slots,
pin: "123456".to_string(),
puk: "12345678".to_string(),
pin_verified: false,
pin_retries: 3,
puk_retries: 3,
max_retries: 3,
connected: true,
touch_required: true,
@@ -136,6 +142,10 @@ impl MockPivSession {
self.pin_verified = false;
}
pub fn set_puk(&mut self, puk: &str) {
self.puk = puk.to_string();
}
pub fn disconnect(&mut self) {
self.connected = false;
}
@@ -145,6 +155,12 @@ impl MockPivSession {
self.pin_verified = false;
}
/// Re-lock: clears PIN verification so the next op needs `verify_pin` again.
/// Mirrors `PivSession::lock` (which re-selects the applet on real hardware).
pub fn lock(&mut self) {
self.pin_verified = false;
}
pub fn simulate_touch(&mut self) {
self.touch_required = false;
}
@@ -211,6 +227,58 @@ impl MockPivSession {
}
}
pub fn unblock_pin(&mut self, puk: &str, new_pin: &str) -> Result<(), RatkeyError> {
self.check_connected()?;
if self.puk_retries == 0 {
self.operations
.push(MockOperation::PinUnblock { success: false });
return Err(RatkeyError::PukLocked);
}
if puk == self.puk {
self.pin = new_pin.to_string();
self.pin_verified = true;
self.pin_retries = self.max_retries;
self.puk_retries = self.max_retries;
self.operations
.push(MockOperation::PinUnblock { success: true });
Ok(())
} else {
self.puk_retries -= 1;
self.operations
.push(MockOperation::PinUnblock { success: false });
if self.puk_retries == 0 {
Err(RatkeyError::PukLocked)
} else {
Err(RatkeyError::PukFailed {
remaining: self.puk_retries,
})
}
}
}
pub fn reset_piv(&mut self) -> Result<(), RatkeyError> {
self.check_connected()?;
if self.pin_retries != 0 || self.puk_retries != 0 {
self.operations
.push(MockOperation::ResetPiv { success: false });
return Err(RatkeyError::ResetRequiresBlockedPinAndPuk);
}
self.slots.insert(SLOT_9A, SlotState::empty());
self.slots.insert(SLOT_9D, SlotState::empty());
self.pin = "123456".to_string();
self.puk = "12345678".to_string();
self.pin_verified = false;
self.pin_retries = self.max_retries;
self.puk_retries = self.max_retries;
self.touch_required = true;
self.operations
.push(MockOperation::ResetPiv { success: true });
Ok(())
}
pub fn generate_ed25519(
&mut self,
slot: u8,
@@ -374,6 +442,7 @@ impl Default for MockPivSession {
impl Drop for MockPivSession {
fn drop(&mut self) {
self.pin.zeroize();
self.puk.zeroize();
}
}
@@ -412,6 +481,70 @@ mod tests {
assert!(matches!(err, RatkeyError::PinLocked));
}
#[test]
fn test_pin_unblock_with_puk() {
let mut session = MockPivSession::new();
let _ = session.verify_pin("wrong");
let _ = session.verify_pin("wrong");
let _ = session.verify_pin("wrong");
assert!(matches!(
session.verify_pin("123456"),
Err(RatkeyError::PinLocked)
));
session.unblock_pin("12345678", "654321").unwrap();
assert!(session.verify_pin("654321").is_ok());
assert!(matches!(
session.verify_pin("123456"),
Err(RatkeyError::PinFailed { .. })
));
}
#[test]
fn test_pin_unblock_wrong_puk_locks_puk() {
let mut session = MockPivSession::new();
let _ = session.verify_pin("wrong");
let _ = session.verify_pin("wrong");
let _ = session.verify_pin("wrong");
let err = session.unblock_pin("bad", "654321").unwrap_err();
assert!(matches!(err, RatkeyError::PukFailed { remaining: 2 }));
let _ = session.unblock_pin("bad", "654321");
let err = session.unblock_pin("bad", "654321").unwrap_err();
assert!(matches!(err, RatkeyError::PukLocked));
assert!(matches!(
session.unblock_pin("12345678", "654321"),
Err(RatkeyError::PukLocked)
));
}
#[test]
fn test_reset_piv_requires_blocked_pin_and_puk() {
let mut session = MockPivSession::with_keys();
assert!(matches!(
session.reset_piv(),
Err(RatkeyError::ResetRequiresBlockedPinAndPuk)
));
}
#[test]
fn test_reset_piv_clears_keys_and_restores_defaults() {
let mut session = MockPivSession::with_keys();
let _ = session.verify_pin("badpin");
let _ = session.verify_pin("badpin");
let _ = session.verify_pin("badpin");
let _ = session.unblock_pin("badpuk", "654321");
let _ = session.unblock_pin("badpuk", "654321");
let _ = session.unblock_pin("badpuk", "654321");
session.reset_piv().unwrap();
session.verify_pin("123456").unwrap();
assert!(matches!(
session.sign_ed25519(SLOT_9A, b"test"),
Err(RatkeyError::EmptySlot { slot: SLOT_9A })
));
}
#[test]
fn test_pin_retry_reset() {
let mut session = MockPivSession::new();
+166 -1
View File
@@ -5,9 +5,13 @@ use std::time::{SystemTime, UNIX_EPOCH};
use rns_crypto::sha::truncated_hash;
use crate::apdu;
use crate::error::RatkeyError;
use crate::hwid::*;
use crate::mock::{MockPivSession, SLOT_9A, SLOT_9D, TouchPolicy};
use crate::seed;
use crate::session::PivSession;
use crate::transport::PivTransport;
#[derive(Debug, Clone)]
pub struct ProvisionResult {
@@ -132,6 +136,167 @@ pub fn compute_identity_hash(ed25519_pub: &[u8; 32], x25519_pub: &[u8; 32]) -> [
truncated_hash(&pub_key_bytes)
}
fn touch_byte(tp: TouchPolicy) -> u8 {
match tp {
TouchPolicy::Never => apdu::TOUCH_POLICY_NEVER,
TouchPolicy::Always => apdu::TOUCH_POLICY_ALWAYS,
TouchPolicy::Cached => apdu::TOUCH_POLICY_CACHED,
}
}
fn touch_str(tp: TouchPolicy) -> &'static str {
match tp {
TouchPolicy::Never => "never",
TouchPolicy::Always => "always",
TouchPolicy::Cached => "cached",
}
}
/// Recoverable provision / restore: derive the identity from `mnemonic`, import
/// both keys into the token (PIN-once + configured touch policy), and write the
/// `.hwid`. Requires the management key. The session must already be connected.
pub fn import_recoverable_identity<T: PivTransport>(
session: &mut PivSession<T>,
mgmt_key: &[u8],
config: &ProvisionConfig,
mnemonic: &str,
) -> Result<ProvisionResult, RatkeyError> {
let derived = seed::derive_identity(mnemonic)?;
session.authenticate_management_key(mgmt_key)?;
session.import_ed25519(
SLOT_9A,
&derived.ed25519_seed,
Some(apdu::PIN_POLICY_ONCE),
Some(touch_byte(config.touch_signing)),
)?;
session.import_x25519(
SLOT_9D,
&derived.x25519_secret,
Some(apdu::PIN_POLICY_ONCE),
Some(touch_byte(config.touch_encryption)),
)?;
finalize_provision(session, config, derived.ed25519_pub, derived.x25519_pub)
}
/// On-device provisioning (no seed backup): authenticate, generate both keys on
/// the token, and write the `.hwid`. Requires the management key.
pub fn provision_hardware_only<T: PivTransport>(
session: &mut PivSession<T>,
mgmt_key: &[u8],
config: &ProvisionConfig,
) -> Result<ProvisionResult, RatkeyError> {
session.authenticate_management_key(mgmt_key)?;
let ed_pub = session.generate_ed25519(
SLOT_9A,
Some(apdu::PIN_POLICY_ONCE),
Some(touch_byte(config.touch_signing)),
)?;
let x_pub = session.generate_x25519(
SLOT_9D,
Some(apdu::PIN_POLICY_ONCE),
Some(touch_byte(config.touch_encryption)),
)?;
finalize_provision(session, config, ed_pub, x_pub)
}
/// Register an already-provisioned token: read its slot public keys and write a
/// `.hwid` for it (import-existing). No key material is created; no mgmt key needed.
pub fn read_existing<T: PivTransport>(
session: &mut PivSession<T>,
config: &ProvisionConfig,
) -> Result<ProvisionResult, RatkeyError> {
let ed_pub = session.read_public_key(SLOT_9A)?;
let x_pub = session.read_public_key(SLOT_9D)?;
finalize_provision(session, config, ed_pub, x_pub)
}
/// Build the `.hwid` from the provisioned public keys + device metadata, writing
/// it under `config.identities_dir` if set. Shared by all real-hardware flows.
fn finalize_provision<T: PivTransport>(
session: &PivSession<T>,
config: &ProvisionConfig,
ed25519_pub: [u8; 32],
x25519_pub: [u8; 32],
) -> Result<ProvisionResult, RatkeyError> {
let identity_hash = compute_identity_hash(&ed25519_pub, &x25519_pub);
let identity_hash_hex = hex::encode(identity_hash);
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let hwid = HwidConfig {
identity: HwidIdentity {
hash: identity_hash_hex.clone(),
nickname: config.nickname.clone(),
created_at: now,
},
device: HwidDevice {
device_type: session.device_type().as_str().to_string(),
serial: session.serial().unwrap_or(0),
firmware: session.firmware().unwrap_or("unknown").to_string(),
},
keys: HwidKeys {
ed25519_pub: hex::encode(ed25519_pub),
x25519_pub: hex::encode(x25519_pub),
},
slots: HwidSlots {
signing: "9A".to_string(),
encryption: "9D".to_string(),
},
policy: HwidPolicy {
pin_cache_timeout: 300,
touch_signing: touch_str(config.touch_signing).to_string(),
touch_encryption: touch_str(config.touch_encryption).to_string(),
},
attestation: HwidAttestation::default(),
app: HwidApp::default(),
backup: HwidBackup::default(),
};
let hwid_path = if let Some(ref dir) = config.identities_dir {
let identity_dir = dir.join(&identity_hash_hex);
std::fs::create_dir_all(&identity_dir)?;
let path = identity_dir.join("identity.hwid");
hwid.to_file(&path)?;
Some(path)
} else {
None
};
Ok(ProvisionResult {
config: hwid,
ed25519_pub,
x25519_pub,
identity_hash,
identity_hash_hex,
hwid_path,
})
}
/// Recoverable provisioning: generate a fresh 12-word mnemonic, import the
/// derived identity, and return both the result and the mnemonic to show once.
pub fn provision_recoverable<T: PivTransport>(
session: &mut PivSession<T>,
mgmt_key: &[u8],
config: &ProvisionConfig,
) -> Result<(ProvisionResult, String), RatkeyError> {
let mnemonic = seed::generate_mnemonic()?;
let result = import_recoverable_identity(session, mgmt_key, config, &mnemonic)?;
Ok((result, mnemonic))
}
/// Restore a recoverable identity from an existing 12-word mnemonic onto a token.
pub fn restore<T: PivTransport>(
session: &mut PivSession<T>,
mgmt_key: &[u8],
config: &ProvisionConfig,
mnemonic: &str,
) -> Result<ProvisionResult, RatkeyError> {
import_recoverable_identity(session, mgmt_key, config, mnemonic)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -218,7 +383,7 @@ mod tests {
let result = provision_mock(&mut session, &config).unwrap();
let path = result.hwid_path.as_ref().unwrap();
let mut hw = crate::HardwareIdentity::from_file_mock(path, session).unwrap();
let mut hw = crate::HardwareIdentity::from_file(path, Box::new(session)).unwrap();
let message = b"provisioned and loaded";
let sig = hw.sign(message).unwrap();
+148
View File
@@ -0,0 +1,148 @@
//! BIP-39 recoverable backup: a deterministic Reticulum identity derived from a
//! 12-word mnemonic. Interop-compatible with ratkey-py (derivation scheme v1):
//!
//! ```text
//! mnemonic (12 words)
//! -> PBKDF2-SHA512 (BIP-39, passphrase="") -> 64-byte seed
//! -> HKDF-SHA256(seed, salt="ratkey-ed25519-v1", info) -> 32-byte Ed25519 seed
//! -> HKDF-SHA256(seed, salt="ratkey-x25519-v1", info) -> 32-byte X25519 secret
//! ```
//!
//! The seed phrase is a second attack surface (it reconstructs the private keys
//! and is not protected by the device PIN). Callers must surface that tradeoff.
use bip39::{Language, Mnemonic};
use hkdf::Hkdf;
use sha2::Sha256;
use zeroize::Zeroize;
use rns_crypto::ed25519::Ed25519PrivateKey;
use rns_crypto::x25519::X25519PrivateKey;
use crate::error::RatkeyError;
const ED25519_SALT: &[u8] = b"ratkey-ed25519-v1";
const X25519_SALT: &[u8] = b"ratkey-x25519-v1";
const HKDF_INFO: &[u8] = b"ratkey identity key derivation";
const MNEMONIC_WORDS: usize = 12;
const MNEMONIC_ENTROPY_BYTES: usize = 16;
/// Key material derived from a mnemonic. The two secret fields are zeroized on drop.
pub struct DerivedIdentity {
pub ed25519_seed: [u8; 32],
pub x25519_secret: [u8; 32],
pub ed25519_pub: [u8; 32],
pub x25519_pub: [u8; 32],
}
impl Drop for DerivedIdentity {
fn drop(&mut self) {
self.ed25519_seed.zeroize();
self.x25519_secret.zeroize();
}
}
/// Generate a fresh 12-word (128-bit) BIP-39 English mnemonic.
pub fn generate_mnemonic() -> Result<String, RatkeyError> {
let mut entropy = [0u8; MNEMONIC_ENTROPY_BYTES];
entropy.copy_from_slice(&rns_crypto::random::random_bytes(MNEMONIC_ENTROPY_BYTES));
let result = Mnemonic::from_entropy_in(Language::English, &entropy)
.map(|m| m.to_string())
.map_err(|e| RatkeyError::InvalidHwid(format!("mnemonic generation failed: {e}")));
entropy.zeroize();
result
}
/// True for a valid 12-word BIP-39 English mnemonic (wordlist + checksum).
pub fn validate_mnemonic(words: &str) -> bool {
let w = words.trim();
w.split_whitespace().count() == MNEMONIC_WORDS
&& Mnemonic::parse_in_normalized(Language::English, w).is_ok()
}
/// Derive the Reticulum identity keys from a 12-word mnemonic (scheme v1).
pub fn derive_identity(words: &str) -> Result<DerivedIdentity, RatkeyError> {
if !validate_mnemonic(words) {
return Err(RatkeyError::InvalidHwid(
"invalid seed phrase: expected 12 valid BIP-39 English words".to_string(),
));
}
let mnemonic = Mnemonic::parse_in_normalized(Language::English, words.trim())
.map_err(|e| RatkeyError::InvalidHwid(format!("invalid seed phrase: {e}")))?;
let mut seed = mnemonic.to_seed("");
let ed25519_seed = hkdf32(&seed, ED25519_SALT)?;
let x25519_secret = hkdf32(&seed, X25519_SALT)?;
seed.zeroize();
let ed25519_pub = Ed25519PrivateKey::from_bytes(&ed25519_seed)
.public_key()
.to_bytes();
let x25519_pub = X25519PrivateKey::from_bytes(&x25519_secret)
.public_key()
.to_bytes();
Ok(DerivedIdentity {
ed25519_seed,
x25519_secret,
ed25519_pub,
x25519_pub,
})
}
fn hkdf32(ikm: &[u8], salt: &[u8]) -> Result<[u8; 32], RatkeyError> {
let hk = Hkdf::<Sha256>::new(Some(salt), ikm);
let mut okm = [0u8; 32];
hk.expand(HKDF_INFO, &mut okm)
.map_err(|_| RatkeyError::InvalidHwid("HKDF expand failed".to_string()))?;
Ok(okm)
}
#[cfg(test)]
mod tests {
use super::*;
fn test_mnemonic() -> String {
// Standard BIP-39 all-zero-entropy vector (checksum word "about").
"abandon ".repeat(11) + "about"
}
#[test]
fn test_derive_matches_python_vector() {
// Cross-checked against ratkey-py's derivation (scheme v1).
let d = derive_identity(&test_mnemonic()).unwrap();
assert_eq!(
hex::encode(d.ed25519_seed),
"dfbf047515deef875db5884b7d1ec625f57641adb7265153a2c3b775ed04386f"
);
assert_eq!(
hex::encode(d.x25519_secret),
"20c92deea11650882a353b4e9928602d247b4ee689c1e0e10dc77637dbe3b33f"
);
}
#[test]
fn test_derive_is_deterministic() {
let a = derive_identity(&test_mnemonic()).unwrap();
let b = derive_identity(&test_mnemonic()).unwrap();
assert_eq!(a.ed25519_pub, b.ed25519_pub);
assert_eq!(a.x25519_pub, b.x25519_pub);
}
#[test]
fn test_validate_rejects_bad_input() {
assert!(!validate_mnemonic("not a real phrase"));
assert!(!validate_mnemonic(&"abandon ".repeat(12))); // 12 abandon = bad checksum
assert!(validate_mnemonic(&test_mnemonic()));
}
#[test]
fn test_generate_roundtrips() {
let m = generate_mnemonic().unwrap();
assert_eq!(m.split_whitespace().count(), MNEMONIC_WORDS);
assert!(validate_mnemonic(&m));
// A generated phrase derives a stable identity.
let d = derive_identity(&m).unwrap();
assert_ne!(d.ed25519_pub, [0u8; 32]);
}
}
+343 -98
View File
@@ -1,70 +1,43 @@
//! Real PIV session over PC/SC (YubiKey 5, Nitrokey 3).
//! Requires `hardware` feature + PC/SC daemon (macOS CryptoTokenKit / Linux pcscd / Windows WinSCard).
use pcsc::{Card, Context, Protocols, Scope, ShareMode};
use tracing::{debug, warn};
use zeroize::Zeroize;
//! Transport-agnostic PIV session. Every PIV operation is built on `apdu` plus a
//! `PivTransport`; the transport is the only platform-specific part (see `transport`).
//! `hardware` feature adds the PC/SC `connect()` entry points.
use crate::apdu;
use crate::detect::DeviceType;
use crate::error::RatkeyError;
use crate::pin::PinCache;
use crate::transport::PivTransport;
const MAX_RESPONSE: usize = 4096;
/// Device identity captured once at connect time; no per-operation cost.
pub struct DeviceMeta {
pub device_type: DeviceType,
pub serial: Option<u32>,
pub firmware: Option<String>,
}
pub struct PivSession {
card: Card,
pub struct PivSession<T: PivTransport> {
transport: T,
device_type: DeviceType,
reader_name: String,
serial: Option<u32>,
firmware: Option<String>,
pin_cache: PinCache,
}
impl PivSession {
pub fn connect() -> Result<Self, RatkeyError> {
let devices = crate::detect::detect_devices()?;
let device = devices.first().ok_or(RatkeyError::NoDevice)?;
Self::connect_reader(&device.reader_name)
}
pub fn connect_reader(reader_name: &str) -> Result<Self, RatkeyError> {
let ctx = Context::establish(Scope::User)?;
let reader = std::ffi::CString::new(reader_name)
.map_err(|_| RatkeyError::UnsupportedDevice(reader_name.to_string()))?;
let card = ctx.connect(&reader, ShareMode::Shared, Protocols::ANY)?;
let resp = transmit(&card, &apdu::select_piv())?;
apdu::check_response(&resp)?;
let device_type = crate::detect::detect_device_type(reader_name);
debug!(
"PIV session established with {} ({})",
reader_name,
device_type.as_str()
);
let (serial, firmware) = crate::detect::read_identity(&card, device_type);
Ok(Self {
card,
device_type,
reader_name: reader_name.to_string(),
serial,
firmware,
impl<T: PivTransport> PivSession<T> {
pub fn new(transport: T, meta: DeviceMeta) -> Self {
Self {
transport,
device_type: meta.device_type,
serial: meta.serial,
firmware: meta.firmware,
pin_cache: PinCache::default_timeout(),
})
}
}
pub fn device_type(&self) -> DeviceType {
self.device_type
}
pub fn reader_name(&self) -> &str {
&self.reader_name
}
pub fn serial(&self) -> Option<u32> {
self.serial
}
@@ -73,102 +46,374 @@ impl PivSession {
self.firmware.as_deref()
}
/// Probes the attestation slot (F9) — always present on provisioned tokens.
pub fn is_connected(&self) -> bool {
let cmd = apdu::get_metadata(apdu::SLOT_ATTESTATION);
let mut buf = vec![0u8; 256];
self.card.transmit(&cmd, &mut buf).is_ok()
self.transport.is_connected()
}
/// Re-locks the card: re-selects the PIV applet (resetting the on-card PIN
/// verification) and clears the cached PIN, so the next private-key op needs
/// a fresh `verify_pin`. This is the mechanism behind the app-side session
/// timeout / lock-on-quit.
pub fn lock(&mut self) -> Result<(), RatkeyError> {
let resp = self.transport.transmit(&apdu::select_piv())?;
apdu::check_response(&resp)?;
self.pin_cache.clear();
Ok(())
}
pub fn verify_pin(&mut self, pin: &str) -> Result<(), RatkeyError> {
let cmd = apdu::verify_pin(pin);
let resp = transmit(&self.card, &cmd)?;
// PIN-bearing APDU buffers are wiped once transmitted.
let cmd = zeroize::Zeroizing::new(apdu::verify_pin(pin));
let resp = self.transport.transmit(&cmd)?;
apdu::check_response(&resp)?;
self.pin_cache.cache(pin);
debug!("PIN verified");
Ok(())
}
pub fn change_pin(&mut self, old_pin: &str, new_pin: &str) -> Result<(), RatkeyError> {
let cmd = apdu::change_pin(old_pin, new_pin);
let resp = transmit(&self.card, &cmd)?;
let cmd = zeroize::Zeroizing::new(apdu::change_pin(old_pin, new_pin));
let resp = self.transport.transmit(&cmd)?;
apdu::check_response(&resp)?;
self.pin_cache.cache(new_pin);
debug!("PIN changed");
Ok(())
}
pub fn unblock_pin(&mut self, puk: &str, new_pin: &str) -> Result<(), RatkeyError> {
let cmd = zeroize::Zeroizing::new(apdu::reset_retry(puk, new_pin));
let resp = self.transport.transmit(&cmd)?;
match apdu::check_response(&resp) {
Ok(_) => {
self.pin_cache.cache(new_pin);
Ok(())
}
Err(RatkeyError::PinFailed { remaining }) => Err(RatkeyError::PukFailed { remaining }),
Err(RatkeyError::PinLocked) => Err(RatkeyError::PukLocked),
Err(other) => Err(other),
}
}
pub fn reset_piv(&mut self) -> Result<(), RatkeyError> {
let resp = self.transport.transmit(&apdu::reset_piv())?;
match apdu::check_response(&resp) {
Ok(_) => {
self.pin_cache.clear();
Ok(())
}
Err(RatkeyError::Apdu {
sw1: 0x69,
sw2: 0x85,
}) => Err(RatkeyError::ResetRequiresBlockedPinAndPuk),
Err(other) => Err(other),
}
}
pub fn generate_ed25519(
&self,
&mut self,
slot: u8,
pin_policy: Option<u8>,
touch_policy: Option<u8>,
) -> Result<[u8; 32], RatkeyError> {
let cmd = apdu::generate_key(slot, apdu::ALG_ED25519, pin_policy, touch_policy);
let resp = transmit(&self.card, &cmd)?;
let resp = self.transport.transmit(&apdu::generate_key(
slot,
apdu::ALG_ED25519,
pin_policy,
touch_policy,
))?;
let data = apdu::check_response(&resp)?;
apdu::parse_generate_response(data)
}
pub fn generate_x25519(
&self,
&mut self,
slot: u8,
pin_policy: Option<u8>,
touch_policy: Option<u8>,
) -> Result<[u8; 32], RatkeyError> {
let cmd = apdu::generate_key(slot, apdu::ALG_X25519, pin_policy, touch_policy);
let resp = transmit(&self.card, &cmd)?;
let resp = self.transport.transmit(&apdu::generate_key(
slot,
apdu::ALG_X25519,
pin_policy,
touch_policy,
))?;
let data = apdu::check_response(&resp)?;
apdu::parse_generate_response(data)
}
pub fn sign_ed25519(&self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError> {
let cmd = apdu::sign_ed25519(slot, message);
let resp = transmit(&self.card, &cmd)?;
let data = apdu::check_response(&resp)?;
apdu::parse_sign_response(data)
/// Import an off-device Ed25519 key (recoverable provisioning / restore).
/// Requires prior `authenticate_management_key`.
pub fn import_ed25519(
&mut self,
slot: u8,
private_key: &[u8; 32],
pin_policy: Option<u8>,
touch_policy: Option<u8>,
) -> Result<(), RatkeyError> {
let resp = self.transport.transmit(&apdu::import_ed25519(
slot,
private_key,
pin_policy,
touch_policy,
))?;
apdu::check_response(&resp)?;
Ok(())
}
pub fn ecdh_x25519(&self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError> {
let cmd = apdu::ecdh_x25519(slot, peer_pub);
let resp = transmit(&self.card, &cmd)?;
let data = apdu::check_response(&resp)?;
let mut secret = apdu::parse_ecdh_response(data)?;
// Wipes local stack copy only. Caller must zeroize the returned bytes.
let result = secret;
secret.zeroize();
Ok(result)
/// Import an off-device X25519 key. Requires prior `authenticate_management_key`.
pub fn import_x25519(
&mut self,
slot: u8,
private_key: &[u8; 32],
pin_policy: Option<u8>,
touch_policy: Option<u8>,
) -> Result<(), RatkeyError> {
let resp = self.transport.transmit(&apdu::import_x25519(
slot,
private_key,
pin_policy,
touch_policy,
))?;
apdu::check_response(&resp)?;
Ok(())
}
/// Transmit a PIN-gated command, retrying once through the cached PIN
/// when the card answers 0x6982 (security status not satisfied) — e.g.
/// pin_policy=ALWAYS slots, or the applet was re-selected since the last
/// VERIFY. The cache expires on its own timeout and is cleared by `lock`.
fn transmit_pin_gated(&mut self, cmd: &[u8]) -> Result<Vec<u8>, RatkeyError> {
let resp = self.transport.transmit(cmd)?;
match apdu::check_response(&resp) {
Err(RatkeyError::Apdu {
sw1: 0x69,
sw2: 0x82,
}) => {
let pin = match self.pin_cache.get() {
Some(pin) => zeroize::Zeroizing::new(pin.to_string()),
None => {
return Err(RatkeyError::Apdu {
sw1: 0x69,
sw2: 0x82,
});
}
};
self.verify_pin(&pin)?;
let resp = self.transport.transmit(cmd)?;
Ok(apdu::check_response(&resp)?.to_vec())
}
other => Ok(other?.to_vec()),
}
}
pub fn sign_ed25519(&mut self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError> {
let data = self.transmit_pin_gated(&apdu::sign_ed25519(slot, message))?;
apdu::parse_sign_response(&data)
}
pub fn ecdh_x25519(&mut self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError> {
let data = self.transmit_pin_gated(&apdu::ecdh_x25519(slot, peer_pub))?;
apdu::parse_ecdh_response(&data)
}
/// Returns DER-encoded X.509 attestation certificate.
pub fn attest_key(&self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
let cmd = apdu::attest_key(slot);
let resp = transmit(&self.card, &cmd)?;
let data = apdu::check_response(&resp)?;
Ok(data.to_vec())
pub fn attest_key(&mut self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
let resp = self.transport.transmit(&apdu::attest_key(slot))?;
Ok(apdu::check_response(&resp)?.to_vec())
}
pub fn read_certificate(&self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
pub fn read_certificate(&mut self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
let cmd = apdu::get_data(slot).ok_or(RatkeyError::EmptySlot { slot })?;
let resp = transmit(&self.card, &cmd)?;
let data = apdu::check_response(&resp)?;
Ok(data.to_vec())
let resp = self.transport.transmit(&cmd)?;
Ok(apdu::check_response(&resp)?.to_vec())
}
/// Returns raw metadata TLV bytes.
pub fn read_metadata(&self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
let cmd = apdu::get_metadata(slot);
let resp = transmit(&self.card, &cmd)?;
/// Device attestation (slot F9) intermediate certificate, unwrapped to raw DER.
/// This is the issuer of the per-slot certs returned by [`Self::attest_key`].
pub fn read_attestation_cert(&mut self) -> Result<Vec<u8>, RatkeyError> {
let cmd = apdu::get_data(apdu::SLOT_ATTESTATION).ok_or(RatkeyError::EmptySlot {
slot: apdu::SLOT_ATTESTATION,
})?;
let resp = self.transport.transmit(&cmd)?;
let data = apdu::check_response(&resp)?;
Ok(data.to_vec())
apdu::parse_certificate_object(data).ok_or_else(|| {
RatkeyError::InvalidHwid("device attestation cert (F9) not found in response".into())
})
}
/// Returns raw GET METADATA TLV bytes.
pub fn read_metadata(&mut self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
let resp = self.transport.transmit(&apdu::get_metadata(slot))?;
Ok(apdu::check_response(&resp)?.to_vec())
}
/// Reads the slot's 32-byte public key from GET METADATA. The metadata byte
/// layout is pending confirmation against a real device — see
/// `apdu::parse_metadata_public_key`. Yubico 5.3+ only (Nitrokey 3 has no
/// GET METADATA).
pub fn read_public_key(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> {
let metadata = self.read_metadata(slot)?;
apdu::parse_metadata_public_key(&metadata)
}
/// Authenticate the PIV management key (slot 9B) via witness/challenge mutual
/// auth — required before on-device key generation. The algorithm is read
/// from the card (YubiKey 5.7 default: AES-192).
pub fn authenticate_management_key(&mut self, key: &[u8]) -> Result<(), RatkeyError> {
let meta = self.read_metadata(apdu::SLOT_CARD_MANAGEMENT)?;
let alg = apdu::parse_metadata_algorithm(&meta)?;
let block = crate::mgmt::block_len(alg).ok_or_else(|| {
RatkeyError::UnsupportedDevice(format!(
"unsupported management-key algorithm 0x{alg:02X}"
))
})?;
// Step 1: get the card's encrypted witness, decrypt it with the key.
let resp = self.transport.transmit(&apdu::auth_witness_request(alg))?;
let witness = apdu::parse_auth_witness(apdu::check_response(&resp)?)?;
let decrypted = crate::mgmt::ecb_decrypt(alg, key, &witness)?;
// Step 2: prove the witness + send our own challenge. A wrong key is
// rejected here with an APDU status (not the mutual check below).
let challenge = rns_crypto::random::random_bytes(block);
let resp = self
.transport
.transmit(&apdu::auth_witness_response(alg, &decrypted, &challenge))?;
let data = apdu::check_response(&resp).map_err(|_| RatkeyError::ManagementAuthFailed)?;
let encrypted = apdu::parse_auth_response(data)?;
// Step 3: mutual check — the card must have encrypted our challenge.
if crate::mgmt::ecb_encrypt(alg, key, &challenge)? != encrypted {
return Err(RatkeyError::ManagementAuthFailed);
}
Ok(())
}
}
fn transmit(card: &Card, command: &[u8]) -> Result<Vec<u8>, RatkeyError> {
let mut response_buf = vec![0u8; MAX_RESPONSE];
let response = card.transmit(command, &mut response_buf).map_err(|e| {
warn!("PC/SC transmit failed: {}", e);
RatkeyError::Disconnected
})?;
Ok(response.to_vec())
/// PC/SC convenience alias; `connect()` lives on this monomorphization.
#[cfg(feature = "hardware")]
pub type PcscPivSession = PivSession<crate::transport::PcscTransport>;
#[cfg(feature = "hardware")]
impl PivSession<crate::transport::PcscTransport> {
/// Connect to the first detected token over PC/SC.
pub fn connect() -> Result<Self, RatkeyError> {
let (transport, meta) = crate::transport::PcscTransport::connect()?;
Ok(Self::new(transport, meta))
}
/// Connect to a specific PC/SC reader by name.
pub fn connect_reader(reader_name: &str) -> Result<Self, RatkeyError> {
let (transport, meta) = crate::transport::PcscTransport::connect_reader(reader_name)?;
Ok(Self::new(transport, meta))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
/// Card that loses PIN verification whenever `verified` is flipped off
/// (pin_policy=ALWAYS / applet reselect shape): SIGN answers 0x6982
/// until a VERIFY lands.
struct PinGatedTransport {
verified: Arc<AtomicBool>,
verify_calls: Arc<AtomicU32>,
}
impl PivTransport for PinGatedTransport {
fn transmit(&mut self, apdu: &[u8]) -> Result<Vec<u8>, RatkeyError> {
match apdu[1] {
0xA4 => {
self.verified.store(false, Ordering::SeqCst);
Ok(vec![0x90, 0x00])
}
0x20 => {
self.verify_calls.fetch_add(1, Ordering::SeqCst);
self.verified.store(true, Ordering::SeqCst);
Ok(vec![0x90, 0x00])
}
0x87 => {
if !self.verified.load(Ordering::SeqCst) {
return Ok(vec![0x69, 0x82]);
}
let mut v = vec![0x7C, 0x42, 0x82, 0x40];
v.extend_from_slice(&[0xAB; 64]);
v.extend_from_slice(&[0x90, 0x00]);
Ok(v)
}
_ => Ok(vec![0x90, 0x00]),
}
}
fn is_connected(&self) -> bool {
true
}
}
fn session_with_flags() -> (
PivSession<PinGatedTransport>,
Arc<AtomicBool>,
Arc<AtomicU32>,
) {
let verified = Arc::new(AtomicBool::new(false));
let verify_calls = Arc::new(AtomicU32::new(0));
let transport = PinGatedTransport {
verified: verified.clone(),
verify_calls: verify_calls.clone(),
};
let session = PivSession::new(
transport,
DeviceMeta {
device_type: DeviceType::Unknown,
serial: None,
firmware: None,
},
);
(session, verified, verify_calls)
}
/// T2-6a: the PIN cache is no longer write-only — a 0x6982 on a key op
/// re-verifies through the cached PIN and retries once.
#[test]
fn sign_retries_through_cached_pin() {
let (mut session, verified, verify_calls) = session_with_flags();
session.verify_pin("123456").unwrap();
assert_eq!(verify_calls.load(Ordering::SeqCst), 1);
// Card drops auth state (pin_policy=ALWAYS consumes the VERIFY).
verified.store(false, Ordering::SeqCst);
let sig = session.sign_ed25519(0x9A, b"message").unwrap();
assert_eq!(sig, [0xAB; 64]);
assert_eq!(
verify_calls.load(Ordering::SeqCst),
2,
"sign must have re-verified via the cached PIN"
);
}
/// After `lock()` the cache is cleared: no silent re-verify is possible.
#[test]
fn sign_after_lock_fails_without_fresh_pin() {
let (mut session, _verified, verify_calls) = session_with_flags();
session.verify_pin("123456").unwrap();
session.lock().unwrap();
let err = session.sign_ed25519(0x9A, b"message").unwrap_err();
assert!(matches!(
err,
RatkeyError::Apdu {
sw1: 0x69,
sw2: 0x82
}
));
assert_eq!(
verify_calls.load(Ordering::SeqCst),
1,
"locked session must not re-verify on its own"
);
}
}
+198
View File
@@ -0,0 +1,198 @@
//! Transport seam for PIV. The PIV protocol logic lives in `PivSession`; this
//! trait is the only platform-specific part: APDU bytes in, response bytes out.
//! Desktop PC/SC ships here behind the `hardware` feature. Mobile NFC/USB
//! transports live in the application layer and implement the same trait.
use crate::error::RatkeyError;
pub trait PivTransport {
/// Send one ISO 7816-4 APDU; return the full response including SW1/SW2.
fn transmit(&mut self, apdu: &[u8]) -> Result<Vec<u8>, RatkeyError>;
/// Cheap liveness probe — token still present and responding.
fn is_connected(&self) -> bool;
}
#[cfg(feature = "hardware")]
pub use pcsc_transport::PcscTransport;
#[cfg(feature = "hardware")]
mod pcsc_transport {
use pcsc::{Context, Protocols, Scope, ShareMode};
use tracing::{debug, warn};
use super::PivTransport;
use crate::apdu;
use crate::detect::{self, detect_device_type};
use crate::error::RatkeyError;
use crate::session::DeviceMeta;
const MAX_RESPONSE: usize = 4096;
/// Real PIV transport over PC/SC (YubiKey 5, Nitrokey 3). Requires a PC/SC
/// daemon: macOS CryptoTokenKit / Linux pcscd / Windows WinSCard.
pub struct PcscTransport {
card: pcsc::Card,
}
impl PcscTransport {
/// Connect to the first detected RATKEY token.
pub fn connect() -> Result<(Self, DeviceMeta), RatkeyError> {
let devices = detect::detect_devices()?;
let device = devices.first().ok_or(RatkeyError::NoDevice)?;
Self::connect_reader(&device.reader_name)
}
/// Connect to a specific PC/SC reader by name.
pub fn connect_reader(reader_name: &str) -> Result<(Self, DeviceMeta), RatkeyError> {
let ctx = Context::establish(Scope::User)?;
let reader = std::ffi::CString::new(reader_name)
.map_err(|_| RatkeyError::UnsupportedDevice(reader_name.to_string()))?;
let card = ctx.connect(&reader, ShareMode::Shared, Protocols::ANY)?;
let resp = transmit_card(&card, &apdu::select_piv())?;
apdu::check_response(&resp)?;
let device_type = detect_device_type(reader_name);
debug!(
"PIV session established with {} ({})",
reader_name,
device_type.as_str()
);
let (serial, firmware) = detect::read_identity(&card, device_type);
Ok((
Self { card },
DeviceMeta {
device_type,
serial,
firmware,
},
))
}
}
impl PivTransport for PcscTransport {
fn transmit(&mut self, apdu: &[u8]) -> Result<Vec<u8>, RatkeyError> {
transmit_card(&self.card, apdu)
}
fn is_connected(&self) -> bool {
// Attestation slot (F9) is present on any provisioned token.
let cmd = apdu::get_metadata(apdu::SLOT_ATTESTATION);
let mut buf = vec![0u8; 256];
self.card.transmit(&cmd, &mut buf).is_ok()
}
}
fn transmit_card(card: &pcsc::Card, command: &[u8]) -> Result<Vec<u8>, RatkeyError> {
let initial = transmit_once(card, command)?;
super::chain_response(command, initial, |apdu| transmit_once(card, apdu))
}
fn transmit_once(card: &pcsc::Card, command: &[u8]) -> Result<Vec<u8>, RatkeyError> {
let mut response_buf = vec![0u8; MAX_RESPONSE];
let response = card.transmit(command, &mut response_buf).map_err(|e| {
warn!("PC/SC transmit failed: {}", e);
RatkeyError::Disconnected
})?;
Ok(response.to_vec())
}
}
/// ISO 7816-4 response chaining, factored out of the PC/SC transport so it is
/// testable without a card. `initial` is the first response (data‖SW1‖SW2);
/// `transmit` sends a follow-up APDU and returns its raw response.
/// - `61 xx`: more data available — fetch it with GET RESPONSE and append.
/// - `6C xx`: wrong Le — resend `command` with the card's expected Le. Assumes
/// `command` carries no Le of its own (true for our case-3 reads); a command
/// that already has an Le would be malformed here.
///
/// Large reads (e.g. GET DATA on a ~1 KB attestation cert) arrive as `61 xx`;
/// without this every such read would be truncated to the first ≤256 bytes.
// Only the `hardware` transport calls this; the unit tests exercise it always.
#[cfg_attr(not(feature = "hardware"), allow(dead_code))]
pub(crate) fn chain_response(
command: &[u8],
initial: Vec<u8>,
mut transmit: impl FnMut(&[u8]) -> Result<Vec<u8>, RatkeyError>,
) -> Result<Vec<u8>, RatkeyError> {
let mut data = initial;
// Bounded against a misbehaving card that never returns a terminal SW.
for _ in 0..64 {
if data.len() < 2 {
break;
}
let (sw1, sw2) = (data[data.len() - 2], data[data.len() - 1]);
if sw1 == 0x61 {
data.truncate(data.len() - 2); // drop interim SW; keep the data
let get_response = [0x00, 0xC0, 0x00, 0x00, sw2]; // sw2 = bytes left (0 = 256)
data.extend_from_slice(&transmit(&get_response)?);
} else if sw1 == 0x6C {
let mut retry = command.to_vec();
retry.push(sw2);
data = transmit(&retry)?;
} else {
break;
}
}
Ok(data)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn passthrough_on_terminal_sw() {
let out = chain_response(&[], vec![0x01, 0x02, 0x90, 0x00], |_| {
panic!("no follow-up expected")
})
.unwrap();
assert_eq!(out, vec![0x01, 0x02, 0x90, 0x00]);
}
#[test]
fn appends_get_response_on_61() {
let mut calls = 0;
let out = chain_response(
&[0x00, 0xCB, 0x3F, 0xFF],
vec![0xAA, 0xBB, 0x61, 0x02],
|apdu| {
calls += 1;
assert_eq!(apdu, &[0x00, 0xC0, 0x00, 0x00, 0x02]); // GET RESPONSE, Le=2
Ok(vec![0xCC, 0xDD, 0x90, 0x00])
},
)
.unwrap();
assert_eq!(calls, 1);
assert_eq!(out, vec![0xAA, 0xBB, 0xCC, 0xDD, 0x90, 0x00]);
}
#[test]
fn chains_multiple_61() {
let mut step = 0;
let out = chain_response(&[0x00], vec![0x01, 0x61, 0x00], |_| {
step += 1;
if step == 1 {
Ok(vec![0x02, 0x61, 0x00]) // still more
} else {
Ok(vec![0x03, 0x90, 0x00]) // done
}
})
.unwrap();
assert_eq!(step, 2);
assert_eq!(out, vec![0x01, 0x02, 0x03, 0x90, 0x00]);
}
#[test]
fn resends_with_le_on_6c() {
let out = chain_response(&[0x00, 0xCB, 0x3F, 0xFF], vec![0x6C, 0x05], |apdu| {
assert_eq!(apdu, &[0x00, 0xCB, 0x3F, 0xFF, 0x05]); // original + Le=5
Ok(vec![0xDE, 0xAD, 0x90, 0x00])
})
.unwrap();
assert_eq!(out, vec![0xDE, 0xAD, 0x90, 0x00]);
}
}
Binary file not shown.
Binary file not shown.
+2
View File
@@ -8,6 +8,7 @@ license.workspace = true
[features]
default = []
serial = ["rns-interface/serial"]
rnode-tcp = ["rns-interface/rnode-tcp"]
ble = ["rns-interface/ble"]
[dependencies]
@@ -23,6 +24,7 @@ tokio = { workspace = true }
bytes = { workspace = true }
tracing = { workspace = true }
hmac = { workspace = true }
md-5 = { workspace = true }
sha2 = { workspace = true }
rmp-serde = { workspace = true }
rmpv = { workspace = true, features = ["with-serde"] }
+6 -3
View File
@@ -12,9 +12,12 @@ pub const RESOURCE_CACHE: u64 = 86400;
pub const MAX_QUEUED_ANNOUNCES: usize = 16384;
pub const QUEUED_ANNOUNCE_LIFE: u64 = 86400;
/// Percentage matching Python `Reticulum.ANNOUNCE_CAP = 2`; transport actor
/// divides by 100 before applying to bitrate math.
pub const ANNOUNCE_CAP: f64 = 2.0;
/// Announce bandwidth cap as a fraction of interface bitrate (2%).
///
/// Python exposes/configures this as `2` percent, then stores `0.02` on live
/// interfaces. Runtime registration must hand the transport actor the stored
/// fraction, because queue spacing is calculated as `tx_time / announce_cap`.
pub const ANNOUNCE_CAP: f64 = 0.02;
pub const MINIMUM_BITRATE: u64 = 5;
pub const IFAC_MIN_SIZE: usize = 1;
File diff suppressed because it is too large. Load diff
+36 -9
View File
@@ -75,23 +75,50 @@ impl Default for ExitHandler {
}
}
/// Install Ctrl-C / SIGTERM handlers that trip `shutdown`. Returned receiver
/// Install a Ctrl-C (SIGINT) handler that trips `shutdown`. Returned receiver
/// yields once on signal for await-based callers.
///
/// On unix the OS-level registration happens synchronously in this call — a
/// handler registered inside a spawned task only takes effect once that task
/// is first polled, leaving a window where SIGINT kills the process via the
/// default disposition.
pub fn install_signal_handlers(shutdown: ShutdownSignal) -> mpsc::Receiver<()> {
let (tx, rx) = mpsc::channel(1);
let shutdown_clone = shutdown.clone();
tokio::spawn(async move {
let ctrl_c = tokio::signal::ctrl_c();
ctrl_c.await.ok();
tracing::info!("received shutdown signal");
shutdown_clone.trigger();
let _ = tx.send(()).await;
});
#[cfg(unix)]
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt()) {
Ok(mut sigint) => {
tokio::spawn(async move {
sigint.recv().await;
signal_shutdown(shutdown_clone, tx).await;
});
}
Err(e) => {
tracing::warn!(error = %e, "SIGINT registration failed; falling back to ctrl_c");
spawn_ctrl_c_handler(shutdown_clone, tx);
}
}
#[cfg(not(unix))]
spawn_ctrl_c_handler(shutdown_clone, tx);
rx
}
fn spawn_ctrl_c_handler(shutdown: ShutdownSignal, tx: mpsc::Sender<()>) {
tokio::spawn(async move {
tokio::signal::ctrl_c().await.ok();
signal_shutdown(shutdown, tx).await;
});
}
async fn signal_shutdown(shutdown: ShutdownSignal, tx: mpsc::Sender<()>) {
tracing::info!("received shutdown signal");
shutdown.trigger();
let _ = tx.send(()).await;
}
#[cfg(test)]
mod tests {
use super::*;
File diff suppressed because it is too large. Load diff
+150 -12
View File
@@ -20,6 +20,9 @@ use rns_wire::flags::{DestinationType, HeaderType, PacketFlags, PacketType, Tran
use rns_wire::hash::packet_hash_pair;
use rns_wire::header::PacketHeader;
/// Python rnprobe `DEFAULT_TIMEOUT`.
const DEFAULT_TIMEOUT_SECS: f64 = 12.0;
#[derive(Debug, Error)]
pub enum ProbeError {
#[error("timed out waiting for path to destination")]
@@ -75,13 +78,52 @@ pub async fn spawn_probe_responder(
.map_err(|_| ProbeError::TransportClosed)?;
let identity = Arc::new(identity);
let mut destination = dest;
// Implicit proof is Python's default (`use_implicit_proof = Yes`).
let implicit = true;
tokio::spawn(async move {
while let Some(event) = event_rx.recv().await {
let DestinationEvent::InboundPacket { raw, .. } = event else {
continue;
let (raw, interface_id) = match event {
DestinationEvent::InboundPacket { raw, interface_id } => (raw, interface_id),
DestinationEvent::AnnounceRequested(request) => {
let raw = match destination.announce_packet(
identity.as_ref(),
None,
None,
request.path_response,
request.tag.as_deref(),
unix_now(),
) {
Ok(raw) => raw,
Err(e) => {
tracing::warn!(
error = %e,
path_response = request.path_response,
"probe responder: failed to build requested announce"
);
continue;
}
};
let outbound = OutboundRequest {
raw: Bytes::from(raw),
destination_hash: dest_hash,
};
let message = if let Some(interface_id) = request.attached_interface {
TransportMessage::OutboundAttached {
request: outbound,
interface_id,
}
} else {
TransportMessage::Outbound(outbound)
};
if transport_tx.send(message).await.is_err() {
tracing::debug!("probe responder: transport closed, exiting");
break;
}
continue;
}
_ => continue,
};
let (header, _) = match PacketHeader::unpack(&raw) {
Ok(h) => h,
@@ -122,10 +164,13 @@ pub async fn spawn_probe_responder(
proof_raw.extend_from_slice(&proof_payload);
if transport_tx
.send(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(proof_raw),
destination_hash: trunc_hash,
}))
.send(TransportMessage::OutboundAttached {
request: OutboundRequest {
raw: Bytes::from(proof_raw),
destination_hash: trunc_hash,
},
interface_id,
})
.await
.is_err()
{
@@ -197,13 +242,15 @@ impl Drop for DeliveryProofWaiter {
}
}
/// `None` waits mirror Python rnprobe: `DEFAULT_TIMEOUT +
/// get_first_hop_timeout(dest)`, resolved fresh at each wait.
pub async fn probe_once(
transport_tx: mpsc::Sender<TransportMessage>,
dest_hash: [u8; 16],
app_name: &str,
size: usize,
proof_wait: Duration,
path_wait: Duration,
proof_wait: Option<Duration>,
path_wait: Option<Duration>,
use_implicit_proof: bool,
) -> Result<ProbeOutcome, ProbeError> {
if size > MTU {
@@ -235,6 +282,11 @@ pub async fn probe_once(
.await
.map_err(|_| ProbeError::TransportClosed)?;
let path_wait = match path_wait {
Some(d) => d,
None => default_probe_wait(&transport_tx, dest_hash).await?,
};
let (await_tx, await_rx) = oneshot::channel();
transport_tx
.send(TransportMessage::AwaitPath {
@@ -298,6 +350,12 @@ pub async fn probe_once(
let (full_hash, trunc_hash) = packet_hash_pair(&raw, HeaderType::Header1);
// Per probe, like Python's per-packet `timeout or DEFAULT_TIMEOUT + fht`.
let proof_wait = match proof_wait {
Some(d) => d,
None => default_probe_wait(&transport_tx, dest_hash).await?,
};
// trunc_hash keys `receipt_table`; unique msg_id filters fan-out.
let msg_id = format!(
"probe.{}.{:x}",
@@ -362,6 +420,17 @@ pub async fn probe_once(
})
}
async fn default_probe_wait(
tx: &mpsc::Sender<TransportMessage>,
dest: [u8; 16],
) -> Result<Duration, ProbeError> {
let first_hop = match query(tx, TransportQuery::FirstHopTimeout { dest }).await? {
TransportQueryResponse::FloatResult(Some(t)) => t,
_ => rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT,
};
Ok(Duration::from_secs_f64(DEFAULT_TIMEOUT_SECS + first_hop))
}
pub fn parse_dest_hash(hex_str: &str) -> Result<[u8; 16], ProbeError> {
let bytes = hex::decode(hex_str.trim()).map_err(|_| ProbeError::InvalidName)?;
<[u8; 16]>::try_from(bytes.as_slice()).map_err(|_| ProbeError::InvalidName)
@@ -413,6 +482,13 @@ fn find_public_key(announces: &[AnnounceRpcEntry], dest_hash: &[u8; 16]) -> Opti
.and_then(|a| a.public_key)
}
fn unix_now() -> f64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -455,6 +531,8 @@ mod tests {
timestamp: 0.0,
public_key: Some([0x11; 64]),
ratchet: None,
name_hash: [0; 10],
is_path_response: false,
retained: false,
},
AnnounceRpcEntry {
@@ -464,6 +542,8 @@ mod tests {
timestamp: 0.0,
public_key: Some([0x22; 64]),
ratchet: None,
name_hash: [0; 10],
is_path_response: false,
retained: false,
},
];
@@ -524,15 +604,20 @@ mod tests {
.await
.expect("timed out waiting for proof")
.expect("channel closed");
let (request, interface_id) = match outbound {
TransportMessage::OutboundAttached {
request,
interface_id,
} => (request, interface_id),
other => panic!("expected OutboundAttached, got {other:?}"),
};
let OutboundRequest {
raw: proof_raw,
destination_hash,
} = match outbound {
TransportMessage::Outbound(r) => r,
other => panic!("expected Outbound, got {other:?}"),
};
} = request;
assert_eq!(destination_hash, expected_trunc);
assert_eq!(interface_id, 0);
let (proof_header, data_offset) = PacketHeader::unpack(&proof_raw).unwrap();
assert_eq!(proof_header.flags.packet_type, PacketType::Proof);
@@ -552,6 +637,59 @@ mod tests {
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn responder_sends_attached_path_response_announce() {
let (tx, mut rx) = mpsc::channel::<TransportMessage>(16);
let identity = Identity::new();
let spawn_tx = tx.clone();
let spawn_handle = tokio::spawn(async move {
spawn_probe_responder(spawn_tx, identity, default_probe_app_name()).await
});
let first = rx.recv().await.expect("RegisterDestination");
let delivery_tx = match first {
TransportMessage::RegisterDestination {
delivery_tx: Some(dt),
..
} => dt,
other => panic!("expected RegisterDestination, got {other:?}"),
};
let dest_hash = spawn_handle.await.unwrap().unwrap();
delivery_tx
.send(DestinationEvent::AnnounceRequested(
rns_transport::link_messages::AnnounceRequest {
app_name: default_probe_app_name().to_string(),
path_response: true,
tag: Some(vec![0xA5; 16]),
attached_interface: Some(7),
},
))
.await
.unwrap();
let outbound = tokio::time::timeout(Duration::from_secs(2), rx.recv())
.await
.expect("timed out waiting for path response")
.expect("channel closed");
let (request, interface_id) = match outbound {
TransportMessage::OutboundAttached {
request,
interface_id,
} => (request, interface_id),
other => panic!("expected OutboundAttached, got {other:?}"),
};
assert_eq!(interface_id, 7);
assert_eq!(request.destination_hash, dest_hash);
let (header, _offset) = PacketHeader::unpack(&request.raw).unwrap();
assert_eq!(header.flags.packet_type, PacketType::Announce);
assert_eq!(header.flags.destination_type, DestinationType::Single);
assert_eq!(header.destination_hash, dest_hash);
assert_eq!(header.context, PacketContext::PathResponse);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn responder_ignores_non_data_packets() {
let (tx, mut rx) = mpsc::channel::<TransportMessage>(16);
+51 -2
View File
@@ -45,7 +45,7 @@ pub async fn start_remote_management(
event_rx,
identity,
app_name,
signing_key,
Some(signing_key),
);
let status_hash: [u8; 16] = truncated_hash(STATUS_PATH.as_bytes());
@@ -252,7 +252,13 @@ fn interface_stats_from_rpc(e: InterfaceStatRpcEntry) -> schema::InterfaceStats
txb: e.tx_bytes,
incoming_announce_frequency: e.incoming_announce_frequency,
outgoing_announce_frequency: e.outgoing_announce_frequency,
incoming_pr_frequency: e.incoming_pr_frequency,
outgoing_pr_frequency: e.outgoing_pr_frequency,
held_announces: e.held_announces,
burst_active: e.burst_active,
burst_activated: e.burst_activated,
pr_burst_active: e.pr_burst_active,
pr_burst_activated: e.pr_burst_activated,
status: e.online,
mode,
bitrate: Some(e.bitrate),
@@ -330,7 +336,13 @@ mod tests {
txb: 7,
incoming_announce_frequency: 0.0,
outgoing_announce_frequency: 0.0,
incoming_pr_frequency: 0.0,
outgoing_pr_frequency: 0.0,
held_announces: 0,
burst_active: false,
burst_activated: 0.0,
pr_burst_active: false,
pr_burst_activated: 0.0,
status: true,
mode: 0x01,
bitrate: Some(1_000_000),
@@ -465,11 +477,17 @@ mod tests {
held_announces: 1,
incoming_announce_frequency: 0.5,
outgoing_announce_frequency: 0.25,
incoming_pr_frequency: 3.0,
outgoing_pr_frequency: 1.5,
burst_active: true,
burst_activated: 1_700_000_001.0,
pr_burst_active: true,
pr_burst_activated: 1_700_000_002.0,
clients: None,
announce_rate_target: None,
announce_rate_grace: None,
announce_rate_penalty: None,
announce_cap: 2.0,
announce_cap: 0.02,
ifac_size: 0,
tx_drops: 0,
}];
@@ -484,6 +502,9 @@ mod tests {
hops: 2,
expires: 1_700_100_000.0,
interface: "MockIf".to_string(),
interface_id: 1,
interface_mode: rns_transport::constants::InterfaceMode::Full,
interface_role: rns_transport::messages::InterfaceRole::Normal,
}];
TransportQueryResponse::PathTable(entries)
}
@@ -562,6 +583,34 @@ mod tests {
Some(0x06),
"Gateway mode maps to Python MODE_GATEWAY=0x06"
);
let incoming_pr = iface_map
.iter()
.find(|(k, _)| k.as_str() == Some("incoming_pr_frequency"))
.unwrap()
.1
.as_f64();
assert_eq!(incoming_pr, Some(3.0));
let outgoing_pr = iface_map
.iter()
.find(|(k, _)| k.as_str() == Some("outgoing_pr_frequency"))
.unwrap()
.1
.as_f64();
assert_eq!(outgoing_pr, Some(1.5));
let burst_active = iface_map
.iter()
.find(|(k, _)| k.as_str() == Some("burst_active"))
.unwrap()
.1
.as_bool();
assert_eq!(burst_active, Some(true));
let pr_burst_active = iface_map
.iter()
.find(|(k, _)| k.as_str() == Some("pr_burst_active"))
.unwrap()
.1
.as_bool();
assert_eq!(pr_burst_active, Some(true));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
@@ -34,7 +34,13 @@ pub struct InterfaceStats {
pub txb: u64,
pub incoming_announce_frequency: f64,
pub outgoing_announce_frequency: f64,
pub incoming_pr_frequency: f64,
pub outgoing_pr_frequency: f64,
pub held_announces: u64,
pub burst_active: bool,
pub burst_activated: f64,
pub pr_burst_active: bool,
pub pr_burst_activated: f64,
/// Python field name (not `online`).
pub status: bool,
/// Matches Python `Interface.MODE_*` integers.
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -235,7 +235,7 @@ pub async fn spawn_rncp_listener(
dest_rx,
&cfg.identity,
&cfg.app_name,
signing_key,
Some(signing_key),
);
let (completion_tx, mut completion_rx) = mpsc::channel::<ResourceCompletion>(64);
+28 -2
View File
@@ -32,6 +32,7 @@ use rns_transport::messages::{
AnnounceRpcEntry, OutboundRequest, TransportMessage, TransportQuery, TransportQueryResponse,
};
use crate::lifecycle::ShutdownSignal;
use crate::link_manager::{
ChannelSendError, LinkChannelMessage, LinkManager, LinkManagerCommand, register_destination,
};
@@ -132,6 +133,22 @@ pub struct RnshListenerConfig {
pub async fn run_rnsh_listener(
transport_tx: mpsc::Sender<TransportMessage>,
cfg: RnshListenerConfig,
) -> Result<(), RnshError> {
run_rnsh_listener_inner(transport_tx, cfg, None).await
}
pub async fn run_rnsh_listener_with_shutdown(
transport_tx: mpsc::Sender<TransportMessage>,
cfg: RnshListenerConfig,
shutdown: ShutdownSignal,
) -> Result<(), RnshError> {
run_rnsh_listener_inner(transport_tx, cfg, Some(shutdown)).await
}
async fn run_rnsh_listener_inner(
transport_tx: mpsc::Sender<TransportMessage>,
cfg: RnshListenerConfig,
shutdown: Option<ShutdownSignal>,
) -> Result<(), RnshError> {
let signing_key = cfg
.identity
@@ -152,7 +169,7 @@ pub async fn run_rnsh_listener(
event_rx,
&cfg.identity,
RNSH_APP_NAME,
signing_key,
Some(signing_key),
);
let announce_tx = transport_tx.clone();
@@ -237,6 +254,15 @@ pub async fn run_rnsh_listener(
} => {
send_announce(&transport_tx, &cfg.identity, RNSH_APP_NAME).await?;
}
_ = async {
if let Some(shutdown) = shutdown.as_ref() {
shutdown.wait().await;
} else {
std::future::pending::<()>().await;
}
} => {
break;
}
}
}
@@ -1474,7 +1500,7 @@ async fn send_client_channel_data(
raw.extend_from_slice(data);
let packet_hash = rns_wire::hash::packet_hash(&raw, channel_header.flags.header_type);
channel.track_outbound_packet_hash(packet_hash, sequence);
link.record_tx(raw.len());
link.record_tx(data.len());
transport_tx
.send(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(raw),
File diff suppressed because it is too large. Load diff
+158 -21
View File
@@ -198,7 +198,11 @@ async fn handle_rpc_client(
return Err(RpcError::AuthFailed);
}
let client_challenge = &client_challenge_frame[rpc::MP_CHALLENGE.len()..];
let client_response = rpc::compute_python_auth_response(rpc_key, client_challenge);
let client_response = rpc::compute_python_auth_response_for(
rpc::detect_python_auth_protocol(client_challenge),
rpc_key,
client_challenge,
);
rpc::write_mp_frame(&mut stream, &client_response).await?;
let client_welcome = rpc::read_mp_frame(&mut stream, 256).await?;
if client_welcome != rpc::MP_WELCOME {
@@ -222,20 +226,58 @@ async fn query_transport(
query: rns_transport::messages::TransportQuery,
) -> Option<rns_transport::messages::TransportQueryResponse> {
let (tx, rx) = tokio::sync::oneshot::channel();
if transport_tx
.send(TransportMessage::Rpc {
let budget = std::time::Duration::from_secs(5);
let started = std::time::Instant::now();
match tokio::time::timeout(
budget,
transport_tx.send(TransportMessage::Rpc {
query,
response_tx: tx,
}),
)
.await
{
Ok(Ok(())) => {}
Ok(Err(_)) => return None,
Err(_) => return None,
}
let remaining = budget.checked_sub(started.elapsed())?;
tokio::time::timeout(remaining, rx)
.await
.ok()
.and_then(|r| r.ok())
}
async fn request_path(
transport_tx: &mpsc::Sender<TransportMessage>,
destination_hash: [u8; 16],
timeout_secs: Option<f64>,
) -> bool {
let wait = std::time::Duration::from_secs_f64(timeout_secs.unwrap_or(5.0).max(0.1));
if transport_tx
.send(TransportMessage::RequestPath { destination_hash })
.await
.is_err()
{
return false;
}
let (reply, rx) = tokio::sync::oneshot::channel();
if transport_tx
.send(TransportMessage::AwaitPath {
dest: destination_hash,
reply,
})
.await
.is_err()
{
return None;
return false;
}
match tokio::time::timeout(wait, rx).await {
Ok(Ok(found)) => found,
_ => false,
}
tokio::time::timeout(std::time::Duration::from_secs(5), rx)
.await
.ok()
.and_then(|r| r.ok())
}
async fn process_rpc_request(
@@ -286,6 +328,12 @@ async fn process_rpc_request(
held_announces: e.held_announces,
incoming_announce_frequency: e.incoming_announce_frequency,
outgoing_announce_frequency: e.outgoing_announce_frequency,
incoming_pr_frequency: e.incoming_pr_frequency,
outgoing_pr_frequency: e.outgoing_pr_frequency,
burst_active: e.burst_active,
burst_activated: e.burst_activated,
pr_burst_active: e.pr_burst_active,
pr_burst_activated: e.pr_burst_activated,
clients: e.clients,
announce_rate_target: e.announce_rate_target,
announce_rate_grace: e.announce_rate_grace,
@@ -297,7 +345,9 @@ async fn process_rpc_request(
.collect();
RpcResponse::InterfaceStats(rpc_entries)
}
_ => RpcResponse::InterfaceStats(Vec::new()),
_ => RpcResponse::Error(
"transport actor did not answer interface stats query".to_string(),
),
}
}
RpcRequest::GetRateTable => {
@@ -360,6 +410,15 @@ async fn process_rpc_request(
None => RpcResponse::HashResult(None),
}
}
RpcRequest::RequestPath {
destination_hash,
timeout_secs,
} => match hash_to_array(&destination_hash) {
Some(dest) => {
RpcResponse::BoolResult(request_path(transport_tx, dest, timeout_secs).await)
}
None => RpcResponse::BoolResult(false),
},
RpcRequest::DropPath { destination_hash } => {
let dest = hash_to_array(&destination_hash);
if let Some(d) = dest {
@@ -367,6 +426,22 @@ async fn process_rpc_request(
}
RpcResponse::Ok
}
RpcRequest::DropPathTable => {
if let Some(TransportQueryResponse::IntResult(n)) =
query_transport(transport_tx, TransportQuery::DropPathTable).await
{
return RpcResponse::IntResult(n);
}
RpcResponse::IntResult(0)
}
RpcRequest::DropRecentAnnounces => {
if let Some(TransportQueryResponse::IntResult(n)) =
query_transport(transport_tx, TransportQuery::DropRecentAnnounces).await
{
return RpcResponse::IntResult(n);
}
RpcResponse::IntResult(0)
}
RpcRequest::DropAnnounceQueues => {
let _ = query_transport(transport_tx, TransportQuery::DropAnnounceQueues).await;
RpcResponse::Ok
@@ -393,6 +468,16 @@ async fn process_rpc_request(
_ => RpcResponse::BlackholeList(Vec::new()),
}
}
RpcRequest::IsBlackholed { identity_hash } => {
if let Some(hash) = hash_to_array(&identity_hash) {
if let Some(TransportQueryResponse::BoolResult(v)) =
query_transport(transport_tx, TransportQuery::IsBlackholed { hash }).await
{
return RpcResponse::BoolResult(v);
}
}
RpcResponse::BoolResult(false)
}
RpcRequest::BlackholeIdentity {
identity_hash,
until,
@@ -688,6 +773,8 @@ mod tests {
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
// Python >=1.3.4 clients speak umsgpack over send_bytes/recv_bytes
// (commit a2ef9782); frames hardcoded so the test needs no msgpack module.
let script = r#"
import multiprocessing.connection
import sys
@@ -695,17 +782,17 @@ import sys
port = int(sys.argv[1])
authkey = bytes.fromhex(sys.argv[2])
conn = multiprocessing.connection.Client(("127.0.0.1", port), authkey=authkey)
conn.send({"get": "link_count"})
resp = conn.recv()
conn.send_bytes(bytes.fromhex("81a3676574aa6c696e6b5f636f756e74")) # {"get": "link_count"}
resp = conn.recv_bytes()
conn.close()
if resp != 0:
raise SystemExit(f"unexpected response: {resp!r}")
if resp != b"\x00":
raise SystemExit(f"unexpected response: {resp.hex()}")
conn = multiprocessing.connection.Client(("127.0.0.1", port), authkey=authkey)
conn.send({"get": "interface_stats"})
resp = conn.recv()
conn.send_bytes(bytes.fromhex("81a3676574af696e746572666163655f7374617473")) # {"get": "interface_stats"}
resp = conn.recv_bytes()
conn.close()
if not isinstance(resp, dict) or "interfaces" not in resp:
raise SystemExit(f"unexpected interface_stats response: {resp!r}")
if b"\xaainterfaces" not in resp:
raise SystemExit(f"unexpected interface_stats response: {resp.hex()}")
"#;
let output = std::process::Command::new("python3")
.arg("-c")
@@ -738,6 +825,9 @@ if not isinstance(resp, dict) or "interfaces" not in resp:
let port = portpicker_ephemeral();
let rpc_key = b"python_listener_key".to_vec();
// umsgpack frames over send_bytes/recv_bytes, matching a >=1.3.4
// Python rpc_loop (commit a2ef9782); hardcoded so no msgpack module
// is needed.
let script = r#"
import multiprocessing.connection
import sys
@@ -747,10 +837,10 @@ authkey = bytes.fromhex(sys.argv[2])
listener = multiprocessing.connection.Listener(("127.0.0.1", port), authkey=authkey)
print("READY", flush=True)
conn = listener.accept()
call = conn.recv()
if call != {"get": "link_count"}:
raise SystemExit(f"unexpected call: {call!r}")
conn.send(7)
call = conn.recv_bytes()
if call != bytes.fromhex("81a3676574aa6c696e6b5f636f756e74"): # {"get": "link_count"}
raise SystemExit(f"unexpected call: {call.hex()}")
conn.send_bytes(b"\x07") # 7
conn.close()
listener.close()
"#;
@@ -827,6 +917,10 @@ listener.close()
RpcRequest::GetNextHop {
destination_hash: vec![0; 16],
},
RpcRequest::RequestPath {
destination_hash: vec![0; 16],
timeout_secs: Some(0.01),
},
RpcRequest::GetFirstHopTimeout {
destination_hash: vec![0; 16],
},
@@ -841,12 +935,17 @@ listener.close()
packet_hash: vec![0; 32],
},
RpcRequest::GetBlackholedIdentities,
RpcRequest::IsBlackholed {
identity_hash: vec![0; 16],
},
RpcRequest::DropPath {
destination_hash: vec![0; 16],
},
RpcRequest::DropAllVia {
transport_hash: vec![0; 16],
},
RpcRequest::DropPathTable,
RpcRequest::DropRecentAnnounces,
RpcRequest::DropAnnounceQueues,
RpcRequest::BlackholeIdentity {
identity_hash: vec![0; 16],
@@ -878,6 +977,44 @@ listener.close()
let _ = tx.send(TransportMessage::Shutdown).await;
}
#[tokio::test]
async fn request_path_rpc_sends_transport_request_and_awaits_result() {
let (tx, mut rx) = mpsc::channel(4);
let dest = [0x42; 16];
let handle = tokio::spawn(async move {
process_rpc_request(
RpcRequest::RequestPath {
destination_hash: dest.to_vec(),
timeout_secs: Some(1.0),
},
&tx,
)
.await
});
match rx.recv().await.expect("RequestPath message") {
TransportMessage::RequestPath { destination_hash } => {
assert_eq!(destination_hash, dest)
}
other => panic!("expected RequestPath, got {other:?}"),
}
match rx.recv().await.expect("AwaitPath message") {
TransportMessage::AwaitPath {
dest: awaited,
reply,
} => {
assert_eq!(awaited, dest);
reply.send(true).unwrap();
}
other => panic!("expected AwaitPath, got {other:?}"),
}
assert!(matches!(
handle.await.unwrap(),
RpcResponse::BoolResult(true)
));
}
fn portpicker_ephemeral() -> u16 {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.local_addr().unwrap().port()
+29 -12
View File
@@ -42,7 +42,7 @@ use rns_runtime::rncp::{
};
const DEFAULT_TIMEOUT_SECS: f64 = 15.0;
const RETICULUM_COMPAT_VERSION: &str = "1.2.2";
use rns_tools::RS_RETICULUM_VERSION;
#[derive(Parser)]
#[command(
@@ -197,7 +197,7 @@ fn load_or_create_identity(
pub(crate) async fn main() {
let args = Args::parse();
if args.version {
println!("rncp-rs {RETICULUM_COMPAT_VERSION}");
println!("rncp-rs {RS_RETICULUM_VERSION}");
return;
}
if args.phy_rates {
@@ -213,10 +213,13 @@ pub(crate) async fn main() {
0 => tracing::Level::WARN,
_ => tracing::Level::ERROR,
};
tracing_subscriber::fmt()
.with_max_level(level)
.with_writer(std::io::stderr)
.init();
let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref());
rns_tools::init_tracing(
level,
rns_tools::config_log_timestamps(&config_dir),
true,
std::io::stderr,
);
if args.fetch {
run_fetch(args).await;
@@ -228,6 +231,9 @@ pub(crate) async fn main() {
}
async fn run_fetch(args: Args) -> ! {
// Register before any slow init so an early SIGINT exits cleanly.
let shutdown = ShutdownSignal::new();
let _signal_rx = install_signal_handlers(shutdown.clone());
// In fetch mode the positionals are `<destination_hash> <remote_path>`.
let (Some(dest_arg), Some(path_arg)) = (args.file.as_ref(), args.destination.as_ref()) else {
eprintln!("rncp-rs: fetch mode requires <destination_hash> <remote_path>");
@@ -264,7 +270,7 @@ async fn run_fetch(args: Args) -> ! {
None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
};
let handle = start_reticulum(args.config.as_deref()).await;
let handle = start_reticulum(args.config.as_deref(), shutdown.clone()).await;
let paths = StoragePaths::from_config_dir(&handle.config_dir);
let identity = match load_or_create_identity(args.identity_path.as_deref(), &paths.identity_dir)
{
@@ -371,6 +377,9 @@ fn print_fetch_summary(outcome: &RncpFetchOutcome) {
}
async fn run_send(args: Args) -> ! {
// Register before any slow init so an early SIGINT exits cleanly.
let shutdown = ShutdownSignal::new();
let _signal_rx = install_signal_handlers(shutdown.clone());
let (Some(file_arg), Some(dest_arg)) = (args.file.as_ref(), args.destination.as_ref()) else {
// Bare `rncp` prints help and exits 0.
let mut cmd = <Args as clap::CommandFactory>::command();
@@ -407,7 +416,7 @@ async fn run_send(args: Args) -> ! {
}
};
let handle = start_reticulum(args.config.as_deref()).await;
let handle = start_reticulum(args.config.as_deref(), shutdown.clone()).await;
let paths = StoragePaths::from_config_dir(&handle.config_dir);
let identity = match load_or_create_identity(args.identity_path.as_deref(), &paths.identity_dir)
@@ -525,6 +534,9 @@ fn human_rate(bps: f64) -> (f64, &'static str) {
}
async fn run_listen(args: Args) -> ! {
// Register before any slow init so an early SIGINT exits cleanly.
let shutdown = ShutdownSignal::new();
let _signal_rx = install_signal_handlers(shutdown.clone());
let save_dir = match args.save.as_deref() {
Some(p) => {
let path = expand_tilde(p);
@@ -571,7 +583,7 @@ async fn run_listen(args: Args) -> ! {
eprintln!("Warning: No allowed identities configured, rncp will not accept any files!");
}
let handle = start_reticulum(args.config.as_deref()).await;
let handle = start_reticulum(args.config.as_deref(), shutdown.clone()).await;
let paths = StoragePaths::from_config_dir(&handle.config_dir);
let identity = match load_or_create_identity(args.identity_path.as_deref(), &paths.identity_dir)
{
@@ -695,6 +707,9 @@ async fn run_listen(args: Args) -> ! {
}
}
}
_ = handle.shutdown.wait() => {
break;
}
}
}
@@ -702,6 +717,7 @@ async fn run_listen(args: Args) -> ! {
task.abort();
let _ = task.await;
}
listener.shutdown().await;
process::exit(0);
}
@@ -802,9 +818,10 @@ fn rncp_allowed_identity_file_candidates() -> Vec<PathBuf> {
paths
}
async fn start_reticulum(config_dir: Option<&str>) -> rns_runtime::reticulum::ReticulumHandle {
let shutdown = ShutdownSignal::new();
let _signal_rx = install_signal_handlers(shutdown.clone());
async fn start_reticulum(
config_dir: Option<&str>,
shutdown: ShutdownSignal,
) -> rns_runtime::reticulum::ReticulumHandle {
let is_foreground = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
match rns_runtime::reticulum::init(config_dir, None, shutdown.clone(), is_foreground).await {
Ok(h) => h,
@@ -0,0 +1,83 @@
//! Base256 armored encoding for rsg/rsm data.
//!
//! Python ref: 1.3.8 `RNS/__init__.py` `b256`/`b256rep`/`b256_to_bytes` (commit
//! 855ef7bf). Upstream marks the glyph table experimental ("likely to change") —
//! this is the 1.3.8 snapshot; re-check on upstream release sweeps.
use std::collections::HashMap;
use std::sync::LazyLock;
/// One glyph per byte value 0x00..=0xFF, in upstream table order
/// (Latin/numerals, Greek, Cyrillic, Armenian, Elder Futhark, Katakana,
/// Shavian, Ol Chiki, Gothic & Deseret).
const B256_GLYPHS: &str = "abcdefghijklmnopqrstuvxyzæø01234\
ABCDEFGHIJKLMNOPQRSTUWXYZÆØ56789\
αβγδεζηθικλμνξπρστφχψωΓΔΘΛΞΠΣΦΨΩ\
БДЖЗИЛПЦЧШЩЪЫЭЮЯбджзилпцчшщъыэюя\
ԱԲԳԴԵԶԷԸԹԺԻԽԾԿՀՁՂՃՄՅՆՇՈՉՊՋՎՐՑՒՔՖ\
ᚠᚢᚦᚱᚹᚺᚾᛈᛇᛉᛊᛏᛒᛖᛗᛟ\
イウオカキケサシスセタチテトナヌ\
ネヒフヘホマミムメモヤラリルレワ\
𐑐𐑑𐑒𐑔𐑕𐑗𐑙𐑳𐑶𐑸𐑹𐑺𐑻𐑽𐑾𐑿\
᱑᱕᱘᱙ᱚᱝᱟᱣᱦᱨᱬᱭᱰᱳᱶᱷ\
𐌳𐌸𐌾𐐀𐐁𐐂𐐆𐐇𐐈𐐉𐐊𐐋𐐌𐐍𐐎𐐏";
static B256: LazyLock<Vec<char>> = LazyLock::new(|| {
let table: Vec<char> = B256_GLYPHS.chars().collect();
assert_eq!(table.len(), 256, "b256 glyph table must hold 256 entries");
table
});
static B256_INDEX: LazyLock<HashMap<char, u8>> = LazyLock::new(|| {
B256.iter()
.enumerate()
.map(|(index, glyph)| (*glyph, index as u8))
.collect()
});
pub fn b256rep(data: &[u8]) -> String {
data.iter().map(|byte| B256[*byte as usize]).collect()
}
#[allow(dead_code)]
pub fn b256_to_bytes(input: &str) -> Result<Vec<u8>, String> {
input
.chars()
.map(|glyph| {
B256_INDEX
.get(&glyph)
.copied()
.ok_or_else(|| format!("Could not decode base256: invalid glyph {glyph:?}"))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
// Generated by running the verbatim 1.3.8 RNS/__init__.py b256 helpers over
// bytes(range(256)) — proves the table copy is glyph-for-glyph faithful.
const PYTHON_138_ALL_BYTES: &str = "abcdefghijklmnopqrstuvxyzæø01234ABCDEFGHIJKLMNOPQRSTUWXYZÆØ56789αβγδεζηθικλμνξπρστφχψωΓΔΘΛΞΠΣΦΨΩБДЖЗИЛПЦЧШЩЪЫЭЮЯбджзилпцчшщъыэюяԱԲԳԴԵԶԷԸԹԺԻԽԾԿՀՁՂՃՄՅՆՇՈՉՊՋՎՐՑՒՔՖᚠᚢᚦᚱᚹᚺᚾᛈᛇᛉᛊᛏᛒᛖᛗᛟイウオカキケサシスセタチテトナヌネヒフヘホマミムメモヤラリルレワ𐑐𐑑𐑒𐑔𐑕𐑗𐑙𐑳𐑶𐑸𐑹𐑺𐑻𐑽𐑾𐑿᱑᱕᱘᱙ᱚᱝᱟᱣᱦᱨᱬᱭᱰᱳᱶᱷ𐌳𐌸𐌾𐐀𐐁𐐂𐐆𐐇𐐈𐐉𐐊𐐋𐐌𐐍𐐎𐐏";
#[test]
fn matches_python_138_table() {
let all_bytes: Vec<u8> = (0..=255u8).collect();
assert_eq!(b256rep(&all_bytes), PYTHON_138_ALL_BYTES);
}
#[test]
fn round_trips_all_byte_values() {
let all_bytes: Vec<u8> = (0..=255u8).collect();
let encoded = b256rep(&all_bytes);
assert_eq!(b256_to_bytes(&encoded).unwrap(), all_bytes);
}
#[test]
fn decode_rejects_unknown_glyph() {
assert!(b256_to_bytes("ab!").is_err());
// 'w' and 'V' are deliberately absent from the upstream table.
assert!(b256_to_bytes("w").is_err());
assert!(b256_to_bytes("V").is_err());
}
}
+224 -23
View File
@@ -8,13 +8,77 @@ pub fn run(cmd: HwCommands) {
pin,
nickname,
output,
mgmt_key,
} => {
cmd_provision(pin, nickname, output);
cmd_provision(pin, nickname, output, mgmt_key);
}
HwCommands::List { dir } => cmd_list(dir),
HwCommands::Info { hwid } => cmd_info(hwid),
HwCommands::Verify { hwid } => cmd_verify(hwid),
HwCommands::Test { hwid } => cmd_test(hwid),
HwCommands::Test { hwid, pin } => cmd_test(hwid, pin),
HwCommands::Attest => cmd_attest(),
}
}
/// Fetch on-card attestation certs and verify the chain to a bundled Yubico root.
/// ATTEST + reading the F9 device cert are unauthenticated (no PIN).
fn cmd_attest() {
let mut session = match rns_ratkey::PcscPivSession::connect() {
Ok(s) => s,
Err(e) => {
eprintln!("Error connecting to hardware token: {e}");
eprintln!("\nRun `rnid-rs hw detect` to check for connected devices.");
std::process::exit(1);
}
};
let device_cert = match session.read_attestation_cert() {
Ok(c) => c,
Err(e) => {
eprintln!("Error reading device attestation cert (slot F9): {e}");
std::process::exit(1);
}
};
println!(
"Attesting {} (serial {}, firmware {})...\n",
session.device_type().as_str(),
session.serial().unwrap_or(0),
session.firmware().unwrap_or("unknown"),
);
let mut all_ok = true;
for (label, slot) in [
("9A (signing)", rns_ratkey::apdu::SLOT_AUTHENTICATION),
("9D (encryption)", rns_ratkey::apdu::SLOT_KEY_MANAGEMENT),
] {
match session.attest_key(slot) {
Ok(cert) => match rns_ratkey::attestation::verify_attestation(&cert, &device_cert) {
Ok(v) => {
println!("Slot {label}:");
println!(" chain_verified: {}", v.chain_verified);
println!(" root CA: {}", v.root_ca);
println!(" {}", v.description);
all_ok &= v.chain_verified;
}
Err(e) => {
eprintln!("Slot {label}: verification error: {e}");
all_ok = false;
}
},
Err(e) => {
eprintln!("Slot {label}: attest error: {e}");
all_ok = false;
}
}
println!();
}
if all_ok {
println!("✓ Attestation chain cryptographically verified to a bundled Yubico root.");
} else {
eprintln!("✗ Attestation could not be fully verified.");
std::process::exit(1);
}
}
@@ -66,7 +130,42 @@ fn cmd_detect() {
}
}
fn cmd_provision(pin: Option<String>, nickname: Option<String>, output: Option<PathBuf>) {
/// Best-effort on-card attestation capture for the `.hwid`: the per-slot certs +
/// the chain-verified flag. Empty on devices without PIV attestation (e.g. Nitrokey).
fn capture_attestation(
session: &mut rns_ratkey::PcscPivSession,
) -> rns_ratkey::hwid::HwidAttestation {
let device = match session.read_attestation_cert() {
Ok(c) => c,
Err(_) => return Default::default(),
};
let ed = session
.attest_key(rns_ratkey::apdu::SLOT_AUTHENTICATION)
.ok();
let x = session
.attest_key(rns_ratkey::apdu::SLOT_KEY_MANAGEMENT)
.ok();
let verified = ed
.as_ref()
.and_then(|c| rns_ratkey::attestation::verify_attestation(c, &device).ok())
.map(|v| v.chain_verified)
.unwrap_or(false);
rns_ratkey::hwid::HwidAttestation {
ed25519_cert: ed.map(hex::encode).unwrap_or_default(),
x25519_cert: x.map(hex::encode).unwrap_or_default(),
verified,
}
}
/// Factory-default PIV management key (24 bytes; AES-192 on YubiKey 5.7+).
const DEFAULT_MGMT_KEY: &str = "010203040506070801020304050607080102030405060708";
fn cmd_provision(
pin: Option<String>,
nickname: Option<String>,
output: Option<PathBuf>,
mgmt_key: Option<String>,
) {
let pin = match pin {
Some(p) => p,
None => {
@@ -81,7 +180,7 @@ fn cmd_provision(pin: Option<String>, nickname: Option<String>, output: Option<P
std::process::exit(1);
}
let mut session = match rns_ratkey::session::PivSession::connect() {
let mut session = match rns_ratkey::PcscPivSession::connect() {
Ok(s) => s,
Err(e) => {
eprintln!("Error connecting to hardware token: {e}");
@@ -95,12 +194,29 @@ fn cmd_provision(pin: Option<String>, nickname: Option<String>, output: Option<P
std::process::exit(1);
}
// Slot 9A (PIV authentication), touch-always: prevents silent sign while PIN cache valid.
// Key generation is an administrative op gated by the management key, not the PIN.
let mgmt_key_hex = mgmt_key.unwrap_or_else(|| DEFAULT_MGMT_KEY.to_string());
let mgmt_key_bytes = match hex::decode(mgmt_key_hex.trim()) {
Ok(b) => b,
Err(e) => {
eprintln!("Error: invalid --mgmt-key hex: {e}");
std::process::exit(1);
}
};
if let Err(e) = session.authenticate_management_key(&mgmt_key_bytes) {
eprintln!("Management key authentication failed: {e}");
eprintln!("Pass --mgmt-key <hex> if the device uses a non-default management key.");
std::process::exit(1);
}
// Slot 9A (PIV authentication). PIN-once + touch-never: the PIN is the
// session unlock; the app re-locks on timeout / quit. (Policies are burned
// in permanently for a hardware-only identity.)
println!("Generating Ed25519 key in slot 9A...");
let ed_pub = match session.generate_ed25519(
rns_ratkey::apdu::SLOT_AUTHENTICATION,
Some(rns_ratkey::apdu::PIN_POLICY_ONCE),
Some(rns_ratkey::apdu::TOUCH_POLICY_ALWAYS),
Some(rns_ratkey::apdu::TOUCH_POLICY_NEVER),
) {
Ok(pub_key) => pub_key,
Err(e) => {
@@ -109,12 +225,13 @@ fn cmd_provision(pin: Option<String>, nickname: Option<String>, output: Option<P
}
};
// Slot 9D (PIV key management), touch-cached: one tap unlocks ECDH for a window (else every packet prompts).
// Slot 9D (PIV key management). PIN-once + touch-never: ECDH runs on every
// inbound packet, so per-op touch is impractical; the PIN gates the session.
println!("Generating X25519 key in slot 9D...");
let x_pub = match session.generate_x25519(
rns_ratkey::apdu::SLOT_KEY_MANAGEMENT,
Some(rns_ratkey::apdu::PIN_POLICY_ONCE),
Some(rns_ratkey::apdu::TOUCH_POLICY_CACHED),
Some(rns_ratkey::apdu::TOUCH_POLICY_NEVER),
) {
Ok(pub_key) => pub_key,
Err(e) => {
@@ -126,11 +243,15 @@ fn cmd_provision(pin: Option<String>, nickname: Option<String>, output: Option<P
let identity_hash = rns_ratkey::provision::compute_identity_hash(&ed_pub, &x_pub);
let hash_hex = hex::encode(identity_hash);
// Capture + verify the on-card attestation chain so the .hwid records it.
let attestation = capture_attestation(&mut session);
println!("\nHardware identity provisioned:");
println!(" Identity hash: {hash_hex}");
println!(" Ed25519 public: {}", hex::encode(ed_pub));
println!(" X25519 public: {}", hex::encode(x_pub));
println!(" Device: {}", session.device_type().as_str());
println!(" Attestation: chain_verified={}", attestation.verified);
if let Some(dir) = output {
let identity_dir = dir.join(&hash_hex);
@@ -164,10 +285,10 @@ fn cmd_provision(pin: Option<String>, nickname: Option<String>, output: Option<P
},
policy: rns_ratkey::hwid::HwidPolicy {
pin_cache_timeout: 300,
touch_signing: "always".to_string(),
touch_encryption: "cached".to_string(),
touch_signing: "never".to_string(),
touch_encryption: "never".to_string(),
},
attestation: Default::default(),
attestation: attestation.clone(),
app: Default::default(),
backup: Default::default(),
};
@@ -292,7 +413,22 @@ fn cmd_verify(hwid_path: PathBuf) {
println!("Verifying hardware identity {}...", config.identity.hash);
let session = match rns_ratkey::session::PivSession::connect() {
let expected_ed = match config.ed25519_pub_bytes() {
Ok(k) => k,
Err(e) => {
eprintln!("Error: .hwid has invalid Ed25519 key: {e}");
std::process::exit(1);
}
};
let expected_x = match config.x25519_pub_bytes() {
Ok(k) => k,
Err(e) => {
eprintln!("Error: .hwid has invalid X25519 key: {e}");
std::process::exit(1);
}
};
let mut session = match rns_ratkey::PcscPivSession::connect() {
Ok(s) => s,
Err(e) => {
eprintln!("Error: cannot connect to hardware token: {e}");
@@ -300,20 +436,42 @@ fn cmd_verify(hwid_path: PathBuf) {
}
};
let metadata = match session.read_metadata(rns_ratkey::apdu::SLOT_AUTHENTICATION) {
Ok(m) => m,
Err(e) => {
eprintln!("Error reading slot 9A: {e}");
std::process::exit(1);
// Reads the slot public keys from GET METADATA and compares against the .hwid.
// This is the on-device confirmation of the metadata parser before it gates
// HardwareIdentity construction.
let mut ok = true;
match session.read_public_key(rns_ratkey::apdu::SLOT_AUTHENTICATION) {
Ok(dev_ed) if dev_ed == expected_ed => println!(" Slot 9A (Ed25519): MATCH"),
Ok(_) => {
println!(" Slot 9A (Ed25519): MISMATCH");
ok = false;
}
};
Err(e) => {
println!(" Slot 9A (Ed25519): error reading key: {e}");
ok = false;
}
}
match session.read_public_key(rns_ratkey::apdu::SLOT_KEY_MANAGEMENT) {
Ok(dev_x) if dev_x == expected_x => println!(" Slot 9D (X25519): MATCH"),
Ok(_) => {
println!(" Slot 9D (X25519): MISMATCH");
ok = false;
}
Err(e) => {
println!(" Slot 9D (X25519): error reading key: {e}");
ok = false;
}
}
println!(" Slot 9A metadata: {} bytes", metadata.len());
println!(" Verification requires comparing public keys from device with .hwid file.");
println!(" (Full verification implemented when hardware is available for testing)");
if ok {
println!("\nVerified: connected token matches this .hwid.");
} else {
println!("\nVerification FAILED: token does not match this .hwid.");
std::process::exit(1);
}
}
fn cmd_test(hwid_path: PathBuf) {
fn cmd_test(hwid_path: PathBuf, pin: Option<String>) {
let config = match rns_ratkey::hwid::HwidConfig::from_file(&hwid_path) {
Ok(c) => c,
Err(e) => {
@@ -322,9 +480,18 @@ fn cmd_test(hwid_path: PathBuf) {
}
};
let pin = match pin {
Some(p) => p,
None => {
eprintln!("Error: --pin is required (PIN-once keys need one verification per session)");
eprintln!("Usage: rnid-rs hw test <hwid> --pin <PIN>");
std::process::exit(1);
}
};
println!("Testing hardware identity {}...\n", config.identity.hash);
let session = match rns_ratkey::session::PivSession::connect() {
let mut session = match rns_ratkey::PcscPivSession::connect() {
Ok(s) => s,
Err(e) => {
eprintln!("Error: cannot connect to hardware token: {e}");
@@ -332,6 +499,12 @@ fn cmd_test(hwid_path: PathBuf) {
}
};
// PIN_POLICY_ONCE: a fresh session must verify the PIN before any private-key op.
if let Err(e) = session.verify_pin(&pin) {
eprintln!("PIN verification failed: {e}");
std::process::exit(1);
}
println!("1. Testing Ed25519 signing in slot 9A...");
let test_msg = b"RATKEY hardware identity test message";
match session.sign_ed25519(rns_ratkey::apdu::SLOT_AUTHENTICATION, test_msg) {
@@ -373,5 +546,33 @@ fn cmd_test(hwid_path: PathBuf) {
}
}
println!("3. Testing HardwareIdentity decrypt (on-device ECDH + HKDF + AES) end-to-end...");
let mut hw = match rns_ratkey::HardwareIdentity::from_hwid(config.clone(), Box::new(session)) {
Ok(h) => h,
Err(e) => {
println!(" FAIL: cannot build HardwareIdentity: {e}");
std::process::exit(1);
}
};
let plaintext = b"RATKEY end-to-end decrypt test";
let ciphertext = match hw.as_identity().encrypt(plaintext, None) {
Ok(c) => c,
Err(e) => {
println!(" FAIL: encrypt to hardware identity failed: {e}");
std::process::exit(1);
}
};
match hw.decrypt(&ciphertext, None, false) {
Ok(pt) if pt == plaintext => println!(" PASS: round-trip decrypt via on-device ECDH"),
Ok(_) => {
println!(" FAIL: decrypted plaintext mismatch");
std::process::exit(1);
}
Err(e) => {
println!(" FAIL: {e}");
std::process::exit(1);
}
}
println!("\nAll tests passed.");
}
File diff suppressed because it is too large. Load diff
+524
View File
@@ -0,0 +1,524 @@
//! RSM metadata embedding: ConfigObj-subset INI parsing plus the Validator
//! subset used for `--meta-spec` (string/integer/float/boolean with min/max/
//! default; unknown checks fail validation, matching upstream behavior where
//! Validator returns a failed result for unrecognized check names).
//!
//! Python ref: 1.3.8 `RNS/Utilities/rnid.py:566-586` (`rsg_meta_from_file`,
//! commit f0824fd7) with `RNS/vendor/configobj.py` + `RNS/vendor/validate.py`.
//! Like upstream, spec check expressions containing commas are unusable: the
//! INI list division splits them before check parsing (upstream raises inside
//! Validator; here it is a validation error on the same rnid error path).
use std::path::Path;
use rmpv::Value;
#[derive(Debug, Clone, PartialEq)]
pub enum MetaValue {
Str(String),
List(Vec<String>),
Int(i64),
Float(f64),
Bool(bool),
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct MetaSection {
pub scalars: Vec<(String, MetaValue)>,
pub sections: Vec<(String, MetaSection)>,
}
impl MetaSection {
fn scalar_mut(&mut self, key: &str) -> Option<&mut MetaValue> {
self.scalars
.iter_mut()
.find(|(k, _)| k == key)
.map(|(_, v)| v)
}
fn has_scalar(&self, key: &str) -> bool {
self.scalars.iter().any(|(k, _)| k == key)
}
fn has_section(&self, name: &str) -> bool {
self.sections.iter().any(|(k, _)| k == name)
}
}
/// Load and parse a metadata file, optionally validating against a spec file.
/// Mirrors `rsg_meta_from_file` (1.3.8 rnid.py:566-575).
pub fn rsg_meta_from_file(
path: &Path,
spec_path: Option<&Path>,
) -> Result<Vec<(String, Value)>, String> {
let content = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
let mut meta = parse_ini(&content)?;
if let Some(spec_path) = spec_path {
let spec_content = std::fs::read_to_string(spec_path).map_err(|e| e.to_string())?;
let spec = parse_ini(&spec_content)?;
validate_section(&mut meta, &spec)
.map_err(|_| "Metadata did not pass spec validation".to_string())?;
}
Ok(section_to_values(&meta))
}
/// Convert a parsed section to ordered `(key, msgpack value)` pairs, scalars
/// first then subsections — the same ordering ConfigObj `.dict()` yields.
pub fn section_to_values(section: &MetaSection) -> Vec<(String, Value)> {
let mut out = Vec::with_capacity(section.scalars.len() + section.sections.len());
for (key, value) in &section.scalars {
out.push((key.clone(), meta_value_to_rmpv(value)));
}
for (name, sub) in &section.sections {
let entries = section_to_values(sub)
.into_iter()
.map(|(k, v)| (Value::from(k.as_str()), v))
.collect();
out.push((name.clone(), Value::Map(entries)));
}
out
}
fn meta_value_to_rmpv(value: &MetaValue) -> Value {
match value {
MetaValue::Str(s) => Value::from(s.as_str()),
MetaValue::List(items) => {
Value::Array(items.iter().map(|s| Value::from(s.as_str())).collect())
}
MetaValue::Int(i) => Value::from(*i),
MetaValue::Float(f) => Value::F64(*f),
MetaValue::Bool(b) => Value::Boolean(*b),
}
}
pub fn parse_ini(content: &str) -> Result<MetaSection, String> {
let mut root = MetaSection::default();
let mut path: Vec<String> = Vec::new();
for (index, raw_line) in content.lines().enumerate() {
let line_num = index + 1;
let line = raw_line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
if line.starts_with('[') {
let depth = line.chars().take_while(|&c| c == '[').count();
let closing = line.chars().rev().take_while(|&c| c == ']').count();
if depth != closing || line.len() < depth + closing {
return Err(format!("line {line_num}: malformed section header"));
}
let name = unquote(line[depth..line.len() - closing].trim());
if name.is_empty() {
return Err(format!("line {line_num}: empty section name"));
}
if depth > path.len() + 1 {
return Err(format!("line {line_num}: section nested too deep"));
}
path.truncate(depth - 1);
let parent = section_for_path(&mut root, &path);
if parent.has_section(&name) || parent.has_scalar(&name) {
return Err(format!("line {line_num}: duplicate section name"));
}
parent.sections.push((name.clone(), MetaSection::default()));
path.push(name);
continue;
}
let Some(eq_pos) = line.find('=') else {
return Err(format!("line {line_num}: unrecognized line"));
};
let key = unquote(line[..eq_pos].trim());
if key.is_empty() {
return Err(format!("line {line_num}: empty key"));
}
let value =
parse_value(line[eq_pos + 1..].trim()).map_err(|e| format!("line {line_num}: {e}"))?;
let section = section_for_path(&mut root, &path);
if section.has_scalar(&key) || section.has_section(&key) {
return Err(format!("line {line_num}: duplicate keyword name"));
}
section.scalars.push((key, value));
}
Ok(root)
}
fn section_for_path<'a>(root: &'a mut MetaSection, path: &[String]) -> &'a mut MetaSection {
let mut current = root;
for name in path {
let index = current
.sections
.iter()
.position(|(k, _)| k == name)
.expect("section path always points at existing sections");
current = &mut current.sections[index].1;
}
current
}
/// ConfigObj value semantics: inline comments outside quotes are stripped;
/// commas outside quotes divide the value into a list of strings; a lone
/// comma is the empty-list marker; members are unquoted.
fn parse_value(input: &str) -> Result<MetaValue, String> {
let stripped = strip_inline_comment(input);
let trimmed = stripped.trim();
if trimmed.starts_with("\"\"\"") || trimmed.starts_with("'''") {
return Err("multiline values are not supported".to_string());
}
if trimmed == "," {
return Ok(MetaValue::List(Vec::new()));
}
let members = split_unquoted_commas(trimmed)?;
if members.len() == 1 {
return Ok(MetaValue::Str(unquote(members[0].trim())));
}
let mut items = Vec::new();
for (index, member) in members.iter().enumerate() {
let member = member.trim();
if member.is_empty() {
if index == members.len() - 1 {
continue; // trailing comma
}
return Err("empty list member".to_string());
}
items.push(unquote(member));
}
Ok(MetaValue::List(items))
}
fn strip_inline_comment(input: &str) -> &str {
let mut quote: Option<char> = None;
for (pos, ch) in input.char_indices() {
match quote {
Some(q) if ch == q => quote = None,
None if ch == '\'' || ch == '"' => quote = Some(ch),
None if ch == '#' => return &input[..pos],
_ => {}
}
}
input
}
fn split_unquoted_commas(input: &str) -> Result<Vec<&str>, String> {
let mut members = Vec::new();
let mut quote: Option<char> = None;
let mut start = 0;
for (pos, ch) in input.char_indices() {
match quote {
Some(q) if ch == q => quote = None,
None if ch == '\'' || ch == '"' => quote = Some(ch),
None if ch == ',' => {
members.push(&input[start..pos]);
start = pos + 1;
}
_ => {}
}
}
if quote.is_some() {
return Err("unterminated quote".to_string());
}
members.push(&input[start..]);
Ok(members)
}
fn unquote(token: &str) -> String {
let bytes = token.as_bytes();
if bytes.len() >= 2 {
let first = bytes[0];
if (first == b'\'' || first == b'"') && bytes[bytes.len() - 1] == first {
return token[1..token.len() - 1].to_string();
}
}
token.to_string()
}
/// Walk the spec, coercing matching meta values in place. Missing keys take
/// the check's `default` when present and fail validation otherwise; unknown
/// check names fail; keys absent from the spec pass through untouched.
fn validate_section(meta: &mut MetaSection, spec: &MetaSection) -> Result<(), ()> {
for (key, check) in &spec.scalars {
let MetaValue::Str(check) = check else {
// A list here means the check expression contained commas, which
// ConfigObj list division splits before Validator ever runs.
return Err(());
};
let check = parse_check(check)?;
match meta.scalar_mut(key) {
Some(value) => *value = apply_check(&check, value)?,
None => {
let default = check.default.as_ref().ok_or(())?;
let coerced = apply_check(&check, &MetaValue::Str(default.clone()))?;
meta.scalars.push((key.clone(), coerced));
}
}
}
for (name, sub_spec) in &spec.sections {
if !meta.has_section(name) {
meta.sections.push((name.clone(), MetaSection::default()));
}
let sub = meta
.sections
.iter_mut()
.find(|(k, _)| k == name)
.map(|(_, v)| v)
.expect("section ensured above");
validate_section(sub, sub_spec)?;
}
Ok(())
}
struct Check {
name: String,
min: Option<String>,
max: Option<String>,
default: Option<String>,
}
fn parse_check(expr: &str) -> Result<Check, ()> {
let expr = expr.trim();
let (name, arg) = match expr.find('(') {
Some(open) => {
if !expr.ends_with(')') {
return Err(());
}
(
expr[..open].trim(),
Some(expr[open + 1..expr.len() - 1].trim()),
)
}
None => (expr, None),
};
let mut check = Check {
name: name.to_string(),
min: None,
max: None,
default: None,
};
if let Some(arg) = arg.filter(|a| !a.is_empty()) {
match arg.split_once('=') {
Some((kw, value)) => match kw.trim() {
"min" => check.min = Some(unquote(value.trim())),
"max" => check.max = Some(unquote(value.trim())),
"default" => check.default = Some(unquote(value.trim())),
_ => return Err(()),
},
// Single positional argument is `min` (validate.py `('min', 'max')`).
None => check.min = Some(unquote(arg)),
}
}
Ok(check)
}
fn apply_check(check: &Check, value: &MetaValue) -> Result<MetaValue, ()> {
match check.name.as_str() {
"string" => {
let MetaValue::Str(s) = value else {
return Err(());
};
let min = parse_bound_int(&check.min)?;
let max = parse_bound_int(&check.max)?;
let len = s.chars().count() as i64;
if min.is_some_and(|m| len < m) || max.is_some_and(|m| len > m) {
return Err(());
}
Ok(MetaValue::Str(s.clone()))
}
"integer" => {
let MetaValue::Str(s) = value else {
return Err(());
};
let parsed: i64 = s.trim().parse().map_err(|_| ())?;
let min = parse_bound_int(&check.min)?;
let max = parse_bound_int(&check.max)?;
if min.is_some_and(|m| parsed < m) || max.is_some_and(|m| parsed > m) {
return Err(());
}
Ok(MetaValue::Int(parsed))
}
"float" => {
let MetaValue::Str(s) = value else {
return Err(());
};
let parsed: f64 = s.trim().parse().map_err(|_| ())?;
let min = parse_bound_float(&check.min)?;
let max = parse_bound_float(&check.max)?;
if min.is_some_and(|m| parsed < m) || max.is_some_and(|m| parsed > m) {
return Err(());
}
Ok(MetaValue::Float(parsed))
}
"boolean" => {
if check.min.is_some() || check.max.is_some() {
return Err(());
}
let MetaValue::Str(s) = value else {
return Err(());
};
match s.to_lowercase().as_str() {
"on" | "1" | "true" | "yes" => Ok(MetaValue::Bool(true)),
"off" | "0" | "false" | "no" => Ok(MetaValue::Bool(false)),
_ => Err(()),
}
}
_ => Err(()),
}
}
fn parse_bound_int(bound: &Option<String>) -> Result<Option<i64>, ()> {
bound
.as_ref()
.map(|s| s.trim().parse().map_err(|_| ()))
.transpose()
}
fn parse_bound_float(bound: &Option<String>) -> Result<Option<f64>, ()> {
bound
.as_ref()
.map(|s| s.trim().parse().map_err(|_| ()))
.transpose()
}
#[cfg(test)]
mod tests {
use super::*;
fn parse_and_validate(ini: &str, spec: &str) -> Result<MetaSection, ()> {
let mut meta = parse_ini(ini).map_err(|_| ())?;
let spec = parse_ini(spec).map_err(|_| ())?;
validate_section(&mut meta, &spec)?;
Ok(meta)
}
#[test]
fn parses_scalars_lists_and_nested_sections_in_order() {
// Semantics cross-checked against the vendored ConfigObj: comment
// stripping, quote handling, list division, trailing comma.
let meta = parse_ini(concat!(
"title = Test Release\n",
"tags = alpha, beta, gamma\n",
"empty =\n",
"quoted = \"hello # world\"\n",
"inline = value # trailing comment\n",
"single_item_list = one,\n",
"[origin]\n",
"name = Origins\n",
"[[nested]]\n",
"deep = yes\n",
))
.unwrap();
assert_eq!(
meta.scalars,
vec![
("title".into(), MetaValue::Str("Test Release".into())),
(
"tags".into(),
MetaValue::List(vec!["alpha".into(), "beta".into(), "gamma".into()])
),
("empty".into(), MetaValue::Str(String::new())),
("quoted".into(), MetaValue::Str("hello # world".into())),
("inline".into(), MetaValue::Str("value".into())),
(
"single_item_list".into(),
MetaValue::List(vec!["one".into()])
),
]
);
assert_eq!(meta.sections.len(), 1);
let (name, origin) = &meta.sections[0];
assert_eq!(name, "origin");
assert_eq!(
origin.scalars,
vec![("name".into(), MetaValue::Str("Origins".into()))]
);
assert_eq!(origin.sections[0].0, "nested");
assert_eq!(
origin.sections[0].1.scalars,
vec![("deep".into(), MetaValue::Str("yes".into()))]
);
}
#[test]
fn rejects_duplicates_and_bad_nesting() {
assert!(parse_ini("a = 1\na = 2\n").is_err());
assert!(parse_ini("[s]\n[s]\n").is_err());
assert!(parse_ini("[[deep]]\n").is_err());
assert!(parse_ini("no equals sign\n").is_err());
}
#[test]
fn spec_coerces_types_and_fills_defaults() {
let meta = parse_and_validate(
"name = pkg\nversion = 7\nweight = 2.5\nactive = yes\n",
"name = string(max=64)\nversion = integer(max=100)\nweight = float(min=0)\nactive = boolean\nextra = string(default=filled)\n",
)
.unwrap();
assert_eq!(
meta.scalars,
vec![
("name".into(), MetaValue::Str("pkg".into())),
("version".into(), MetaValue::Int(7)),
("weight".into(), MetaValue::Float(2.5)),
("active".into(), MetaValue::Bool(true)),
("extra".into(), MetaValue::Str("filled".into())),
]
);
}
#[test]
fn spec_failures_match_upstream_validator() {
// Out of range.
assert!(parse_and_validate("version = 200\n", "version = integer(max=100)\n").is_err());
// Missing key without default.
assert!(parse_and_validate("name = pkg\n", "name = string\ncount = integer\n").is_err());
// Unknown check name.
assert!(parse_and_validate("name = pkg\n", "name = ip_addr_list\n").is_err());
// Comma'd check expressions break upstream too (list division).
assert!(parse_and_validate("version = 7\n", "version = integer(1, 100)\n").is_err());
// Non-boolean value for boolean check.
assert!(parse_and_validate("active = maybe\n", "active = boolean\n").is_err());
// Single positional argument is min.
assert!(parse_and_validate("version = 3\n", "version = integer(5)\n").is_err());
assert!(parse_and_validate("version = 7\n", "version = integer(5)\n").is_ok());
}
#[test]
fn spec_validates_nested_sections_and_ignores_extra_keys() {
let meta = parse_and_validate(
"extra = untouched\n[sec]\nport = 8\n",
"[sec]\nport = integer\n",
)
.unwrap();
assert_eq!(
meta.scalars,
vec![("extra".into(), MetaValue::Str("untouched".into()))]
);
assert_eq!(
meta.sections[0].1.scalars,
vec![("port".into(), MetaValue::Int(8))]
);
}
#[test]
fn converts_to_ordered_msgpack_values() {
let meta = parse_ini("title = t\ntags = a, b\n[origin]\nname = o\n").unwrap();
let values = section_to_values(&meta);
assert_eq!(values[0], ("title".to_string(), Value::from("t")));
assert_eq!(
values[1],
(
"tags".to_string(),
Value::Array(vec![Value::from("a"), Value::from("b")])
)
);
let (key, origin) = &values[2];
assert_eq!(key, "origin");
assert_eq!(
origin,
&Value::Map(vec![(Value::from("name"), Value::from("o"))])
);
}
}
+198 -18
View File
@@ -65,6 +65,8 @@ pub struct ValidatedRsg {
pub signer_hash: [u8; 16],
pub file_hash: [u8; 32],
pub public_key: [u8; 64],
/// Full envelope meta map, for `--meta` display (Python signed_data["meta"]).
pub meta: Vec<(Value, Value)>,
}
struct ParsedEnvelope {
@@ -72,19 +74,34 @@ struct ParsedEnvelope {
file_hash: [u8; 32],
signer_hash: [u8; 16],
public_key: [u8; 64],
meta: Vec<(Value, Value)>,
}
pub fn is_legacy_format(rsg_data: &[u8]) -> bool {
rsg_data.len() == SIG_LEN
}
pub fn create_rsg<R: Read>(signer_identity: &Identity, message: R) -> Result<Vec<u8>, RsgError> {
/// Python ref: 1.3.8 rnid.py:488-516 create_rsg. With `embed` the message
/// bytes are packed into the envelope under "message"; `meta` keys not
/// already present are merged into the envelope meta map (rnid.py:501-503).
pub fn create_rsg<R: Read>(
signer_identity: &Identity,
mut message: R,
embed: bool,
meta: Option<&[(String, Value)]>,
) -> Result<Vec<u8>, RsgError> {
if !signer_identity.has_private_key() {
return Err(RsgError::MissingPrivateKey);
}
let file_hash = sha256_reader(message)?;
let envelope = encode_envelope(signer_identity, file_hash)?;
let (file_hash, embedded) = if embed {
let mut data = Vec::new();
message.read_to_end(&mut data)?;
(rns_crypto::sha::sha256(&data), Some(data))
} else {
(sha256_reader(message)?, None)
};
let envelope = encode_envelope(signer_identity, file_hash, embedded.as_deref(), meta)?;
let signature = signer_identity
.sign(&envelope)
.ok_or(RsgError::MissingPrivateKey)?;
@@ -95,6 +112,17 @@ pub fn create_rsg<R: Read>(signer_identity: &Identity, message: R) -> Result<Vec
Ok(out)
}
// TODO(rngit): Python 1.3.8 rnid.py:588-600 also hosts check_release_rsm_structure,
// the canonical release-manifest validator consumed only by rngit/server.py.
// Excluded per the rngit/release-manifest stub policy; a Rust rngit must port it.
/// Decode the msgpack envelope after the 64-byte signature without any
/// validation. Python ref: 1.3.8 rnid.py:413-419 extract_signed_rsg_data.
pub fn extract_signed_rsg_data(rsg_data: &[u8]) -> Option<Value> {
let envelope = rsg_data.get(SIG_LEN..)?;
rmpv::decode::read_value(&mut Cursor::new(envelope)).ok()
}
pub fn create_raw_signature<R: Read>(
signer_identity: &Identity,
mut message: R,
@@ -163,6 +191,7 @@ pub fn validate_rsg<R: Read>(
signer_hash: parsed.signer_hash,
file_hash: parsed.file_hash,
public_key: parsed.public_key,
meta: parsed.meta,
})
}
@@ -198,20 +227,42 @@ fn sha256_reader<R: Read>(mut reader: R) -> Result<[u8; 32], RsgError> {
Ok(hasher.finalize().into())
}
fn encode_envelope(identity: &Identity, file_hash: [u8; 32]) -> Result<Vec<u8>, RsgError> {
let meta = Value::Map(vec![
// Envelope layout matches Python 1.3.8 byte-for-byte: top-level key order
// hashtype, hash, meta, [message]; meta order signer, pubkey, then merged
// keys. The meta.note field is no longer emitted (dropped upstream in
// 1.2.8/1.3.2, commits a2193b9f/22ab5c29).
fn encode_envelope(
identity: &Identity,
file_hash: [u8; 32],
message: Option<&[u8]>,
meta: Option<&[(String, Value)]>,
) -> Result<Vec<u8>, RsgError> {
let mut meta_entries = vec![
(Value::from("signer"), Value::Binary(identity.hash.to_vec())),
(
Value::from("pubkey"),
Value::Binary(identity.get_public_key().to_vec()),
),
(Value::from("note"), Value::Nil),
]);
let envelope = Value::Map(vec![
];
if let Some(meta) = meta {
for (key, value) in meta {
let present = meta_entries
.iter()
.any(|(k, _)| value_as_str(k) == Some(key.as_str()));
if !present {
meta_entries.push((Value::from(key.as_str()), value.clone()));
}
}
}
let mut entries = vec![
(Value::from("hashtype"), Value::from(HASH_TYPE_SHA256)),
(Value::from("hash"), Value::Binary(file_hash.to_vec())),
(Value::from("meta"), meta),
]);
(Value::from("meta"), Value::Map(meta_entries)),
];
if let Some(message) = message {
entries.push((Value::from("message"), Value::Binary(message.to_vec())));
}
let envelope = Value::Map(entries);
let mut buf = Vec::new();
rmpv::encode::write_value(&mut buf, &envelope).map_err(|e| RsgError::Msgpack(e.to_string()))?;
Ok(buf)
@@ -244,15 +295,15 @@ fn parse_envelope(envelope: &[u8]) -> Result<ParsedEnvelope, RsgError> {
.and_then(value_as_bytes)
.and_then(slice_to_array::<64>)
.ok_or(RsgError::InvalidEnvelope("missing or invalid meta.pubkey"))?;
if map_get(meta_map, "note").is_none() {
return Err(RsgError::InvalidEnvelope("missing meta.note"));
}
// meta.note is neither required nor emitted since upstream 1.2.8/1.3.2;
// envelopes still carrying it (incl. note:nil) remain accepted.
Ok(ParsedEnvelope {
hashtype,
file_hash,
signer_hash,
public_key,
meta: meta_map.clone(),
})
}
@@ -291,7 +342,7 @@ mod tests {
use super::*;
fn message() -> &'static [u8] {
b"Reticulum 1.2.4 rsg test payload"
b"Reticulum 1.2.5 rsg test payload"
}
fn pack_value(value: Value) -> Vec<u8> {
@@ -342,7 +393,7 @@ mod tests {
#[test]
fn validates_new_rsg_with_embedded_signer() {
let identity = Identity::new();
let rsg = create_rsg(&identity, message()).unwrap();
let rsg = create_rsg(&identity, message(), false, None).unwrap();
assert!(!is_legacy_format(&rsg));
let validated = validate_rsg(&rsg, message(), None).unwrap();
@@ -354,7 +405,7 @@ mod tests {
#[test]
fn validates_new_rsg_with_required_hash() {
let identity = Identity::new();
let rsg = create_rsg(&identity, message()).unwrap();
let rsg = create_rsg(&identity, message(), false, None).unwrap();
let validated =
validate_rsg(&rsg, message(), Some(RequiredSigner::Hash(identity.hash))).unwrap();
@@ -365,7 +416,7 @@ mod tests {
fn rejects_wrong_required_hash() {
let identity = Identity::new();
let other = Identity::new();
let rsg = create_rsg(&identity, message()).unwrap();
let rsg = create_rsg(&identity, message(), false, None).unwrap();
let err =
validate_rsg(&rsg, message(), Some(RequiredSigner::Hash(other.hash))).unwrap_err();
@@ -375,12 +426,141 @@ mod tests {
#[test]
fn rejects_modified_message() {
let identity = Identity::new();
let rsg = create_rsg(&identity, message()).unwrap();
let rsg = create_rsg(&identity, message(), false, None).unwrap();
let err = validate_rsg(&rsg, b"modified".as_slice(), None).unwrap_err();
assert!(matches!(err, RsgError::HashMismatch));
}
#[test]
fn created_envelope_omits_note_field() {
let identity = Identity::new();
let rsg = create_rsg(&identity, message(), false, None).unwrap();
let Some(Value::Map(map)) = extract_signed_rsg_data(&rsg) else {
panic!("envelope must decode to a map");
};
let Some(Value::Map(meta)) = map_get(&map, "meta").cloned() else {
panic!("meta must be a map");
};
let keys: Vec<_> = meta.iter().filter_map(|(k, _)| value_as_str(k)).collect();
assert_eq!(keys, ["signer", "pubkey"]);
}
#[test]
fn accepts_envelope_with_legacy_note_field() {
// Python <=1.3.1 emitted meta.note (note:None shim) — stays accepted.
let identity = Identity::new();
let envelope = pack_value(envelope_value(
Some(Value::from(HASH_TYPE_SHA256)),
Some(Value::Binary(rns_crypto::sha::sha256(message()).to_vec())),
Some(meta_value(
Some(Value::Binary(identity.hash.to_vec())),
Some(Value::Binary(identity.get_public_key().to_vec())),
Some(Value::Nil),
)),
));
let rsg = signed_rsg(&identity, envelope);
let validated = validate_rsg(&rsg, message(), None).unwrap();
assert_eq!(validated.signer_hash, identity.hash);
}
#[test]
fn embeds_message_and_merges_meta() {
let identity = Identity::new();
let meta = vec![
("title".to_string(), Value::from("t")),
// Reserved keys must not be overridden by merged meta.
("signer".to_string(), Value::from("bogus")),
];
let rsg = create_rsg(&identity, message(), true, Some(&meta)).unwrap();
let Some(Value::Map(map)) = extract_signed_rsg_data(&rsg) else {
panic!("envelope must decode to a map");
};
assert_eq!(
map_get(&map, "message").and_then(value_as_bytes),
Some(message())
);
let Some(Value::Map(meta_map)) = map_get(&map, "meta").cloned() else {
panic!("meta must be a map");
};
let keys: Vec<_> = meta_map
.iter()
.filter_map(|(k, _)| value_as_str(k))
.collect();
assert_eq!(keys, ["signer", "pubkey", "title"]);
assert_eq!(
map_get(&meta_map, "signer").and_then(value_as_bytes),
Some(identity.hash.as_slice())
);
// The embedded message validates against the envelope hash.
let validated = validate_rsg(&rsg, message(), None).unwrap();
assert_eq!(validated.signer_hash, identity.hash);
}
#[test]
fn extract_returns_none_on_bad_envelope() {
assert!(extract_signed_rsg_data(&[0u8; 10]).is_none());
let mut rsg = vec![0u8; SIG_LEN];
rsg.extend_from_slice(&[0xd9, 0x20]);
assert!(extract_signed_rsg_data(&rsg).is_none());
}
// Fixture generated by running the VERBATIM Python 1.3.8 rnid.py create_rsg
// (git show 1.3.8:RNS/Utilities/rnid.py) with embed=True over MESSAGE using
// the identity below (vendored umsgpack + RNS Identity from pip rns).
const FIXTURE_PRV_HEX: &str = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f";
const FIXTURE_MESSAGE: &str = "Hello Reticulum 1.3.8 signed message test.\nSecond line æø.";
const FIXTURE_RSM_HEX: &str = "266bce756d1873e4b44113fd24bd57c9c8e78dc25b5acd109e9417b045a5d736520049307a49293c13b432a5899065374060fe8b97d7ef4228e40c7bdcafbf0384a86861736874797065a6736861323536a468617368c420322779176317ebc50102a216a56a68d41c8e9aa1c849f4d4eded5c31ba542795a46d65746182a67369676e6572c410aca31af0441d81dbec71e82da0b4b5f5a67075626b6579c4408f40c5adb68f25624ae5b214ea767a6ec94d829d3d7b5e1ad1ba6f3e2138285f29acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd7a76d657373616765c43c48656c6c6f205265746963756c756d20312e332e38207369676e6564206d65737361676520746573742e0a5365636f6e64206c696e6520c3a6c3b82e";
fn fixture_identity() -> Identity {
Identity::from_private_key(&hex::decode(FIXTURE_PRV_HEX).unwrap()).unwrap()
}
// Same generator, embed=False: a plain note-less .rsg as Python >=1.3.2
// emits it (rsg-note-field-drop).
const FIXTURE_RSG_HEX: &str = "804718b7b983d4d555035627aab086d91ecddea89eaf7c75aa72b5275038b478c5db2c105841a8aa06c18dc6b84a2638694937a9b649a3a06ed1d4ba3127800083a86861736874797065a6736861323536a468617368c420322779176317ebc50102a216a56a68d41c8e9aa1c849f4d4eded5c31ba542795a46d65746182a67369676e6572c410aca31af0441d81dbec71e82da0b4b5f5a67075626b6579c4408f40c5adb68f25624ae5b214ea767a6ec94d829d3d7b5e1ad1ba6f3e2138285f29acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd7";
#[test]
fn embedded_message_rsm_is_byte_exact_with_python_138() {
let identity = fixture_identity();
let rsg = create_rsg(&identity, FIXTURE_MESSAGE.as_bytes(), true, None).unwrap();
assert_eq!(hex::encode(&rsg), FIXTURE_RSM_HEX);
}
#[test]
fn plain_rsg_is_byte_exact_with_python_138_and_cross_validates() {
let identity = fixture_identity();
let rsg = create_rsg(&identity, FIXTURE_MESSAGE.as_bytes(), false, None).unwrap();
assert_eq!(hex::encode(&rsg), FIXTURE_RSG_HEX);
// Python >=1.3.2 note-less output is accepted by the Rust validator.
let python_rsg = hex::decode(FIXTURE_RSG_HEX).unwrap();
let validated = validate_rsg(&python_rsg, FIXTURE_MESSAGE.as_bytes(), None).unwrap();
assert_eq!(validated.signer_hash, identity.hash);
}
#[test]
fn validates_python_138_created_rsm() {
let rsm = hex::decode(FIXTURE_RSM_HEX).unwrap();
let identity = fixture_identity();
let Some(Value::Map(map)) = extract_signed_rsg_data(&rsm) else {
panic!("fixture envelope must decode to a map");
};
let embedded = map_get(&map, "message")
.and_then(value_as_bytes)
.expect("fixture must embed a message");
assert_eq!(embedded, FIXTURE_MESSAGE.as_bytes());
let validated =
validate_rsg(&rsm, embedded, Some(RequiredSigner::Hash(identity.hash))).unwrap();
assert_eq!(validated.signer_hash, identity.hash);
assert_eq!(validated.public_key, identity.get_public_key());
}
#[test]
fn validates_legacy_raw_signature() {
let identity = Identity::new();
+2 -3
View File
@@ -13,6 +13,7 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use clap::{CommandFactory, Parser};
use rns_interface::{kiss, rnode, rnode_admin};
use rns_tools::RS_RETICULUM_VERSION;
// rnodeconf support is staged: safe inspection/config modules are compiled now,
// while hardware-gated flashing/signing paths are wired in behind explicit CLI flows.
@@ -32,8 +33,6 @@ mod model;
#[path = "rnodeconf/trust.rs"]
mod trust;
const RNODECONF_VERSION: &str = "2.5.0";
#[derive(Parser, Debug)]
#[command(
name = "rnodeconf-rs",
@@ -166,7 +165,7 @@ struct Args {
pub(crate) fn main() -> ExitCode {
let args = Args::parse();
if args.version {
println!("rnodeconf-rs {RNODECONF_VERSION}");
println!("rnodeconf-rs {RS_RETICULUM_VERSION}");
return ExitCode::SUCCESS;
}
if let Some(trust_key) = args.trust_key.as_deref() {
+89 -9
View File
@@ -27,7 +27,7 @@ const REMOTE_TIMEOUT_SECS: u64 = 30;
const REMOTE_HOPS: u8 = 8;
const MGMT_APP: &str = "rnstransport.remote.management";
const BLACKHOLE_APP: &str = "rnstransport.info.blackhole";
const RETICULUM_COMPAT_VERSION: &str = "1.2.2";
use rns_tools::RS_RETICULUM_VERSION;
#[derive(Parser)]
#[command(
@@ -130,7 +130,7 @@ pub(crate) async fn main() -> ExitCode {
let args = Args::parse();
if args.version {
println!("rnpath-rs {RETICULUM_COMPAT_VERSION}");
println!("rnpath-rs {RS_RETICULUM_VERSION}");
return ExitCode::SUCCESS;
}
@@ -139,7 +139,13 @@ pub(crate) async fn main() -> ExitCode {
1 => tracing::Level::INFO,
_ => tracing::Level::DEBUG,
};
tracing_subscriber::fmt().with_max_level(level).init();
let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref());
rns_tools::init_tracing(
level,
rns_tools::config_log_timestamps(&config_dir),
true,
std::io::stdout,
);
if args.blackholed_list {
return run_remote_blackhole_list(args).await;
@@ -188,6 +194,7 @@ pub(crate) async fn main() -> ExitCode {
config_dir,
rpc_key,
timeout: std::time::Duration::from_secs(args.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS)),
explicit_timeout: args.timeout.map(std::time::Duration::from_secs),
};
// First matching branch wins when multiple action flags are passed.
@@ -267,15 +274,25 @@ struct ClientCtx {
config_dir: PathBuf,
rpc_key: Vec<u8>,
timeout: std::time::Duration,
/// `-w` as given; `None` means path requests wait `PATH_REQUEST_TIMEOUT`.
explicit_timeout: Option<std::time::Duration>,
}
async fn request(ctx: &ClientCtx, req: &RpcRequest) -> Result<RpcResponse, LocalRpcFailure> {
request_with_timeout(ctx, req, ctx.timeout).await
}
async fn request_with_timeout(
ctx: &ClientCtx,
req: &RpcRequest,
timeout: std::time::Duration,
) -> Result<RpcResponse, LocalRpcFailure> {
let result = match &ctx.endpoint {
SharedInstanceRpcEndpoint::Tcp(port) => {
rpc::connect_and_request(*port, &ctx.rpc_key, req, ctx.timeout).await
rpc::connect_and_request(*port, &ctx.rpc_key, req, timeout).await
}
SharedInstanceRpcEndpoint::Unix(socket_path) => {
rpc::connect_unix_and_request(socket_path, &ctx.rpc_key, req, ctx.timeout).await
rpc::connect_unix_and_request(socket_path, &ctx.rpc_key, req, timeout).await
}
};
result.map_err(|source| LocalRpcFailure {
@@ -754,13 +771,78 @@ async fn query_path(ctx: &ClientCtx, dest_hex: &str) -> ExitCode {
_ => None,
};
let path_entry = match request(ctx, &RpcRequest::GetPathTable { max_hops: None }).await {
let mut path_entry = match request(ctx, &RpcRequest::GetPathTable { max_hops: None }).await {
Ok(RpcResponse::PathTable(entries)) => entries
.into_iter()
.find(|entry| entry.hash.as_slice() == dest),
_ => None,
};
let mut next_hop = next_hop;
let mut iface = iface;
if next_hop.is_none() && path_entry.is_none() {
// Python rnpath defaults -w to Transport.PATH_REQUEST_TIMEOUT.
let timeout_secs = ctx
.explicit_timeout
.map(|d| d.as_secs_f64())
.unwrap_or(rns_transport::constants::PATH_REQUEST_TIMEOUT)
.max(0.1);
let req = RpcRequest::RequestPath {
destination_hash: dest.to_vec(),
timeout_secs: Some(timeout_secs),
};
let rpc_timeout = std::time::Duration::from_secs_f64(timeout_secs + 1.0);
let found = match request_with_timeout(ctx, &req, rpc_timeout).await {
Ok(RpcResponse::BoolResult(found)) => found,
Ok(other) => {
eprintln!("rnpath-rs: unexpected response: {other:?}");
return ExitCode::from(1);
}
Err(e) => {
eprintln!("rnpath-rs: {e}");
return ExitCode::from(1);
}
};
if found {
next_hop = match request(
ctx,
&RpcRequest::GetNextHop {
destination_hash: dest.to_vec(),
},
)
.await
{
Ok(RpcResponse::HashResult(h)) => h,
Ok(other) => {
eprintln!("rnpath-rs: unexpected response: {other:?}");
return ExitCode::from(1);
}
Err(e) => {
eprintln!("rnpath-rs: {e}");
return ExitCode::from(1);
}
};
iface = match request(
ctx,
&RpcRequest::GetNextHopIfName {
destination_hash: dest.to_vec(),
},
)
.await
{
Ok(RpcResponse::StringResult(s)) => s,
_ => None,
};
path_entry = match request(ctx, &RpcRequest::GetPathTable { max_hops: None }).await {
Ok(RpcResponse::PathTable(entries)) => entries
.into_iter()
.find(|entry| entry.hash.as_slice() == dest),
_ => None,
};
}
}
println!("Destination: {}", hex::encode(dest));
match next_hop.as_ref() {
Some(h) => println!(" Next hop : {}", hex::encode(h)),
@@ -775,9 +857,7 @@ async fn query_path(ctx: &ClientCtx, dest_hex: &str) -> ExitCode {
}
if next_hop.is_none() && path_entry.is_none() {
println!(
" Note : no cached local path was found; active path requests are not implemented in rnpath yet"
);
println!(" Note : path request timed out or no path was found");
ExitCode::from(1)
} else {
ExitCode::SUCCESS
+12 -10
View File
@@ -12,8 +12,7 @@ use rns_runtime::probe::{
};
const DEFAULT_PROBE_SIZE: usize = 16;
const DEFAULT_TIMEOUT_SECS: f64 = 12.0;
const RETICULUM_COMPAT_VERSION: &str = "1.2.2";
use rns_tools::RS_RETICULUM_VERSION;
#[derive(Parser)]
#[command(
@@ -65,7 +64,7 @@ struct Args {
pub(crate) async fn main() {
let args = Args::parse();
if args.version {
println!("rnprobe-rs {RETICULUM_COMPAT_VERSION}");
println!("rnprobe-rs {RS_RETICULUM_VERSION}");
return;
}
@@ -82,10 +81,13 @@ pub(crate) async fn main() {
1 => tracing::Level::INFO,
_ => tracing::Level::DEBUG,
};
tracing_subscriber::fmt()
.with_max_level(level)
.with_writer(std::io::stderr)
.init();
let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref());
rns_tools::init_tracing(
level,
rns_tools::config_log_timestamps(&config_dir),
true,
std::io::stderr,
);
let full_name = args
.full_name
@@ -103,9 +105,9 @@ pub(crate) async fn main() {
};
let size = args.size.unwrap_or(DEFAULT_PROBE_SIZE);
let timeout = Duration::from_secs_f64(args.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS));
// None = Python default: 12 s + first-hop timeout, resolved per wait.
let timeout = args.timeout.map(Duration::from_secs_f64);
let wait = Duration::from_secs_f64(args.wait.max(0.0));
let path_wait = timeout;
let shutdown = rns_runtime::lifecycle::ShutdownSignal::new();
let _signal_rx = rns_runtime::lifecycle::install_signal_handlers(shutdown.clone());
@@ -143,7 +145,7 @@ pub(crate) async fn main() {
&full_name,
size,
timeout,
path_wait,
timeout,
handle.should_use_implicit_proof(),
)
.await;
+74 -32
View File
@@ -7,23 +7,36 @@ use std::path::{Path, PathBuf};
use clap::Parser;
use tracing_subscriber::fmt::MakeWriter;
const RETICULUM_COMPAT_VERSION: &str = "1.2.2";
use rns_tools::{RETICULUM_COMPAT_VERSION, RS_RETICULUM_VERSION};
const LOG_ROTATE_BYTES: u64 = 5 * 1024 * 1024;
const RNSD_EXAMPLE_CONFIG: &str = r#"# This is an example Reticulum config file.
[reticulum]
enable_transport = No
share_instance = Yes
enable_transport = no
share_instance = yes
instance_name = default
# Interval in minutes at which remote blackhole sources
# are updated. Defaults to one hour.
# blackhole_update_interval = 60
# When not running as a transport node, force the same,
# static transport identity at every instance start.
# Defaults to a new identity per start if transport is
# disabled.
# static_transport_identity = no
[logging]
loglevel = 4
# You can disable timestamp inclusion in logs.
# logtimestamps = no
[interfaces]
[[Default Interface]]
type = AutoInterface
enabled = Yes
enabled = yes
[[UDP Interface]]
type = UDPInterface
@@ -60,7 +73,7 @@ bandwidth = 125000
txpower = 7
spreadingfactor = 8
codingrate = 5
flow_control = False
flow_control = false
[[Packet Radio KISS Interface]]
type = KISSInterface
@@ -134,7 +147,7 @@ pub(crate) async fn main() {
let args = Args::parse();
if args.version {
println!("rnsd-rs {RETICULUM_COMPAT_VERSION}");
println!("rnsd-rs {RS_RETICULUM_VERSION}");
return;
}
@@ -151,6 +164,7 @@ pub(crate) async fn main() {
config_loglevel + args.verbose as i32 - args.quiet as i32
};
let level = tracing_level(verbosity);
let log_timestamps = rns_tools::config_log_timestamps(&config_dir);
if args.service {
if let Err(e) = fs::create_dir_all(&config_dir) {
@@ -168,15 +182,12 @@ pub(crate) async fn main() {
);
std::process::exit(1);
}
tracing_subscriber::fmt()
.with_max_level(level)
.with_writer(LogFileWriter { path: log_path })
.init();
rns_tools::init_tracing(level, log_timestamps, false, LogFileWriter::new(log_path));
} else {
tracing_subscriber::fmt().with_max_level(level).init();
rns_tools::init_tracing(level, log_timestamps, true, std::io::stdout);
}
tracing::info!("rnsd-rs {RETICULUM_COMPAT_VERSION} starting");
tracing::info!("rnsd-rs {RS_RETICULUM_VERSION} starting");
let shutdown = rns_runtime::lifecycle::ShutdownSignal::new();
let _signal_rx = rns_runtime::lifecycle::install_signal_handlers(shutdown.clone());
@@ -214,7 +225,7 @@ async fn run_interactive_shell(handle: rns_runtime::reticulum::ReticulumHandle)
let mut stdout = io::stdout();
let _ = writeln!(
stdout,
"rnsd-rs {RETICULUM_COMPAT_VERSION} interactive console"
"rnsd-rs {RS_RETICULUM_VERSION} interactive console"
);
let _ = writeln!(
stdout,
@@ -387,23 +398,50 @@ fn rotate_log_if_needed(path: &Path) -> std::io::Result<()> {
#[derive(Clone)]
struct LogFileWriter {
path: PathBuf,
/// One persistent file handle + in-memory size counter shared across
/// `make_writer` calls — tracing calls it per event, so per-event opens
/// and per-write stats would dominate logging cost.
shared: std::sync::Arc<std::sync::Mutex<RotatingLogFile>>,
}
impl LogFileWriter {
fn new(path: PathBuf) -> Self {
Self {
shared: std::sync::Arc::new(std::sync::Mutex::new(RotatingLogFile {
path,
file: None,
size: 0,
})),
}
}
}
impl<'a> MakeWriter<'a> for LogFileWriter {
type Writer = Box<dyn Write + Send + 'a>;
type Writer = SharedLogWriter;
fn make_writer(&'a self) -> Self::Writer {
match OpenOptions::new()
.create(true)
.append(true)
.open(&self.path)
{
Ok(file) => Box::new(RotatingLogFile {
path: self.path.clone(),
file: Some(file),
}),
Err(_) => Box::new(std::io::stderr()),
SharedLogWriter(self.shared.clone())
}
}
/// Per-event writer handle; locks the shared rotating file for each write
/// and falls back to stderr if the logfile cannot be opened.
struct SharedLogWriter(std::sync::Arc<std::sync::Mutex<RotatingLogFile>>);
impl Write for SharedLogWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let mut inner = self.0.lock().expect("log writer mutex poisoned");
match inner.write(buf) {
Ok(n) => Ok(n),
Err(_) => std::io::stderr().write(buf),
}
}
fn flush(&mut self) -> io::Result<()> {
let mut inner = self.0.lock().expect("log writer mutex poisoned");
match inner.flush() {
Ok(()) => Ok(()),
Err(_) => std::io::stderr().flush(),
}
}
}
@@ -411,23 +449,25 @@ impl<'a> MakeWriter<'a> for LogFileWriter {
struct RotatingLogFile {
path: PathBuf,
file: Option<File>,
/// Current logfile size, maintained in memory; stat only happens at open.
size: u64,
}
impl RotatingLogFile {
fn file_mut(&mut self) -> io::Result<&mut File> {
if self.file.is_none() {
self.file = Some(
OpenOptions::new()
.create(true)
.append(true)
.open(&self.path)?,
);
let file = OpenOptions::new()
.create(true)
.append(true)
.open(&self.path)?;
self.size = file.metadata().map(|m| m.len()).unwrap_or(0);
self.file = Some(file);
}
Ok(self.file.as_mut().expect("log file was just opened"))
}
fn rotate_if_needed(&mut self) -> io::Result<()> {
if self.path.metadata().map(|m| m.len()).unwrap_or(0) <= LOG_ROTATE_BYTES {
if self.size <= LOG_ROTATE_BYTES {
return Ok(());
}
@@ -449,6 +489,7 @@ impl RotatingLogFile {
.append(true)
.open(&self.path)?,
);
self.size = 0;
Ok(())
}
}
@@ -456,6 +497,7 @@ impl RotatingLogFile {
impl Write for RotatingLogFile {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let written = self.file_mut()?.write(buf)?;
self.size += written as u64;
self.rotate_if_needed()?;
Ok(written)
}
+28 -17
View File
@@ -19,11 +19,12 @@ use rns_runtime::lifecycle::{ShutdownSignal, install_signal_handlers};
use rns_runtime::platform::{StoragePaths, resolve_config_dir};
use rns_runtime::rnsh::{
RnshClientConfig, RnshError, RnshListenerConfig, RnshWindowSize, rnsh_client_execute,
run_rnsh_listener,
run_rnsh_listener_with_shutdown,
};
use tokio::sync::mpsc;
const RNS_VERSION: &str = "1.2.2";
use rns_tools::RS_RETICULUM_VERSION;
const RNSH_PROTOCOL_VERSION: &str = "0.2.0";
const APP_NAME: &str = "rnsh";
const DEFAULT_SERVICE_NAME: &str = "default";
@@ -86,7 +87,7 @@ pub(crate) async fn main() -> ExitCode {
async fn run(mut args: Args) -> ExitCode {
if args.version {
println!("rnsh-rs {RNS_VERSION} (protocol {RNSH_PROTOCOL_VERSION})");
println!("rnsh-rs {RS_RETICULUM_VERSION} (protocol {RNSH_PROTOCOL_VERSION})");
return ExitCode::SUCCESS;
}
@@ -120,9 +121,12 @@ async fn run(mut args: Args) -> ExitCode {
}
async fn run_listener(args: Args) -> ExitCode {
init_logging(args.verbose, args.quiet);
// Register before any slow init so an early SIGINT exits cleanly.
let shutdown = ShutdownSignal::new();
let _signal_rx = install_signal_handlers(shutdown.clone());
init_logging(args.verbose, args.quiet, args.config.as_deref());
let handle = match start_reticulum(args.config.as_deref()).await {
let handle = match start_reticulum(args.config.as_deref(), shutdown.clone()).await {
Ok(handle) => handle,
Err(e) => {
eprintln!("rnsh-rs: failed to start reticulum: {e}");
@@ -160,7 +164,9 @@ async fn run_listener(args: Args) -> ExitCode {
announce_period: args.announce,
};
match run_rnsh_listener(handle.transport_tx.clone(), cfg).await {
match run_rnsh_listener_with_shutdown(handle.transport_tx.clone(), cfg, handle.shutdown.clone())
.await
{
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("rnsh-rs: {e}");
@@ -170,7 +176,10 @@ async fn run_listener(args: Args) -> ExitCode {
}
async fn run_initiator(args: Args) -> ExitCode {
init_logging(args.verbose, args.quiet);
// Register before any slow init so an early SIGINT exits cleanly.
let shutdown = ShutdownSignal::new();
let _signal_rx = install_signal_handlers(shutdown.clone());
init_logging(args.verbose, args.quiet, args.config.as_deref());
let destination = match args.destination.as_deref().and_then(parse_hash16) {
Some(hash) => hash,
@@ -180,7 +189,7 @@ async fn run_initiator(args: Args) -> ExitCode {
}
};
let handle = match start_reticulum(args.config.as_deref()).await {
let handle = match start_reticulum(args.config.as_deref(), shutdown.clone()).await {
Ok(handle) => handle,
Err(e) => {
eprintln!("rnsh-rs: failed to start reticulum: {e}");
@@ -251,25 +260,27 @@ async fn run_initiator(args: Args) -> ExitCode {
async fn start_reticulum(
config_dir: Option<&Path>,
shutdown: ShutdownSignal,
) -> Result<rns_runtime::reticulum::ReticulumHandle, rns_runtime::reticulum::ReticulumError> {
let shutdown = ShutdownSignal::new();
let _signal_rx = install_signal_handlers(shutdown.clone());
let is_foreground = Arc::new(AtomicBool::new(true));
let config = config_dir.and_then(|path| path.to_str());
rns_runtime::reticulum::init(config, None, shutdown, is_foreground).await
}
fn init_logging(verbose: u8, quiet: u8) {
fn init_logging(verbose: u8, quiet: u8, config_dir: Option<&Path>) {
let level = match (verbose as i32) - (quiet as i32) {
n if n >= 2 => tracing::Level::DEBUG,
1 => tracing::Level::INFO,
0 => tracing::Level::WARN,
_ => tracing::Level::ERROR,
};
let _ = tracing_subscriber::fmt()
.with_max_level(level)
.with_writer(std::io::stderr)
.try_init();
let resolved = resolve_config_dir(config_dir.and_then(|path| path.to_str()));
rns_tools::init_tracing(
level,
rns_tools::config_log_timestamps(&resolved),
true,
std::io::stderr,
);
}
fn terminal_window_size() -> (Option<u32>, Option<u32>, Option<u32>, Option<u32>) {
@@ -871,8 +882,8 @@ mod tests {
#[test]
fn version_string_uses_rust_command_name() {
assert_eq!(
format!("rnsh-rs {RNS_VERSION} (protocol {RNSH_PROTOCOL_VERSION})"),
"rnsh-rs 1.2.2 (protocol 0.2.0)"
format!("rnsh-rs {RS_RETICULUM_VERSION} (protocol {RNSH_PROTOCOL_VERSION})"),
format!("rnsh-rs {} (protocol 0.2.0)", env!("CARGO_PKG_VERSION"))
);
}
+465 -91
View File
@@ -27,7 +27,7 @@ const DEFAULT_TIMEOUT_SECS: u64 = 5;
const REMOTE_TIMEOUT_SECS: u64 = 30;
const REMOTE_HOPS: u8 = 8;
const MGMT_APP: &str = "rnstransport.remote.management";
const RETICULUM_COMPAT_VERSION: &str = "1.2.4";
use rns_tools::RS_RETICULUM_VERSION;
#[derive(Parser)]
#[command(
@@ -44,15 +44,23 @@ struct Args {
#[arg(short = 'A', long)]
announce_stats: bool,
/// Show path request frequency stats.
#[arg(short = 'P', long = "pr-stats")]
pr_stats: bool,
/// Show link table entry count.
#[arg(short, long)]
link_stats: bool,
/// Only show interfaces with active announce or path request bursts.
#[arg(short = 'B', long)]
burst: bool,
/// Display traffic totals.
#[arg(short, long)]
totals: bool,
/// Sort interfaces by rate, traffic, rx, tx, rxs, txs, announces, arx, atx or held.
/// Sort interfaces by rate, traffic, rx, tx, rxs, txs, announces, arx, atx, prx, ptx or held.
#[arg(short, long)]
sort: Option<String>,
@@ -117,7 +125,7 @@ pub(crate) async fn main() -> ExitCode {
let args = Args::parse();
if args.version {
println!("rnstatus-rs {RETICULUM_COMPAT_VERSION}");
println!("rnstatus-rs {RS_RETICULUM_VERSION}");
return ExitCode::SUCCESS;
}
if let Err(e) = validate_args(&args) {
@@ -132,7 +140,13 @@ pub(crate) async fn main() -> ExitCode {
1 => tracing::Level::INFO,
_ => tracing::Level::DEBUG,
};
tracing_subscriber::fmt().with_max_level(level).init();
let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref());
rns_tools::init_tracing(
level,
rns_tools::config_log_timestamps(&config_dir),
true,
std::io::stdout,
);
if args.monitor {
run_monitor(args).await
@@ -144,21 +158,38 @@ pub(crate) async fn main() -> ExitCode {
}
async fn run_monitor(args: Args) -> ExitCode {
let interval = Duration::from_secs_f64(args.monitor_interval.max(0.1));
// Python 1.3.8 rnstatus.py:714-744 (commit 32389002): one RNS instance and
// one remote destination live across refreshes; only the request repeats.
let session = if args.remote.is_some() {
match RemoteSession::open(&args).await {
Ok(s) => Some(s),
Err(code) => return code,
}
} else {
None
};
loop {
let started = std::time::Instant::now();
print!("\x1b[2J\x1b[H");
let exit = if args.remote.is_some() {
run_remote_once(&args).await
} else {
run_local_once(&args).await
let exit = match &session {
Some(session) => session.query_and_print(&args).await,
None => run_local_once(&args).await,
};
if exit != ExitCode::SUCCESS {
if let Some(session) = &session {
session.shutdown.trigger();
}
return exit;
}
tokio::time::sleep(interval).await;
tokio::time::sleep(monitor_sleep(args.monitor_interval, started.elapsed())).await;
}
}
/// Python 1.3.8 rnstatus.py:742-744: sleep `max(interval - render time, 0.2)`.
fn monitor_sleep(interval_secs: f64, elapsed: Duration) -> Duration {
Duration::from_secs_f64((interval_secs - elapsed.as_secs_f64()).max(0.2))
}
async fn run_local(args: Args) -> ExitCode {
run_local_once(&args).await
}
@@ -200,6 +231,10 @@ async fn run_local_once(args: &Args) -> ExitCode {
match local_rpc_request(&endpoint, &rpc_key, &RpcRequest::GetInterfaceStats, timeout).await
{
Ok(RpcResponse::InterfaceStats(v)) => v,
Ok(RpcResponse::Error(e)) => {
eprintln!("rnstatus-rs: {e}");
return ExitCode::from(1);
}
Ok(other) => {
eprintln!("rnstatus-rs: unexpected response: {other:?}");
return ExitCode::from(1);
@@ -323,13 +358,15 @@ enum SortKey {
Announces,
AnnounceRx,
AnnounceTx,
PathRequestRx,
PathRequestTx,
Held,
}
fn validate_args(args: &Args) -> Result<(), String> {
parse_sort_key(args.sort.as_deref()).map(|_| ())?;
if args.monitor_interval <= 0.0 {
return Err("--monitor-interval must be greater than 0".to_string());
if !(args.monitor_interval > 0.0 && args.monitor_interval.is_finite()) {
return Err("--monitor-interval must be a finite number greater than 0".to_string());
}
if (args.discovered || args.discovered_details) && args.remote.is_some() {
return Err(
@@ -353,10 +390,12 @@ fn parse_sort_key(value: Option<&str>) -> Result<Option<SortKey>, String> {
"announces" | "announce" => SortKey::Announces,
"arx" => SortKey::AnnounceRx,
"atx" => SortKey::AnnounceTx,
"prx" => SortKey::PathRequestRx,
"ptx" => SortKey::PathRequestTx,
"held" => SortKey::Held,
_ => {
return Err(format!(
"--sort must be one of rate, traffic, rx, tx, rxs, txs, announces, arx, atx or held; got {value}"
"--sort must be one of rate, traffic, rx, tx, rxs, txs, announces, arx, atx, prx, ptx or held; got {value}"
));
}
};
@@ -374,10 +413,38 @@ fn local_stat_sort_value(e: &rpc::InterfaceStatEntry, key: SortKey) -> f64 {
SortKey::Announces => e.incoming_announce_frequency + e.outgoing_announce_frequency,
SortKey::AnnounceRx => e.incoming_announce_frequency,
SortKey::AnnounceTx => e.outgoing_announce_frequency,
SortKey::PathRequestRx => e.incoming_pr_frequency,
SortKey::PathRequestTx => e.outgoing_pr_frequency,
SortKey::Held => e.held_announces as f64,
}
}
/// Python 1.3.8 rnstatus.py:421-427 mode string table (unknown modes render "Full").
fn mode_display_name(mode: &str) -> &'static str {
match mode {
"AccessPoint" | "Access Point" => "Access Point",
"PointToPoint" | "Point-to-Point" => "Point-to-Point",
"Roaming" => "Roaming",
"Boundary" => "Boundary",
"Gateway" => "Gateway",
"Internal" => "Internal",
_ => "Full",
}
}
/// Same table keyed on the numeric mode carried by remote /status responses.
fn remote_mode_display_name(mode: u64) -> &'static str {
match mode {
0x02 => "Point-to-Point",
0x03 => "Access Point",
0x04 => "Roaming",
0x05 => "Boundary",
0x06 => "Gateway",
0x07 => "Internal",
_ => "Full",
}
}
fn visible_by_default(name: &str) -> bool {
!(name.starts_with("LocalInterface[")
|| name.starts_with("TCPInterface[Client")
@@ -394,6 +461,24 @@ fn interface_matches_filter(name: &str, filter: Option<&str>) -> bool {
})
}
fn interface_matches_burst_filter(
name: &str,
burst_active: bool,
pr_burst_active: bool,
args: &Args,
) -> bool {
if !args.burst {
return interface_matches_filter(name, args.filter.as_deref());
}
burst_active
|| pr_burst_active
|| args.filter.as_deref().is_some_and(|filter| {
name.to_ascii_lowercase()
.contains(&filter.to_ascii_lowercase())
})
}
fn filtered_local_stats<'a>(
stats: &'a [rpc::InterfaceStatEntry],
args: &Args,
@@ -401,7 +486,14 @@ fn filtered_local_stats<'a>(
let mut entries: Vec<_> = stats
.iter()
.filter(|entry| args.all || visible_by_default(&entry.name))
.filter(|entry| interface_matches_filter(&entry.name, args.filter.as_deref()))
.filter(|entry| {
interface_matches_burst_filter(
&entry.name,
entry.burst_active,
entry.pr_burst_active,
args,
)
})
.collect();
if let Ok(Some(key)) = parse_sort_key(args.sort.as_deref()) {
entries.sort_by(|a, b| {
@@ -429,7 +521,7 @@ fn print_local_human(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
let status = if entry.online { "Up" } else { "Down" };
println!(" {}", entry.name);
println!(" Status : {status}");
println!(" Mode : {}", entry.mode);
println!(" Mode : {}", mode_display_name(&entry.mode));
println!(" Role : {}", entry.role);
println!(" Bitrate : {}", format::pretty_speed(entry.bitrate));
println!(" MTU : {} B", entry.mtu);
@@ -457,6 +549,7 @@ fn print_local_human(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
}
if entry.incoming_announce_frequency > 0.0
|| entry.outgoing_announce_frequency > 0.0
|| entry.burst_active
{
print_announce_frequency(
entry.incoming_announce_frequency,
@@ -465,9 +558,18 @@ fn print_local_human(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
entry.announce_rate_target,
entry.announce_rate_penalty,
entry.announce_rate_grace,
burst_status_text(entry.burst_active, entry.burst_activated),
);
}
}
if args.pr_stats {
print_path_request_frequency(
entry.incoming_pr_frequency,
entry.outgoing_pr_frequency,
entry.clients,
burst_status_text(entry.pr_burst_active, entry.pr_burst_activated),
);
}
println!(
" Traffic : {} rx / {} tx",
format::pretty_size(entry.rx_bytes),
@@ -514,7 +616,7 @@ fn print_local_json(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
print!(",");
}
print!(
"{{\"name\":{},\"online\":{},\"mode\":{},\"role\":{},\"bitrate\":{},\"mtu\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{},\"tx_drops\":{}}}",
"{{\"name\":{},\"online\":{},\"mode\":{},\"role\":{},\"bitrate\":{},\"mtu\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"incoming_pr_frequency\":{},\"outgoing_pr_frequency\":{},\"burst_active\":{},\"burst_activated\":{},\"pr_burst_active\":{},\"pr_burst_activated\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{},\"tx_drops\":{}}}",
json_str(&e.name),
e.online,
json_str(&e.mode),
@@ -531,6 +633,12 @@ fn print_local_json(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
e.held_announces,
e.incoming_announce_frequency,
e.outgoing_announce_frequency,
e.incoming_pr_frequency,
e.outgoing_pr_frequency,
e.burst_active,
e.burst_activated,
e.pr_burst_active,
e.pr_burst_activated,
opt_u64_json(e.clients),
opt_f64_json(e.announce_rate_target),
opt_u32_json(e.announce_rate_grace),
@@ -807,85 +915,105 @@ fn unix_now_secs() -> u64 {
}
async fn run_remote(args: Args) -> ExitCode {
run_remote_once(&args).await
let session = match RemoteSession::open(&args).await {
Ok(s) => s,
Err(code) => return code,
};
let exit = session.query_and_print(&args).await;
session.shutdown.trigger();
exit
}
async fn run_remote_once(args: &Args) -> ExitCode {
let remote_hex = args.remote.as_deref().expect("checked in main");
let remote_hash = match hash::parse_dest_hash(remote_hex) {
Ok(h) => h,
Err(e) => {
eprintln!("rnstatus-rs: --remote: {e}");
return ExitCode::from(2);
}
};
/// Remote-management state reused across monitor refreshes: one runtime,
/// one identity, one client — only the /status request repeats.
struct RemoteSession {
remote_hash: [u8; 16],
client: LinkClient,
shutdown: ShutdownSignal,
timeout: Duration,
}
let identity_path = match args.identity.as_ref() {
Some(p) => p.clone(),
None => {
eprintln!("rnstatus-rs: --remote requires --identity <path>.");
return ExitCode::from(2);
}
};
let identity = match rns_identity::identity::Identity::from_file(&identity_path) {
Ok(id) => id,
Err(e) => {
eprintln!(
"rnstatus-rs: could not load identity from {}: {e:?}",
identity_path.display()
);
return ExitCode::from(1);
}
};
impl RemoteSession {
async fn open(args: &Args) -> Result<Self, ExitCode> {
let remote_hex = args.remote.as_deref().expect("checked in main");
let remote_hash = match hash::parse_dest_hash(remote_hex) {
Ok(h) => h,
Err(e) => {
eprintln!("rnstatus-rs: --remote: {e}");
return Err(ExitCode::from(2));
}
};
let shutdown = ShutdownSignal::new();
let foreground = Arc::new(AtomicBool::new(true));
let handle = match init(args.config.as_deref(), None, shutdown.clone(), foreground).await {
Ok(h) => h,
Err(e) => {
eprintln!("rnstatus-rs: failed to initialize Reticulum runtime: {e:?}");
return ExitCode::from(1);
}
};
let identity_path = match args.identity.as_ref() {
Some(p) => p.clone(),
None => {
eprintln!("rnstatus-rs: --remote requires --identity <path>.");
return Err(ExitCode::from(2));
}
};
let identity = match rns_identity::identity::Identity::from_file(&identity_path) {
Ok(id) => id,
Err(e) => {
eprintln!(
"rnstatus-rs: could not load identity from {}: {e:?}",
identity_path.display()
);
return Err(ExitCode::from(1));
}
};
let timeout = Duration::from_secs(args.timeout.unwrap_or(REMOTE_TIMEOUT_SECS));
let shutdown = ShutdownSignal::new();
let foreground = Arc::new(AtomicBool::new(true));
let handle = match init(args.config.as_deref(), None, shutdown.clone(), foreground).await {
Ok(h) => h,
Err(e) => {
eprintln!("rnstatus-rs: failed to initialize Reticulum runtime: {e:?}");
return Err(ExitCode::from(1));
}
};
// Wire format: msgpack 1-tuple `(include_link_count,)`.
let payload = match rmp_serde::to_vec(&(args.link_stats,)) {
Ok(v) => v,
Err(e) => {
eprintln!("rnstatus-rs: msgpack encode failed: {e}");
shutdown.trigger();
return ExitCode::from(1);
}
};
let client = LinkClient::new(handle.transport_tx.clone(), identity);
let response_bytes = match client
.query(
Ok(Self {
remote_hash,
MGMT_APP,
"/status",
payload,
REMOTE_HOPS,
timeout,
)
.await
{
Ok(b) => b,
Err(e) => {
eprintln!("rnstatus-rs: remote query failed: {}", remote_err(&e));
shutdown.trigger();
return match e {
LinkClientError::Timeout(_) => ExitCode::from(124),
_ => ExitCode::from(1),
};
}
};
client: LinkClient::new(handle.transport_tx.clone(), identity),
shutdown,
timeout: Duration::from_secs(args.timeout.unwrap_or(REMOTE_TIMEOUT_SECS)),
})
}
let exit = print_remote_status(&response_bytes, args);
shutdown.trigger();
exit
async fn query_and_print(&self, args: &Args) -> ExitCode {
// Wire format: msgpack 1-tuple `(include_link_count,)`.
let payload = match rmp_serde::to_vec(&(args.link_stats,)) {
Ok(v) => v,
Err(e) => {
eprintln!("rnstatus-rs: msgpack encode failed: {e}");
return ExitCode::from(1);
}
};
let response_bytes = match self
.client
.query(
self.remote_hash,
MGMT_APP,
"/status",
payload,
REMOTE_HOPS,
self.timeout,
)
.await
{
Ok(b) => b,
Err(e) => {
eprintln!("rnstatus-rs: remote query failed: {}", remote_err(&e));
return match e {
LinkClientError::Timeout(_) => ExitCode::from(124),
_ => ExitCode::from(1),
};
}
};
print_remote_status(&response_bytes, args)
}
}
#[derive(Debug, Clone)]
@@ -902,6 +1030,12 @@ struct RemoteInterface {
held_announces: u64,
incoming_announce_frequency: f64,
outgoing_announce_frequency: f64,
incoming_pr_frequency: f64,
outgoing_pr_frequency: f64,
burst_active: bool,
burst_activated: f64,
pr_burst_active: bool,
pr_burst_activated: f64,
clients: Option<u64>,
announce_rate_target: Option<f64>,
announce_rate_grace: Option<u32>,
@@ -922,6 +1056,8 @@ impl RemoteInterface {
}
SortKey::AnnounceRx => self.incoming_announce_frequency,
SortKey::AnnounceTx => self.outgoing_announce_frequency,
SortKey::PathRequestRx => self.incoming_pr_frequency,
SortKey::PathRequestTx => self.outgoing_pr_frequency,
SortKey::Held => self.held_announces as f64,
}
}
@@ -972,7 +1108,14 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
ifs.iter()
.filter_map(|iface| iface.as_map().map(|m| remote_interface_from_map(m)))
.filter(|iface| args.all || visible_by_default(&iface.name))
.filter(|iface| interface_matches_filter(&iface.name, args.filter.as_deref()))
.filter(|iface| {
interface_matches_burst_filter(
&iface.name,
iface.burst_active,
iface.pr_burst_active,
args,
)
})
.collect::<Vec<_>>()
})
.unwrap_or_default();
@@ -994,7 +1137,7 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
print!(",");
}
print!(
"{{\"name\":{},\"online\":{},\"mode\":{},\"bitrate\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{}}}",
"{{\"name\":{},\"online\":{},\"mode\":{},\"bitrate\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"incoming_pr_frequency\":{},\"outgoing_pr_frequency\":{},\"burst_active\":{},\"burst_activated\":{},\"pr_burst_active\":{},\"pr_burst_activated\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{}}}",
json_str(&iface.name),
iface.online,
iface.mode,
@@ -1010,6 +1153,12 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
iface.held_announces,
iface.incoming_announce_frequency,
iface.outgoing_announce_frequency,
iface.incoming_pr_frequency,
iface.outgoing_pr_frequency,
iface.burst_active,
iface.burst_activated,
iface.pr_burst_active,
iface.pr_burst_activated,
opt_u64_json(iface.clients),
opt_f64_json(iface.announce_rate_target),
opt_u32_json(iface.announce_rate_grace),
@@ -1035,7 +1184,7 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
let status = if iface.online { "Up" } else { "Down" };
println!(" {}", iface.name);
println!(" Status : {status}");
println!(" Mode : 0x{:02x}", iface.mode);
println!(" Mode : {}", remote_mode_display_name(iface.mode));
println!(" Bitrate : {}", format::pretty_speed(iface.bitrate));
if let Some(clients) = iface.clients {
println!(" Clients : {clients}");
@@ -1058,6 +1207,7 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
}
if iface.incoming_announce_frequency > 0.0
|| iface.outgoing_announce_frequency > 0.0
|| iface.burst_active
{
print_announce_frequency(
iface.incoming_announce_frequency,
@@ -1066,9 +1216,18 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
iface.announce_rate_target,
iface.announce_rate_penalty,
iface.announce_rate_grace,
burst_status_text(iface.burst_active, iface.burst_activated),
);
}
}
if args.pr_stats {
print_path_request_frequency(
iface.incoming_pr_frequency,
iface.outgoing_pr_frequency,
iface.clients,
burst_status_text(iface.pr_burst_active, iface.pr_burst_activated),
);
}
println!(
" Traffic : {} rx / {} tx",
format::pretty_size(iface.rxb),
@@ -1118,6 +1277,12 @@ fn remote_interface_from_map(m: &[(rmpv::Value, rmpv::Value)]) -> RemoteInterfac
.unwrap_or(0.0),
outgoing_announce_frequency: map_f64_or_u64(m, "outgoing_announce_frequency")
.unwrap_or(0.0),
incoming_pr_frequency: map_f64_or_u64(m, "incoming_pr_frequency").unwrap_or(0.0),
outgoing_pr_frequency: map_f64_or_u64(m, "outgoing_pr_frequency").unwrap_or(0.0),
burst_active: map_bool(m, "burst_active").unwrap_or(false),
burst_activated: map_f64_or_u64(m, "burst_activated").unwrap_or(0.0),
pr_burst_active: map_bool(m, "pr_burst_active").unwrap_or(false),
pr_burst_activated: map_f64_or_u64(m, "pr_burst_activated").unwrap_or(0.0),
clients: map_u64(m, "clients"),
announce_rate_target: map_f64_or_u64(m, "announce_rate_target"),
announce_rate_grace: map_u64(m, "announce_rate_grace")
@@ -1157,6 +1322,7 @@ fn print_announce_frequency(
target: Option<f64>,
penalty: Option<f64>,
grace: Option<u32>,
burst_text: String,
) {
let outgoing_text = format!("{}↑", format::pretty_frequency(outgoing));
let incoming_text = format!("{}↓", format::pretty_frequency(incoming));
@@ -1166,7 +1332,38 @@ fn print_announce_frequency(
.unwrap_or_default();
let limits = announce_rate_limits_text(target, penalty, grace);
println!(" Announces: {outgoing_text}{per_client}");
println!(" {incoming_text} {limits}");
println!(" {incoming_text} {limits}{burst_text}");
}
fn print_path_request_frequency(
incoming: f64,
outgoing: f64,
clients: Option<u64>,
burst_text: String,
) {
let outgoing_text = format!("{}↑", format::pretty_frequency(outgoing));
let incoming_text = format!("{}↓", format::pretty_frequency(incoming));
let per_client = clients
.filter(|clients| *clients > 0)
.map(|clients| format!(" {}/c", format::pretty_frequency(outgoing / clients as f64)))
.unwrap_or_default();
println!(" Path Rqs.: {outgoing_text}{per_client}");
println!(" {incoming_text} {burst_text}");
}
fn burst_status_text(active: bool, activated: f64) -> String {
if !active || activated <= 0.0 {
return String::new();
}
let age = (unix_now() - activated).max(0.0);
format!(" burst for {}", format::pretty_time(age))
}
fn unix_now() -> f64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64()
}
fn announce_rate_limits_text(
@@ -1246,6 +1443,183 @@ fn json_str(s: &str) -> String {
mod tests {
use super::*;
fn test_args() -> Args {
Args {
all: true,
announce_stats: false,
pr_stats: false,
link_stats: false,
burst: false,
totals: false,
sort: None,
reverse: false,
json: false,
config: None,
remote: None,
identity: None,
timeout: None,
discovered: false,
discovered_details: false,
monitor: false,
monitor_interval: 1.0,
version: false,
verbose: 0,
quiet: 0,
filter: None,
}
}
fn local_entry(
name: &str,
burst_active: bool,
pr_burst_active: bool,
) -> rpc::InterfaceStatEntry {
rpc::InterfaceStatEntry {
id: 1,
name: name.to_string(),
rx_bytes: 0,
tx_bytes: 0,
rx_rate: 0,
tx_rate: 0,
online: true,
bitrate: 1,
mtu: 500,
mode: "Full".to_string(),
role: "normal".to_string(),
announce_queue: None,
held_announces: 0,
incoming_announce_frequency: 0.0,
outgoing_announce_frequency: 0.0,
incoming_pr_frequency: 2.0,
outgoing_pr_frequency: 3.0,
burst_active,
burst_activated: if burst_active { 1_700_000_000.0 } else { 0.0 },
pr_burst_active,
pr_burst_activated: if pr_burst_active {
1_700_000_001.0
} else {
0.0
},
clients: None,
announce_rate_target: None,
announce_rate_grace: None,
announce_rate_penalty: None,
announce_cap: 0.0,
ifac_size: 0,
tx_drops: 0,
}
}
#[test]
fn sort_key_accepts_path_request_rates() {
assert_eq!(
parse_sort_key(Some("prx")).unwrap(),
Some(SortKey::PathRequestRx)
);
assert_eq!(
parse_sort_key(Some("ptx")).unwrap(),
Some(SortKey::PathRequestTx)
);
let entry = local_entry("SortIf", false, false);
assert_eq!(local_stat_sort_value(&entry, SortKey::PathRequestRx), 2.0);
assert_eq!(local_stat_sort_value(&entry, SortKey::PathRequestTx), 3.0);
}
#[test]
fn pr_and_burst_flags_parse() {
let args = Args::try_parse_from(["rnstatus-rs", "-P", "-B"]).unwrap();
assert!(args.pr_stats);
assert!(args.burst);
}
#[test]
fn burst_filter_includes_active_bursts_or_name_matches() {
let stats = vec![
local_entry("InactiveIf", false, false),
local_entry("AnnounceBurstIf", true, false),
local_entry("PrBurstIf", false, true),
local_entry("ManualMatchIf", false, false),
];
let mut args = test_args();
args.burst = true;
args.filter = Some("manual".to_string());
let names: Vec<_> = filtered_local_stats(&stats, &args)
.into_iter()
.map(|entry| entry.name.as_str())
.collect();
assert_eq!(names, vec!["AnnounceBurstIf", "PrBurstIf", "ManualMatchIf"]);
}
#[test]
fn remote_status_parser_defaults_missing_125_fields() {
let iface = remote_interface_from_map(&[
(rmpv::Value::from("name"), rmpv::Value::from("LegacyIf")),
(rmpv::Value::from("status"), rmpv::Value::from(true)),
]);
assert_eq!(iface.incoming_pr_frequency, 0.0);
assert_eq!(iface.outgoing_pr_frequency, 0.0);
assert!(!iface.burst_active);
assert_eq!(iface.burst_activated, 0.0);
assert!(!iface.pr_burst_active);
assert_eq!(iface.pr_burst_activated, 0.0);
}
#[test]
fn mode_display_names_match_python_138_table() {
assert_eq!(mode_display_name("Full"), "Full");
assert_eq!(mode_display_name("PointToPoint"), "Point-to-Point");
assert_eq!(mode_display_name("AccessPoint"), "Access Point");
assert_eq!(mode_display_name("Roaming"), "Roaming");
assert_eq!(mode_display_name("Boundary"), "Boundary");
assert_eq!(mode_display_name("Gateway"), "Gateway");
assert_eq!(mode_display_name("Internal"), "Internal");
// Python rnstatus.py:427 falls back to "Full" for unknown modes.
assert_eq!(mode_display_name("Bogus"), "Full");
assert_eq!(remote_mode_display_name(0x01), "Full");
assert_eq!(remote_mode_display_name(0x02), "Point-to-Point");
assert_eq!(remote_mode_display_name(0x03), "Access Point");
assert_eq!(remote_mode_display_name(0x04), "Roaming");
assert_eq!(remote_mode_display_name(0x05), "Boundary");
assert_eq!(remote_mode_display_name(0x06), "Gateway");
assert_eq!(remote_mode_display_name(0x07), "Internal");
assert_eq!(remote_mode_display_name(0x08), "Full");
}
#[test]
fn monitor_sleep_compensates_render_time_with_floor() {
// Python rnstatus.py:742-744: max(interval - elapsed, 0.2).
assert_eq!(
monitor_sleep(1.0, Duration::from_millis(250)),
Duration::from_secs_f64(0.75)
);
assert_eq!(
monitor_sleep(1.0, Duration::from_secs(5)),
Duration::from_secs_f64(0.2)
);
assert_eq!(
monitor_sleep(0.05, Duration::ZERO),
Duration::from_secs_f64(0.2)
);
}
#[test]
fn monitor_interval_must_be_finite_positive() {
let mut args = test_args();
args.monitor_interval = 0.0;
assert!(validate_args(&args).is_err());
args.monitor_interval = f64::INFINITY;
assert!(validate_args(&args).is_err());
args.monitor_interval = f64::NAN;
assert!(validate_args(&args).is_err());
args.monitor_interval = 0.5;
assert!(validate_args(&args).is_ok());
}
#[test]
fn local_rpc_auth_failure_explains_config_mismatch_and_port_owner() {
let endpoint = SharedInstanceRpcEndpoint::Tcp(37429);
+29 -37
View File
@@ -1,45 +1,35 @@
//! Python ref: `RNS/__init__.py` (`prettyspeed`, `prettysize`, `prettytime`).
pub fn pretty_size(num: u64) -> String {
if num == 0 {
return "0 B".to_string();
}
let units = ["B", "KB", "MB", "GB", "TB"];
let units = ["", "K", "M", "G", "T", "P", "E", "Z"];
let mut val = num as f64;
for unit in &units {
if val < 1024.0 {
return if val < 10.0 {
format!("{val:.2} {unit}")
} else if val < 100.0 {
format!("{val:.1} {unit}")
if val.abs() < 1000.0 {
return if unit.is_empty() {
format!("{val:.0} B")
} else {
format!("{val:.0} {unit}")
};
}
val /= 1024.0;
}
format!("{val:.1} PB")
}
pub fn pretty_speed(bps: u64) -> String {
if bps == 0 {
return "0 bps".to_string();
}
let units = ["bps", "Kbps", "Mbps", "Gbps"];
let mut val = bps as f64;
for unit in &units {
if val < 1000.0 {
return if val < 10.0 {
format!("{val:.2} {unit}")
} else if val < 100.0 {
format!("{val:.1} {unit}")
} else {
format!("{val:.0} {unit}")
format!("{val:.2} {unit}B")
};
}
val /= 1000.0;
}
format!("{val:.1} Tbps")
format!("{val:.2}YB")
}
pub fn pretty_speed(bps: u64) -> String {
let units = ["", "K", "M", "G", "T", "P", "E", "Z"];
let mut val = bps as f64;
for unit in &units {
if val.abs() < 1000.0 {
return if unit.is_empty() {
format!("{val:.0} bps")
} else {
format!("{val:.2} {unit}bps")
};
}
val /= 1000.0;
}
format!("{val:.2}Ybps")
}
pub fn pretty_time(seconds: f64) -> String {
@@ -89,16 +79,18 @@ mod tests {
fn test_pretty_size() {
assert_eq!(pretty_size(0), "0 B");
assert_eq!(pretty_size(100), "100 B");
assert_eq!(pretty_size(1024), "1.00 KB");
assert_eq!(pretty_size(1536), "1.50 KB");
assert_eq!(pretty_size(1048576), "1.00 MB");
assert_eq!(pretty_size(1073741824), "1.00 GB");
assert_eq!(pretty_size(999), "999 B");
assert_eq!(pretty_size(1000), "1.00 KB");
assert_eq!(pretty_size(1024), "1.02 KB");
assert_eq!(pretty_size(1536), "1.54 KB");
assert_eq!(pretty_size(1048576), "1.05 MB");
assert_eq!(pretty_size(1073741824), "1.07 GB");
}
#[test]
fn test_pretty_speed() {
assert_eq!(pretty_speed(0), "0 bps");
assert_eq!(pretty_speed(115200), "115 Kbps");
assert_eq!(pretty_speed(115200), "115.20 Kbps");
assert_eq!(pretty_speed(1000000), "1.00 Mbps");
assert_eq!(pretty_speed(1000000000), "1.00 Gbps");
}
+33
View File
@@ -2,3 +2,36 @@
pub mod format;
pub mod hash;
/// rsReticulum package version printed by CLI `--version` output.
pub const RS_RETICULUM_VERSION: &str = env!("CARGO_PKG_VERSION");
/// Python Reticulum version these tools track for CLI/protocol parity.
pub const RETICULUM_COMPAT_VERSION: &str = "1.3.8";
/// Python 1.3.2 `[logging] logtimestamps` (Reticulum.py:459-461,
/// RNS/__init__.py:85 default True): whether log lines carry a timestamp
/// prefix. Read pre-init from the config file, like the loglevel.
pub fn config_log_timestamps(config_dir: &std::path::Path) -> bool {
rns_runtime::config::Config::from_file(&config_dir.join("config"))
.ok()
.and_then(|config| config.section("logging")?.get_bool("logtimestamps"))
.unwrap_or(true)
}
/// Shared tracing-subscriber setup for the CLI binaries; omits the timestamp
/// field when `logtimestamps` is disabled (Python RNS.log parity).
pub fn init_tracing<W>(level: tracing::Level, timestamps: bool, ansi: bool, writer: W)
where
W: for<'a> tracing_subscriber::fmt::MakeWriter<'a> + Send + Sync + 'static,
{
let builder = tracing_subscriber::fmt()
.with_max_level(level)
.with_ansi(ansi)
.with_writer(writer);
if timestamps {
let _ = builder.try_init();
} else {
let _ = builder.without_time().try_init();
}
}
@@ -0,0 +1,177 @@
#[cfg(unix)]
use std::fs;
#[cfg(unix)]
use std::path::{Path, PathBuf};
#[cfg(unix)]
use std::process::{Child, Command, Stdio};
#[cfg(unix)]
use std::thread;
#[cfg(unix)]
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
#[cfg(unix)]
struct TempDir {
path: PathBuf,
}
#[cfg(unix)]
impl TempDir {
fn new(prefix: &str) -> Self {
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock before unix epoch")
.as_nanos();
let path = std::env::temp_dir().join(format!(
"rsreticulum-{prefix}-{}-{nonce}",
std::process::id()
));
fs::create_dir_all(&path).expect("create tempdir");
Self { path }
}
fn path(&self) -> &Path {
&self.path
}
}
#[cfg(unix)]
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
#[cfg(unix)]
fn write_config(tmp: &TempDir) {
fs::write(
tmp.path().join("config"),
"[reticulum]\nshare_instance = No\nenable_transport = No\n\n[interfaces]\n",
)
.expect("write config");
}
#[cfg(unix)]
fn wait_until_running(child: &mut Child, settle: Duration) -> bool {
let deadline = Instant::now() + settle;
while Instant::now() < deadline {
if child.try_wait().expect("poll child").is_some() {
return false;
}
thread::sleep(Duration::from_millis(50));
}
true
}
/// Sends SIGINT after a settle period and asserts a clean exit. Retries once
/// with a longer settle if the child died from the raw signal (exit by signal
/// 2): under full-workspace load the child can still be booting when the
/// first SIGINT lands, before its handler is registered. A real handler
/// regression fails both attempts.
#[cfg(unix)]
fn assert_sigint_exits(spawn: impl Fn() -> Child, name: &str) {
use std::os::unix::process::ExitStatusExt;
let settles = [Duration::from_secs(3), Duration::from_secs(8)];
let last_attempt = settles.len() - 1;
for (attempt, settle) in settles.into_iter().enumerate() {
let mut child = spawn();
if !wait_until_running(&mut child, settle) {
let output = child.wait_with_output().expect("collect child output");
panic!(
"{name} exited before SIGINT\nstatus: {}\nstdout:\n{}\nstderr:\n{}",
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
let status = Command::new("kill")
.arg("-INT")
.arg(child.id().to_string())
.status()
.expect("send SIGINT");
assert!(status.success(), "kill -INT failed with {status}");
let deadline = Instant::now() + Duration::from_secs(10);
let exit_status = loop {
if let Some(status) = child.try_wait().expect("poll child after SIGINT") {
break Some(status);
}
if Instant::now() >= deadline {
break None;
}
thread::sleep(Duration::from_millis(50));
};
match exit_status {
Some(status) if status.success() => return,
Some(status) if attempt < last_attempt && status.signal() == Some(2) => {
let _ = child.wait_with_output();
continue;
}
Some(status) => {
let output = child.wait_with_output().expect("collect child output");
panic!(
"{name} exited unsuccessfully after SIGINT: {status}\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
None => {
let _ = child.kill();
let output = child
.wait_with_output()
.expect("collect killed child output");
panic!(
"{name} did not exit after SIGINT\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
}
}
unreachable!("attempt loop either returns or panics");
}
#[cfg(unix)]
#[test]
fn rncp_listener_exits_on_sigint() {
let tmp = TempDir::new("rncp-sigint");
write_config(&tmp);
assert_sigint_exits(
|| {
Command::new(env!("CARGO_BIN_EXE_rncp-rs"))
.arg("--config")
.arg(tmp.path())
.arg("-l")
.arg("-n")
.arg("-S")
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn rncp-rs listener")
},
"rncp-rs",
);
}
#[cfg(unix)]
#[test]
fn rnsh_listener_exits_on_sigint() {
let tmp = TempDir::new("rnsh-sigint");
write_config(&tmp);
assert_sigint_exits(
|| {
Command::new(env!("CARGO_BIN_EXE_rnsh-rs"))
.arg("--config")
.arg(tmp.path())
.arg("-l")
.arg("-n")
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn rnsh-rs listener")
},
"rnsh-rs",
);
}
+6 -1
View File
@@ -135,7 +135,12 @@ fn rnid_flag_conflicts_are_rejected() {
let tmp = TempDir::new("rnid-flag-conflicts");
let output = rnid(&tmp, ["-b", "-B"]);
assert_failure(&output, Some(1), "-b and -B", "base64/base32 conflict");
assert_failure(
&output,
Some(1),
"-b, -B, --hex and --base256",
"base64/base32 conflict",
);
let generated = tmp.join("identity");
let output = rnid(
@@ -0,0 +1,480 @@
use std::ffi::OsStr;
use std::fs;
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Output, Stdio};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use rns_identity::destination::Destination;
use rns_identity::identity::Identity;
const PROBE_APP: &str = "rnstransport.probe";
const COMMAND_TIMEOUT_SECS: &str = "4";
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(prefix: &str) -> Self {
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock before unix epoch")
.as_nanos();
let path = std::env::temp_dir().join(format!(
"rsreticulum-{prefix}-{}-{nonce}",
std::process::id()
));
fs::create_dir_all(&path).expect("create tempdir");
Self { path }
}
fn path(&self) -> &Path {
&self.path
}
fn join(&self, path: impl AsRef<Path>) -> PathBuf {
self.path.join(path)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
struct ChildGuard {
label: &'static str,
child: Option<Child>,
}
impl ChildGuard {
fn spawn<I, S>(label: &'static str, program: &str, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let child = Command::new(program)
.args(args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn child process");
Self {
label,
child: Some(child),
}
}
fn try_wait(&mut self) -> Option<std::process::ExitStatus> {
self.child
.as_mut()
.and_then(|child| child.try_wait().expect("poll child status"))
}
fn terminate_and_output_text(&mut self) -> (String, String) {
let Some(mut child) = self.child.take() else {
return ("<not started>\n".to_string(), String::new());
};
let _ = child.kill();
let output = child.wait_with_output().expect("collect child output");
output_text(&output)
}
}
impl Drop for ChildGuard {
fn drop(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}
fn free_tcp_ports(count: usize) -> Vec<u16> {
let listeners: Vec<TcpListener> = (0..count)
.map(|_| TcpListener::bind("127.0.0.1:0").expect("bind free tcp port"))
.collect();
listeners
.iter()
.map(|listener| listener.local_addr().expect("local addr").port())
.collect()
}
fn write_responder_config(tmp: &TempDir, shared_port: u16, control_port: u16, link_port: u16) {
let config = format!(
"[reticulum]\n\
share_instance = Yes\n\
shared_instance_type = tcp\n\
shared_instance_port = {shared_port}\n\
instance_control_port = {control_port}\n\
rpc_key = 5151515151515151515151515151515151515151515151515151515151515151\n\
enable_transport = No\n\
respond_to_probes = Yes\n\
\n\
[logging]\n\
loglevel = 1\n\
\n\
[interfaces]\n\
\n\
[[Matrix TCP Server]]\n\
type = TCPServerInterface\n\
enabled = Yes\n\
listen_ip = 127.0.0.1\n\
listen_port = {link_port}\n"
);
fs::write(tmp.join("config"), config).expect("write responder config");
}
fn write_origin_config(tmp: &TempDir, shared_port: u16, control_port: u16, link_port: u16) {
let config = format!(
"[reticulum]\n\
share_instance = Yes\n\
shared_instance_type = tcp\n\
shared_instance_port = {shared_port}\n\
instance_control_port = {control_port}\n\
rpc_key = 5252525252525252525252525252525252525252525252525252525252525252\n\
enable_transport = No\n\
\n\
[logging]\n\
loglevel = 1\n\
\n\
[interfaces]\n\
\n\
[[Matrix TCP Client]]\n\
type = TCPClientInterface\n\
enabled = Yes\n\
target_host = 127.0.0.1\n\
target_port = {link_port}\n"
);
fs::write(tmp.join("config"), config).expect("write origin config");
}
fn output_text(output: &Output) -> (String, String) {
(
String::from_utf8_lossy(&output.stdout).into_owned(),
String::from_utf8_lossy(&output.stderr).into_owned(),
)
}
fn rnstatus_json(tmp: &TempDir) -> Output {
Command::new(env!("CARGO_BIN_EXE_rnstatus-rs"))
.arg("--config")
.arg(tmp.path())
.arg("--json")
.arg("--all")
.arg("--timeout")
.arg("1")
.output()
.expect("run rnstatus-rs")
}
fn poll_shared_server(
daemon: &mut ChildGuard,
tmp: &TempDir,
deadline_after: Duration,
) -> Result<(), String> {
let deadline = Instant::now() + deadline_after;
let mut last_status = None;
let mut last_stdout = String::new();
let mut last_stderr = String::new();
while Instant::now() < deadline {
if let Some(status) = daemon.try_wait() {
return Err(format!(
"{} exited before shared server was ready: {status}",
daemon.label
));
}
let output = rnstatus_json(tmp);
last_status = output.status.code();
(last_stdout, last_stderr) = output_text(&output);
if output.status.success() {
let value: serde_json::Value =
serde_json::from_slice(&output.stdout).expect("rnstatus-rs JSON output");
let ready = value
.get("interfaces")
.and_then(|v| v.as_array())
.is_some_and(|interfaces| {
interfaces.iter().any(|entry| {
entry.get("role").and_then(|v| v.as_str()) == Some("shared_server")
})
});
if ready {
return Ok(());
}
}
thread::sleep(Duration::from_millis(100));
}
Err(format!(
"rnstatus-rs did not report {} shared server before the deadline\n\
last rnstatus status: {last_status:?}\n\
--- last rnstatus stdout ---\n{last_stdout}\n\
--- last rnstatus stderr ---\n{last_stderr}",
daemon.label
))
}
fn read_probe_hash(responder: &mut ChildGuard, tmp: &TempDir) -> Result<[u8; 16], String> {
let path = tmp.join("storage").join("probe_identity");
let deadline = Instant::now() + Duration::from_secs(5);
let mut last_error = String::new();
while Instant::now() < deadline {
if let Some(status) = responder.try_wait() {
return Err(format!(
"{} exited before probe identity was ready: {status}",
responder.label
));
}
match Identity::from_file(&path) {
Ok(identity) => {
return Ok(Destination::hash_from_name_and_identity(
PROBE_APP,
Some(&identity.hash),
));
}
Err(e) => last_error = e.to_string(),
}
thread::sleep(Duration::from_millis(100));
}
Err(format!(
"probe identity was not readable at {}\nlast error: {last_error}",
path.display()
))
}
fn run_rnpath(origin: &TempDir, probe_hash_hex: &str) -> Output {
Command::new(env!("CARGO_BIN_EXE_rnpath-rs"))
.arg("--config")
.arg(origin.path())
.arg("-w")
.arg(COMMAND_TIMEOUT_SECS)
.arg(probe_hash_hex)
.output()
.expect("run rnpath-rs")
}
fn run_rnprobe(origin: &TempDir, probe_hash_hex: &str) -> Output {
Command::new(env!("CARGO_BIN_EXE_rnprobe-rs"))
.arg("--config")
.arg(origin.path())
.arg("--json")
.arg("-t")
.arg(COMMAND_TIMEOUT_SECS)
.arg(PROBE_APP)
.arg(probe_hash_hex)
.output()
.expect("run rnprobe-rs")
}
fn poll_command_success<F>(
label: &str,
deadline_after: Duration,
mut run: F,
) -> Result<Output, String>
where
F: FnMut() -> Output,
{
let deadline = Instant::now() + deadline_after;
let mut last_output = None;
while Instant::now() < deadline {
let output = run();
if output.status.success() {
return Ok(output);
}
last_output = Some(output);
thread::sleep(Duration::from_millis(200));
}
let Some(output) = last_output else {
return Err(format!("{label} was not run"));
};
let (stdout, stderr) = output_text(&output);
Err(format!(
"{label} did not succeed before the deadline\n\
last status: {}\n\
--- last stdout ---\n{stdout}\n\
--- last stderr ---\n{stderr}",
output.status
))
}
fn panic_with_daemon_outputs(
message: String,
responder: &mut ChildGuard,
path_origin: &mut ChildGuard,
cold_origin: &mut ChildGuard,
) -> ! {
let (responder_stdout, responder_stderr) = responder.terminate_and_output_text();
let (path_stdout, path_stderr) = path_origin.terminate_and_output_text();
let (cold_stdout, cold_stderr) = cold_origin.terminate_and_output_text();
panic!(
"{message}\n\
--- responder stdout ---\n{responder_stdout}\n\
--- responder stderr ---\n{responder_stderr}\n\
--- path origin stdout ---\n{path_stdout}\n\
--- path origin stderr ---\n{path_stderr}\n\
--- cold origin stdout ---\n{cold_stdout}\n\
--- cold origin stderr ---\n{cold_stderr}"
);
}
#[test]
fn rust_probe_destination_supports_active_path_and_probe_matrix() {
let responder_tmp = TempDir::new("rnprobe-rnpath-responder");
let path_origin_tmp = TempDir::new("rnprobe-rnpath-path-origin");
let cold_origin_tmp = TempDir::new("rnprobe-rnpath-cold-origin");
let ports = free_tcp_ports(7);
let link_port = ports[0];
write_responder_config(&responder_tmp, ports[1], ports[2], link_port);
write_origin_config(&path_origin_tmp, ports[3], ports[4], link_port);
write_origin_config(&cold_origin_tmp, ports[5], ports[6], link_port);
let mut responder = ChildGuard::spawn(
"responder rnsd-rs",
env!("CARGO_BIN_EXE_rnsd-rs"),
["--config".as_ref(), responder_tmp.path().as_os_str()],
);
if let Err(message) = poll_shared_server(&mut responder, &responder_tmp, Duration::from_secs(5))
{
let mut placeholder = ChildGuard {
label: "path origin rnsd-rs",
child: None,
};
let mut cold_placeholder = ChildGuard {
label: "cold origin rnsd-rs",
child: None,
};
panic_with_daemon_outputs(
message,
&mut responder,
&mut placeholder,
&mut cold_placeholder,
);
}
let probe_hash = match read_probe_hash(&mut responder, &responder_tmp) {
Ok(hash) => hash,
Err(message) => {
let mut placeholder = ChildGuard {
label: "path origin rnsd-rs",
child: None,
};
let mut cold_placeholder = ChildGuard {
label: "cold origin rnsd-rs",
child: None,
};
panic_with_daemon_outputs(
message,
&mut responder,
&mut placeholder,
&mut cold_placeholder,
);
}
};
let probe_hash_hex = hex::encode(probe_hash);
let mut path_origin = ChildGuard::spawn(
"path origin rnsd-rs",
env!("CARGO_BIN_EXE_rnsd-rs"),
["--config".as_ref(), path_origin_tmp.path().as_os_str()],
);
if let Err(message) =
poll_shared_server(&mut path_origin, &path_origin_tmp, Duration::from_secs(5))
{
let mut cold_placeholder = ChildGuard {
label: "cold origin rnsd-rs",
child: None,
};
panic_with_daemon_outputs(
message,
&mut responder,
&mut path_origin,
&mut cold_placeholder,
);
}
let mut cold_origin = ChildGuard::spawn(
"cold origin rnsd-rs",
env!("CARGO_BIN_EXE_rnsd-rs"),
["--config".as_ref(), cold_origin_tmp.path().as_os_str()],
);
if let Err(message) =
poll_shared_server(&mut cold_origin, &cold_origin_tmp, Duration::from_secs(5))
{
panic_with_daemon_outputs(message, &mut responder, &mut path_origin, &mut cold_origin);
}
let rnpath = poll_command_success(
"rnpath-rs active path request",
Duration::from_secs(16),
|| run_rnpath(&path_origin_tmp, &probe_hash_hex),
);
let rnpath = match rnpath {
Ok(output) => output,
Err(message) => {
panic_with_daemon_outputs(message, &mut responder, &mut path_origin, &mut cold_origin)
}
};
let (rnpath_stdout, _rnpath_stderr) = output_text(&rnpath);
assert!(
rnpath_stdout.contains(&format!("Destination: {probe_hash_hex}")),
"rnpath-rs output did not include the requested destination\n{rnpath_stdout}"
);
assert!(
!rnpath_stdout.contains("(no known path)"),
"rnpath-rs reported no known path after active request\n{rnpath_stdout}"
);
let known_path_probe = poll_command_success(
"rnprobe-rs with rnpath-populated path",
Duration::from_secs(16),
|| run_rnprobe(&path_origin_tmp, &probe_hash_hex),
);
let known_path_probe = match known_path_probe {
Ok(output) => output,
Err(message) => {
panic_with_daemon_outputs(message, &mut responder, &mut path_origin, &mut cold_origin)
}
};
assert_probe_json_ok(&known_path_probe, &probe_hash_hex);
let cold_probe = poll_command_success(
"rnprobe-rs cold active-path probe",
Duration::from_secs(16),
|| run_rnprobe(&cold_origin_tmp, &probe_hash_hex),
);
let cold_probe = match cold_probe {
Ok(output) => output,
Err(message) => {
panic_with_daemon_outputs(message, &mut responder, &mut path_origin, &mut cold_origin)
}
};
assert_probe_json_ok(&cold_probe, &probe_hash_hex);
}
fn assert_probe_json_ok(output: &Output, expected_hash: &str) {
let (stdout, stderr) = output_text(output);
let value: serde_json::Value =
serde_json::from_str(stdout.trim()).expect("rnprobe-rs JSON output");
assert_eq!(
value.get("status").and_then(|v| v.as_str()),
Some("ok"),
"rnprobe-rs did not report ok\nstdout:\n{stdout}\nstderr:\n{stderr}"
);
assert_eq!(
value.get("destination").and_then(|v| v.as_str()),
Some(expected_hash),
"rnprobe-rs returned the wrong destination\nstdout:\n{stdout}\nstderr:\n{stderr}"
);
assert!(
value.get("rtt_ms").and_then(|v| v.as_f64()).is_some(),
"rnprobe-rs JSON did not include an RTT\nstdout:\n{stdout}\nstderr:\n{stderr}"
);
}
+307
View File
@@ -0,0 +1,307 @@
use std::ffi::OsStr;
use std::fs;
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Output, Stdio};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(prefix: &str) -> Self {
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock before unix epoch")
.as_nanos();
let path = std::env::temp_dir().join(format!(
"rsreticulum-{prefix}-{}-{nonce}",
std::process::id()
));
fs::create_dir_all(&path).expect("create tempdir");
Self { path }
}
fn path(&self) -> &Path {
&self.path
}
fn join(&self, path: impl AsRef<Path>) -> PathBuf {
self.path.join(path)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
struct ChildGuard {
child: Option<Child>,
}
impl ChildGuard {
fn spawn<I, S>(program: &str, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let child = Command::new(program)
.args(args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn child process");
Self { child: Some(child) }
}
fn try_wait(&mut self) -> Option<std::process::ExitStatus> {
self.child
.as_mut()
.and_then(|child| child.try_wait().expect("poll child status"))
}
fn terminate_and_output(mut self) -> Output {
let mut child = self.child.take().expect("child already taken");
let _ = child.kill();
child.wait_with_output().expect("collect child output")
}
}
impl Drop for ChildGuard {
fn drop(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}
fn free_tcp_port_pair() -> (u16, u16) {
let first = TcpListener::bind("127.0.0.1:0").expect("bind first free tcp port");
let second = TcpListener::bind("127.0.0.1:0").expect("bind second free tcp port");
let first_port = first.local_addr().expect("first local addr").port();
let second_port = second.local_addr().expect("second local addr").port();
(first_port, second_port)
}
fn write_stale_python_destination_table(storage_dir: &Path, entries: usize) {
fs::create_dir_all(storage_dir).expect("create storage dir");
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock before unix epoch")
.as_secs_f64();
let mut table = rns_transport::path_table::PathTable::new();
for i in 0..entries {
let mut dest = [0u8; 16];
dest[..8].copy_from_slice(&(i as u64).to_be_bytes());
dest[8..].copy_from_slice(&(!i as u64).to_be_bytes());
let mut packet_hash = [0u8; 32];
packet_hash[..8].copy_from_slice(&(i as u64).to_be_bytes());
packet_hash[8..16].copy_from_slice(&(entries as u64).to_be_bytes());
packet_hash[16..24].copy_from_slice(&(0xA5A5_A5A5_A5A5_A5A5u64).to_be_bytes());
packet_hash[24..].copy_from_slice(&(!i as u64).to_be_bytes());
let mut entry = rns_transport::path_table::PathEntry::new(
None,
1,
7,
rns_transport::constants::InterfaceMode::Gateway,
);
entry.timestamp = now;
entry.expires = now + 3600.0;
entry.packet_hash = Some(packet_hash);
table.insert(dest, entry);
}
let mut names = std::collections::HashMap::new();
names.insert(7u64, "Border_TCP".to_string());
rns_transport::persistence::save_python_destination_table(
&table,
&names,
&storage_dir.join("destination_table"),
)
.expect("write Python destination_table");
}
fn output_text(output: &Output) -> (String, String) {
(
String::from_utf8_lossy(&output.stdout).into_owned(),
String::from_utf8_lossy(&output.stderr).into_owned(),
)
}
fn rnstatus_json(tmp: &TempDir, timeout_secs: &str) -> Output {
Command::new(env!("CARGO_BIN_EXE_rnstatus-rs"))
.arg("--config")
.arg(tmp.path())
.arg("--json")
.arg("--all")
.arg("--timeout")
.arg(timeout_secs)
.output()
.expect("run rnstatus-rs")
}
fn poll_rnstatus_until<F>(
daemon: &mut ChildGuard,
tmp: &TempDir,
deadline_after: Duration,
timeout_secs: &str,
predicate: F,
) -> Result<(), String>
where
F: Fn(&[serde_json::Value]) -> bool,
{
let deadline = Instant::now() + deadline_after;
let mut last_status = None;
let mut last_stdout = String::new();
let mut last_stderr = String::new();
while Instant::now() < deadline {
if let Some(status) = daemon.try_wait() {
return Err(format!(
"rnsd-rs exited before rnstatus-rs succeeded: {status}"
));
}
let output = rnstatus_json(tmp, timeout_secs);
last_status = output.status.code();
(last_stdout, last_stderr) = output_text(&output);
if output.status.success() {
let value: serde_json::Value =
serde_json::from_slice(&output.stdout).expect("rnstatus-rs JSON output");
let interfaces = value
.get("interfaces")
.and_then(|v| v.as_array())
.expect("interfaces array");
if predicate(interfaces) {
return Ok(());
}
}
thread::sleep(Duration::from_millis(100));
}
Err(format!(
"rnstatus-rs did not report the expected interface before the deadline\n\
last rnstatus status: {last_status:?}\n\
--- last rnstatus stdout ---\n{last_stdout}\n\
--- last rnstatus stderr ---\n{last_stderr}"
))
}
fn panic_with_daemon_output(message: String, daemon: ChildGuard) -> ! {
let daemon_output = daemon.terminate_and_output();
let (daemon_stdout, daemon_stderr) = output_text(&daemon_output);
panic!(
"{message}\n\
--- daemon stdout ---\n{daemon_stdout}\n\
--- daemon stderr ---\n{daemon_stderr}"
);
}
#[test]
fn rnsd_rnstatus_cli_survives_stale_python_destination_table() {
let tmp = TempDir::new("rnsd-rnstatus-stale-python-table");
let (shared_port, control_port) = free_tcp_port_pair();
let rpc_key_hex = "5353535353535353535353535353535353535353535353535353535353535353";
let config = format!(
"[reticulum]\n\
share_instance = Yes\n\
shared_instance_type = tcp\n\
shared_instance_port = {shared_port}\n\
instance_control_port = {control_port}\n\
rpc_key = {rpc_key_hex}\n\
enable_transport = Yes\n\
\n\
[logging]\n\
loglevel = 1\n\
\n\
[interfaces]\n"
);
fs::write(tmp.join("config"), config).expect("write config");
write_stale_python_destination_table(&tmp.join("storage"), 512);
let mut daemon = ChildGuard::spawn(
env!("CARGO_BIN_EXE_rnsd-rs"),
["--config".as_ref(), tmp.path().as_os_str()],
);
if let Err(message) = poll_rnstatus_until(
&mut daemon,
&tmp,
Duration::from_secs(5),
"1",
|interfaces| {
interfaces
.iter()
.any(|entry| entry.get("role").and_then(|v| v.as_str()) == Some("shared_server"))
},
) {
panic_with_daemon_output(message, daemon);
}
}
#[test]
#[ignore = "requires network access to a public Reticulum TCP peer"]
fn rnsd_rnstatus_cli_public_tcp_testnet_smoke() {
let tmp = TempDir::new("rnsd-rnstatus-public-tcp-testnet");
let (shared_port, control_port) = free_tcp_port_pair();
let host = std::env::var("RSRETICULUM_LIVE_TCP_HOST")
.unwrap_or_else(|_| "rns.ratspeak.org".to_string());
let port = std::env::var("RSRETICULUM_LIVE_TCP_PORT")
.ok()
.and_then(|value| value.parse::<u16>().ok())
.unwrap_or(4242);
let rpc_key_hex = "5353535353535353535353535353535353535353535353535353535353535353";
let config = format!(
"[reticulum]\n\
share_instance = Yes\n\
shared_instance_type = tcp\n\
shared_instance_port = {shared_port}\n\
instance_control_port = {control_port}\n\
rpc_key = {rpc_key_hex}\n\
enable_transport = No\n\
\n\
[logging]\n\
loglevel = 1\n\
\n\
[interfaces]\n\
\n\
[[Public TCP]]\n\
type = TCPClientInterface\n\
enabled = Yes\n\
target_host = {host}\n\
target_port = {port}\n"
);
fs::write(tmp.join("config"), config).expect("write config");
let mut daemon = ChildGuard::spawn(
env!("CARGO_BIN_EXE_rnsd-rs"),
["--config".as_ref(), tmp.path().as_os_str()],
);
if let Err(message) = poll_rnstatus_until(
&mut daemon,
&tmp,
Duration::from_secs(10),
"2",
|interfaces| {
interfaces.iter().any(|entry| {
entry.get("name").and_then(|v| v.as_str()) == Some("Public TCP")
&& entry.get("online").and_then(|v| v.as_bool()) == Some(true)
})
},
) {
panic_with_daemon_output(
format!("{message}\nexpected Public TCP to come online for {host}:{port}"),
daemon,
);
}
}
+36
View File
@@ -0,0 +1,36 @@
use std::process::Command;
#[test]
fn installed_tools_report_rsreticulum_package_version() {
let expected = env!("CARGO_PKG_VERSION");
let tools = [
("rnsd-rs", env!("CARGO_BIN_EXE_rnsd-rs")),
("rnstatus-rs", env!("CARGO_BIN_EXE_rnstatus-rs")),
("rnpath-rs", env!("CARGO_BIN_EXE_rnpath-rs")),
("rnid-rs", env!("CARGO_BIN_EXE_rnid-rs")),
("rnprobe-rs", env!("CARGO_BIN_EXE_rnprobe-rs")),
("rncp-rs", env!("CARGO_BIN_EXE_rncp-rs")),
("rnodeconf-rs", env!("CARGO_BIN_EXE_rnodeconf-rs")),
("rnsh-rs", env!("CARGO_BIN_EXE_rnsh-rs")),
];
for (name, program) in tools {
let output = Command::new(program)
.arg("--version")
.output()
.unwrap_or_else(|err| panic!("failed to run {name} --version: {err}"));
assert!(
output.status.success(),
"{name} --version failed with status {}\n--- stdout ---\n{}\n--- stderr ---\n{}",
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
stdout.starts_with(&format!("{name} {expected}")),
"{name} --version did not report package version {expected:?}\n--- stdout ---\n{stdout}"
);
}
}
File diff suppressed because it is too large. Load diff
+337 -52
View File
@@ -1,4 +1,5 @@
use super::*;
use crate::now_f64;
impl TransportActor {
pub(super) fn on_tick(&mut self) {
@@ -21,7 +22,10 @@ impl TransportActor {
&& self.state_dirty
&& now - self.last_state_save >= STATE_SAVE_INTERVAL_SECS
{
self.save_routing_state();
// Async: the fsync chain (F_FULLFSYNC per file on macOS) stalls
// the actor for seconds if run inline, starving control queries
// and inbound routing.
self.save_routing_state_async();
}
if now - self.last_tables_cull >= TABLES_CULL_INTERVAL {
@@ -30,6 +34,8 @@ impl TransportActor {
self.path_table.cull_expired_batch(100);
self.reverse_table.cull_expired_batch(100);
self.tunnel_table.cull_expired_batch(50);
self.cull_stale_tunnel_paths(now);
self.cull_path_interface_suppressions(now);
// Drop entries pointing to interfaces that have gone away —
// those routes could never be used anyway.
@@ -38,23 +44,28 @@ impl TransportActor {
self.reverse_table.cull_dead_interfaces(&active_interfaces);
self.link_table.cull_dead_interfaces(&active_interfaces);
// An unvalidated link whose proof window elapsed means the
// cached path is probably stale — expire it and re-resolve so
// the next attempt doesn't hammer a dead route.
let (_, expired_dests) = self.link_table.cull_stale(LINK_TIMEOUT);
for dest_hash in expired_dests {
self.path_table.expire(&dest_hash);
self.on_path_request(dest_hash);
debug!(
dest = hex::encode(dest_hash),
"unvalidated link expired -- path expired and re-discovery triggered"
);
// Failed link establishment can mean either a stale path or a
// topology change. Queue rediscovery so automated path requests
// are bounded and throttled like upstream Reticulum 1.2.5.
let (_, expired_links) = self.link_table.cull_stale(LINK_TIMEOUT);
let mut queued_dests = HashSet::new();
for expired_link in expired_links {
if let Some(request) = self.rediscovery_request_for_expired_link(expired_link, now)
{
if queued_dests.insert(request.destination_hash) {
self.queue_discovery_path_request(
request.destination_hash,
request.blocked_interface,
now,
);
}
}
}
// Cull may have removed path/tunnel entries — flag for save so
// the on-disk file reflects the current routing state. False
// positives (cull found nothing) cost one no-op file rewrite at
// the next 10 s tick.
// the next periodic flush.
self.state_dirty = true;
self.last_tables_cull = now;
}
@@ -100,7 +111,9 @@ impl TransportActor {
self.cull_announce_queues(now);
if now - self.last_blackhole_check >= BLACKHOLE_CHECK_INTERVAL {
self.blackhole_table.cull_expired();
if self.blackhole_table.cull_expired() > 0 {
self.publish_blackhole_snapshot();
}
self.state_dirty = true;
self.last_blackhole_check = now;
}
@@ -127,17 +140,20 @@ impl TransportActor {
// ones (Delivered/Failed/Culled) were already signalled out.
self.receipt_table
.retain(|_, r| r.status == ReceiptStatus::Sent);
while self.receipt_table.len() > MAX_RECEIPTS {
if let Some(oldest_key) = self
let excess = self.receipt_table.len().saturating_sub(MAX_RECEIPTS);
if excess > 0 {
// Cull the oldest in one sorted pass — a min-scan per
// eviction is O(n·k) on burst overflow.
let mut by_age: Vec<([u8; 16], std::time::Instant)> = self
.receipt_table
.iter()
.min_by_key(|(_, r)| r.sent_at)
.map(|(k, _)| *k)
{
if let Some(r) = self.receipt_table.get_mut(&oldest_key) {
r.cull();
.map(|(k, r)| (*k, r.sent_at))
.collect();
by_age.sort_unstable_by_key(|(_, sent_at)| *sent_at);
for (key, _) in by_age.into_iter().take(excess) {
if let Some(mut receipt) = self.receipt_table.remove(&key) {
receipt.cull();
}
self.receipt_table.remove(&oldest_key);
}
}
self.last_receipts_check = now;
@@ -149,19 +165,199 @@ impl TransportActor {
self.last_cache_clean = now;
}
// On-disk announce-cache prune. Deliberately outside the
// startup_complete gate: that gate is stamped on first interface
// registration, and a node with no interfaces must still collect
// backlog (Python's jobs thread cleans unconditionally). Safe before
// interfaces exist — pending re-registration entries are in the
// keep-set and the mtime grace covers fresh writes. First sweep runs
// on the first tick after storage init, then every 15 minutes.
if now - self.last_announce_cache_sweep >= ANNOUNCE_CACHE_SWEEP_INTERVAL
&& self.maybe_sweep_announce_cache()
{
self.last_announce_cache_sweep = now;
}
self.expire_path_waiters(now);
// Drop pending path-request markers older than 30 s so a retried
// request isn't treated as "still in flight".
self.path_requests.retain(|_, last| now - *last < 30.0);
// Drop pending path-request markers after the upstream gate timeout.
self.path_requests
.retain(|_, last| now - *last < PATH_REQUEST_GATE_TIMEOUT);
self.discovery_path_requests
.retain(|_, request| now < request.timeout);
self.discovery_pr_tags
.retain(|_, last| now - *last < PATH_REQUEST_GATE_TIMEOUT);
// Python `max_pr_tags` hard cap on top of the time gate: a tag storm
// inside the gate window must not grow the map without bound.
if self.discovery_pr_tags.len() > MAX_DISCOVERY_PR_TAGS {
let mut by_age: Vec<(Vec<u8>, f64)> = self
.discovery_pr_tags
.iter()
.map(|(tag, last)| (tag.clone(), *last))
.collect();
by_age.sort_unstable_by(|a, b| a.1.total_cmp(&b.1));
let excess = self.discovery_pr_tags.len() - MAX_DISCOVERY_PR_TAGS;
for (tag, _) in by_age.into_iter().take(excess) {
self.discovery_pr_tags.remove(&tag);
}
}
self.process_pending_discovery_path_requests(now);
self.process_announce_queues(now);
}
pub(super) fn queue_discovery_path_request(
&mut self,
destination_hash: [u8; 16],
blocked_interface: Option<InterfaceId>,
now: f64,
) -> bool {
if self.pending_discovery_prs.len() >= MAX_QUEUED_DISCOVERY_PRS {
trace!(
dest = hex::encode(destination_hash),
"dropping queued discovery path request because queue is full"
);
return false;
}
let was_empty = self.pending_discovery_prs.is_empty();
self.pending_discovery_prs
.push_back(PendingDiscoveryPathRequest {
destination_hash,
blocked_interface,
});
if was_empty {
self.last_discovery_pr_tx = now;
}
true
}
pub(super) fn process_pending_discovery_path_requests(&mut self, now: f64) {
if self.pending_discovery_prs.is_empty() {
return;
}
if now - self.last_discovery_pr_tx < DISCOVERY_PR_TX_THROTTLE {
return;
}
let Some(request) = self.pending_discovery_prs.pop_front() else {
return;
};
self.last_discovery_pr_tx = now;
if let Some(blocked_interface) = request.blocked_interface {
let ids: Vec<InterfaceId> = self
.interfaces
.iter()
.filter_map(|(&id, entry)| {
if id == blocked_interface || !entry.direction.outbound {
None
} else {
Some(id)
}
})
.collect();
for id in ids {
self.send_path_request(request.destination_hash, id, None, false);
}
} else {
let mut request_tag = [0u8; 16];
{
use rand::RngCore;
rand::thread_rng().fill_bytes(&mut request_tag);
}
let ids: Vec<InterfaceId> = self
.interfaces
.iter()
.filter_map(|(&id, entry)| entry.direction.outbound.then_some(id))
.collect();
for id in ids {
self.send_path_request(request.destination_hash, id, Some(&request_tag), false);
}
}
}
#[cfg(test)]
pub(super) fn handle_expired_unvalidated_link(
&mut self,
expired_link: crate::link_table::ExpiredLink,
now: f64,
) {
if let Some(request) = self.rediscovery_request_for_expired_link(expired_link, now) {
self.queue_discovery_path_request(
request.destination_hash,
request.blocked_interface,
now,
);
}
}
fn rediscovery_request_for_expired_link(
&mut self,
expired_link: crate::link_table::ExpiredLink,
now: f64,
) -> Option<PendingDiscoveryPathRequest> {
let destination_hash = expired_link.destination_hash;
let last_path_request = self
.path_requests
.get(&destination_hash)
.copied()
.unwrap_or(0.0);
let path_request_throttle = now - last_path_request < PATH_REQUEST_MI;
let mut blocked_interface = None;
let mut should_request = false;
if !self.path_table.has_path(&destination_hash) {
should_request = true;
} else if !path_request_throttle {
if expired_link.taken_hops == 0 {
should_request = true;
} else if self.path_table.hops_to(&destination_hash) == Some(1)
|| expired_link.taken_hops == 1
{
should_request = true;
blocked_interface = Some(expired_link.receiving_interface);
self.mark_failed_link_path_unresponsive(&expired_link);
}
}
if !should_request {
return None;
}
if !self.is_transport_enabled {
self.path_table.expire(&destination_hash);
}
debug!(
dest = hex::encode(destination_hash),
blocked_interface, "unvalidated link expired -- queued re-discovery"
);
Some(PendingDiscoveryPathRequest {
destination_hash,
blocked_interface,
})
}
fn mark_failed_link_path_unresponsive(
&mut self,
expired_link: &crate::link_table::ExpiredLink,
) {
if !self.is_transport_enabled {
return;
}
let receiving_is_boundary = self
.interfaces
.get(&expired_link.receiving_interface)
.is_some_and(|entry| entry.mode == InterfaceMode::Boundary);
if !receiving_is_boundary {
self.path_table
.set_state(expired_link.destination_hash, PathState::Unresponsive);
}
}
/// Called on background → foreground. Resets every `last_*_check` so the
/// next `on_tick` runs all maintenance paths in one go.
pub(super) fn on_resume(&mut self) {
@@ -171,6 +367,7 @@ impl TransportActor {
self.last_receipts_check = 0.0;
self.last_announces_check = 0.0;
self.last_cache_clean = 0.0;
self.last_announce_cache_sweep = 0.0;
self.last_blackhole_check = 0.0;
self.last_rate_cull = 0.0;
self.last_held_announce_check = 0.0;
@@ -271,10 +468,49 @@ impl TransportActor {
}
}
/// Sweep `recent_announces`. Keep retained + pathed entries; reap the
/// rest past `DESTINATION_TIMEOUT` (7 days). No count cap.
pub(super) fn cull_stale_tunnel_paths(&mut self, now: f64) {
let mut removed = 0usize;
for (tunnel_id, tunnel) in self.tunnel_table.iter_mut() {
let stale: Vec<[u8; 16]> = tunnel
.tunnel_paths
.iter()
.filter_map(|(dest_hash, tunnel_path)| {
if now > tunnel_path.timestamp + TUNNEL_PATH_TIMEOUT as f64 {
return Some(*dest_hash);
}
let active = self.path_table.get_live(dest_hash)?;
let current_timebase =
path_timebase_from_random_blobs(active.random_blobs.iter());
let tunnel_timebase =
path_timebase_from_random_blobs(tunnel_path.random_blobs.iter());
(current_timebase > tunnel_timebase).then_some(*dest_hash)
})
.collect();
for dest_hash in stale {
tunnel.tunnel_paths.remove(&dest_hash);
removed += 1;
debug!(
dest = hex::encode(dest_hash),
tunnel = hex::encode(&tunnel_id[..16]),
"removed stale tunnel path"
);
}
}
if removed > 0 {
self.state_dirty = true;
}
}
/// Sweep `recent_announces`, mirroring Python
/// `Identity.clean_known_destinations`: retained + pathed entries are
/// kept; pathless never-used entries die after `UNUSED_DESTINATION_LINGER`
/// (6 min); pathless used entries die after `DESTINATION_TIMEOUT * 1.25`
/// idle since last use.
pub(super) fn cleanup_known_destinations(&mut self, now: f64) {
let threshold = DESTINATION_TIMEOUT as f64;
let used_threshold = DESTINATION_TIMEOUT as f64 * 1.25;
let before = self.recent_announces.len();
// Collect into a Vec; the has-path borrow on path_table fights an
@@ -289,12 +525,11 @@ impl TransportActor {
if self.path_table.has_path(&a.dest_hash) {
return None;
}
let idle = now - a.timestamp;
if idle > threshold {
Some(a.dest_hash)
} else {
None
}
let stale = match a.last_used {
None => now - a.timestamp > UNUSED_DESTINATION_LINGER,
Some(last_used) => now - last_used.max(a.timestamp) > used_threshold,
};
if stale { Some(a.dest_hash) } else { None }
})
.collect();
@@ -381,7 +616,13 @@ mod cleanup_tests {
use crate::actor::RecentAnnounce;
use crate::path_table::PathEntry;
fn insert_entry(actor: &mut TransportActor, hash: u8, timestamp: f64, retained: bool) {
fn insert_entry_with_last_used(
actor: &mut TransportActor,
hash: u8,
timestamp: f64,
retained: bool,
last_used: Option<f64>,
) {
let entry = RecentAnnounce {
dest_hash: [hash; 16],
hops: 0,
@@ -389,13 +630,23 @@ mod cleanup_tests {
timestamp,
public_key: None,
ratchet: None,
raw_packet: Vec::new(),
packet_hash: None,
is_path_response: false,
retained,
last_used,
name_hash: [0u8; 10],
};
actor.recent_announces.insert(entry.dest_hash, entry);
}
fn insert_entry(actor: &mut TransportActor, hash: u8, timestamp: f64, retained: bool) {
insert_entry_with_last_used(actor, hash, timestamp, retained, None);
}
fn insert_used_entry(actor: &mut TransportActor, hash: u8, timestamp: f64, last_used: f64) {
insert_entry_with_last_used(actor, hash, timestamp, false, Some(last_used));
}
#[test]
fn retained_survives_cleanup() {
let (mut actor, _tx) = TransportActor::new();
@@ -418,28 +669,29 @@ mod cleanup_tests {
assert_eq!(actor.recent_announces.len(), 1);
}
// Pre-collapse, a never-used pathless entry was reaped after 6 min.
// Under the uniform 7-d policy, an entry only ten minutes old survives.
#[test]
fn pathless_kept_well_below_destination_timeout() {
fn pathless_never_used_kept_inside_linger() {
let (mut actor, _tx) = TransportActor::new();
let now = 10_000.0;
let ten_minutes_old = now - 10.0 * 60.0;
insert_entry(&mut actor, 0x03, ten_minutes_old, /*retained=*/ false);
insert_entry(
&mut actor,
0x03,
now - UNUSED_DESTINATION_LINGER + 1.0,
/*retained=*/ false,
);
actor.cleanup_known_destinations(now);
assert_eq!(actor.recent_announces.len(), 1);
}
#[test]
fn pathless_reaped_past_destination_timeout() {
fn pathless_never_used_reaped_after_linger() {
let (mut actor, _tx) = TransportActor::new();
let now = 10_000_000.0;
let timeout = DESTINATION_TIMEOUT as f64;
let now = 10_000.0;
insert_entry(
&mut actor,
0x05,
now - timeout - 1.0,
now - UNUSED_DESTINATION_LINGER - 1.0,
/*retained=*/ false,
);
@@ -448,18 +700,51 @@ mod cleanup_tests {
}
#[test]
fn pathless_kept_just_inside_destination_timeout() {
fn pathless_used_survives_destination_timeout_idle() {
let (mut actor, _tx) = TransportActor::new();
let now = 10_000_000.0;
let timeout = DESTINATION_TIMEOUT as f64;
insert_entry(
&mut actor,
0x07,
now - timeout + 1.0,
/*retained=*/ false,
);
// Announce far past linger; 7 d idle since use is inside the
// 7 d * 1.25 window, so the use pin keeps it alive.
insert_used_entry(&mut actor, 0x07, now - timeout * 2.0, now - timeout);
actor.cleanup_known_destinations(now);
assert_eq!(actor.recent_announces.len(), 1);
}
#[test]
fn pathless_used_reaped_past_destination_timeout_x125() {
let (mut actor, _tx) = TransportActor::new();
let now = 10_000_000.0;
let threshold = DESTINATION_TIMEOUT as f64 * 1.25;
insert_used_entry(
&mut actor,
0x09,
now - threshold - 2.0,
now - threshold - 1.0,
);
actor.cleanup_known_destinations(now);
assert!(actor.recent_announces.is_empty());
}
#[test]
fn discovery_pr_tags_capped_at_max() {
let (mut actor, _tx) = TransportActor::new();
let now = crate::now_f64();
// All inside PATH_REQUEST_GATE_TIMEOUT, so only the count cap trims.
for i in 0..=MAX_DISCOVERY_PR_TAGS {
let tag = (i as u64).to_be_bytes().to_vec();
actor.discovery_pr_tags.insert(tag, now - (i as f64) * 1e-4);
}
assert_eq!(actor.discovery_pr_tags.len(), MAX_DISCOVERY_PR_TAGS + 1);
actor.on_tick();
assert_eq!(actor.discovery_pr_tags.len(), MAX_DISCOVERY_PR_TAGS);
let oldest = (MAX_DISCOVERY_PR_TAGS as u64).to_be_bytes().to_vec();
assert!(!actor.discovery_pr_tags.contains_key(&oldest));
let newest = 0u64.to_be_bytes();
assert!(actor.discovery_pr_tags.contains_key(newest.as_slice()));
}
}
File diff suppressed because it is too large. Load diff
+200 -112
View File
@@ -1,4 +1,17 @@
use super::*;
use crate::now_f64;
/// Python 1.3.8 Transport.PR_LOGLEVEL (Transport.py:220/306): path-request
/// chatter logs at DEBUG on transport nodes, EXTREME (trace) on leaf nodes.
macro_rules! pr_log {
($actor:expr, $($arg:tt)*) => {
if $actor.is_transport_enabled {
debug!($($arg)*);
} else {
trace!($($arg)*);
}
};
}
impl TransportActor {
pub(super) fn on_outbound(&mut self, request: crate::messages::OutboundRequest) {
@@ -57,7 +70,7 @@ impl TransportActor {
self.broadcast_on_interfaces(&request.raw, None);
}
rns_wire::flags::DestinationType::Single | rns_wire::flags::DestinationType::Link => {
if let Some(path) = self.path_table.get(&request.destination_hash) {
if let Some(path) = self.path_table.get_live(&request.destination_hash) {
let target_interface = path.interface_id;
let path_hops = path.hops;
let path_next_hop = path.next_hop;
@@ -75,6 +88,10 @@ impl TransportActor {
"outbound: routed via path"
);
// Python 1.3.8 Transport.py:1153/1186: local_hops_delta
// replaces the zero hops byte on the way out.
let apply_delta = self.should_apply_delta(&parsed, target_interface);
// Transport nodes only forward Header2 packets whose transport_id
// matches their identity — Python hubs silently drop Header1 —
// so every directed send through a relay must be wrapped.
@@ -87,7 +104,11 @@ impl TransportActor {
};
let new_header = rns_wire::header::PacketHeader {
flags: new_flags,
hops: parsed.hops,
hops: if apply_delta {
self.local_hops_delta
} else {
parsed.hops
},
transport_id: Some(next_hop),
destination_hash: parsed.destination_hash,
context: parsed.context,
@@ -103,17 +124,23 @@ impl TransportActor {
"outbound: wrapped Header1 -> Header2 for transport"
);
self.send_to_interface(target_interface, &new_raw);
} else if apply_delta {
let mangled = self.mangle_hops(&request.raw, &parsed, false);
self.send_to_interface(target_interface, &mangled);
} else {
self.send_to_interface(target_interface, &request.raw);
}
} else if apply_delta {
let mangled = self.mangle_hops(&request.raw, &parsed, false);
self.send_to_interface(target_interface, &mangled);
} else {
self.send_to_interface(target_interface, &request.raw);
}
// Touch the path so an actively-used route isn't culled
// for staleness while traffic is still flowing on it.
if let Some(path) = self.path_table.get_mut(&request.destination_hash) {
path.timestamp = now_f64();
if let Some(path) = self.path_table.get_live_mut(&request.destination_hash) {
path.touch();
}
} else {
let iface_names: Vec<&str> = self
@@ -128,7 +155,9 @@ impl TransportActor {
"outbound: no path, broadcasting"
);
self.broadcast_on_interfaces(&request.raw, None);
self.on_path_request(request.destination_hash);
if parsed.flags.packet_type != rns_wire::flags::PacketType::Proof {
self.on_automatic_path_request(request.destination_hash);
}
}
}
}
@@ -144,7 +173,17 @@ impl TransportActor {
if let Ok((parsed, _)) = rns_wire::header::PacketHeader::unpack(&request.raw) {
let pkt_hash = rns_wire::hash::packet_hash(&request.raw, parsed.flags.header_type);
self.packet_hashlist.insert(pkt_hash);
self.send_to_interface(interface_id, &request.raw);
// Python's outbound applies should_apply_delta on attached-
// interface sends too (Transport.py:1342-1345).
if self.should_apply_delta(&parsed, interface_id) {
let transport_insert = parsed.flags.packet_type
== rns_wire::flags::PacketType::Announce
&& parsed.flags.header_type == rns_wire::flags::HeaderType::Header1;
let mangled = self.mangle_hops(&request.raw, &parsed, transport_insert);
self.send_to_interface(interface_id, &mangled);
} else {
self.send_to_interface(interface_id, &request.raw);
}
if parsed.flags.packet_type == rns_wire::flags::PacketType::Announce {
if let Some(entry) = self.interfaces.get_mut(&interface_id) {
entry.ingress.sent_announce();
@@ -183,13 +222,13 @@ impl TransportActor {
let mut requested_hash = [0u8; 32];
requested_hash.copy_from_slice(payload);
let dest_hash: Option<[u8; 16]> = self
let dest_and_hops: Option<([u8; 16], u8)> = self
.path_table
.iter()
.find(|(_, entry)| entry.packet_hash == Some(requested_hash))
.map(|(dest, _)| *dest.as_bytes());
.map(|(dest, entry)| (*dest.as_bytes(), entry.hops));
let Some(dest) = dest_hash else {
let Some((dest, cached_hops)) = dest_and_hops else {
trace!(
hash = %hex::encode(requested_hash),
"cache request miss — no path entry with matching packet hash"
@@ -197,21 +236,23 @@ impl TransportActor {
return;
};
let (cached_raw, cached_hops) = match self.recent_announces.get(&dest) {
Some(cached) => (cached.raw_packet.clone(), cached.hops),
None => {
trace!(
dest = %hex::encode(dest),
"cache request: path entry found but no cached announce for destination"
);
return;
}
};
if cached_raw.is_empty() {
let Some(cached_raw) = self.cached_announce_raw(&requested_hash) else {
trace!(
dest = %hex::encode(dest),
"cache request: announce cached but no raw packet (v1 persistence), ignoring"
"cache request: path entry found but no cached announce on disk"
);
return;
};
// Python 1.3.8 Transport.py:2164: a cached packet that fails to unpack
// (incl. hops >= PATHFINDER_M, Packet.py:247-248) is a miss — never
// replay the raw bytes.
if rns_wire::header::PacketHeader::unpack(&cached_raw)
.map_or(true, |(h, _)| h.hops >= PATHFINDER_M)
{
trace!(
dest = %hex::encode(dest),
"cache request: cached announce failed to parse, treating as miss"
);
return;
}
@@ -276,13 +317,18 @@ impl TransportActor {
};
let Some(tag) = tag_bytes else {
trace!(
pr_log!(
self,
dest = %hex::encode(requested_dest),
"ignoring tagless path request"
);
return;
};
if let Some(entry) = self.interfaces.get_mut(&interface_id) {
entry.ingress.received_path_request();
}
let now = now_f64();
let mut unique_tag = Vec::with_capacity(32);
unique_tag.extend_from_slice(&requested_dest);
@@ -321,7 +367,7 @@ impl TransportActor {
}
if !is_from_local_client {
if let Some(path) = self.path_table.get(&requested_dest) {
if let Some(path) = self.path_table.get_live(&requested_dest) {
if self.is_local_client_interface(path.interface_id) {
self.pending_local_path_requests
.insert(requested_dest, interface_id);
@@ -333,7 +379,7 @@ impl TransportActor {
// shared instance's path cache even when the instance is not a transport
// node. Ordinary peers still require transport mode.
if let Some(path) = (self.is_transport_enabled || is_from_local_client)
.then(|| self.path_table.get(&requested_dest))
.then(|| self.path_table.get_live(&requested_dest))
.flatten()
{
let requestor_is_next_hop =
@@ -359,21 +405,24 @@ impl TransportActor {
return;
}
let cached_raw: Option<(u8, Vec<u8>)> =
self.recent_announces.get(&requested_dest).and_then(|a| {
if a.raw_packet.is_empty() {
None
} else {
Some((path.hops, a.raw_packet.clone()))
}
});
let cached_raw: Option<(u8, Vec<u8>)> = path
.packet_hash
.and_then(|hash| self.cached_announce_raw(&hash))
.map(|raw| (path.hops, raw));
if let Some((hops, raw)) = cached_raw {
debug!(
// Python 1.3.8 Transport.py:2984: unparseable cached announce
// aborts the answer entirely (no fall-through to discovery).
let Some(response) =
self.path_response_from_cached_announce(&raw, requested_dest, hops)
else {
return;
};
pr_log!(
self,
dest = %hex::encode(requested_dest),
hops,
"answering path request — path is known, queueing path response"
);
let response = self.path_response_from_cached_announce(&raw, requested_dest, hops);
let now = now_f64();
let path_on_local_client = self.is_local_client_interface(path.interface_id);
let response_delay = if is_from_local_client || path_on_local_client {
@@ -412,43 +461,57 @@ impl TransportActor {
}
}
// Python 1.3.8 Transport.py:2946-2947: recursive_prs forces discovery
// independent of interface mode (flag checked first).
let should_search_unknown = self
.interfaces
.get(&interface_id)
.is_some_and(|iface| mode_discovers_unknown_paths(iface.mode));
.is_some_and(|iface| iface.recursive_prs || mode_discovers_unknown_paths(iface.mode));
if is_from_local_client {
debug!(
pr_log!(
self,
dest = %hex::encode(requested_dest),
"forwarding path request from local shared client"
);
self.forward_path_request(requested_dest, Some(interface_id), tag_bytes, false);
} else if self.is_transport_enabled && should_search_unknown {
let should_forward = match self.discovery_path_requests.entry(requested_dest) {
std::collections::hash_map::Entry::Occupied(_) => {
debug!(
dest = %hex::encode(requested_dest),
"not forwarding path request — discovery request is already waiting"
);
false
}
std::collections::hash_map::Entry::Vacant(entry) => {
debug!(
dest = %hex::encode(requested_dest),
"forwarding path request on other interfaces"
);
entry.insert(DiscoveryPathRequest {
requesting_interface: interface_id,
timeout: now + PATH_REQUEST_TIMEOUT,
});
true
}
};
if should_forward {
self.forward_path_request(requested_dest, Some(interface_id), tag_bytes, true);
if self.discovery_path_requests.contains_key(&requested_dest) {
debug!(
dest = %hex::encode(requested_dest),
"not forwarding path request — discovery request is already waiting"
);
return;
}
} else if self.has_local_client_interfaces() {
let ingress_limited = self
.interfaces
.get_mut(&interface_id)
.is_some_and(|iface| iface.ingress.should_ingress_limit_pr());
if ingress_limited {
debug!(
dest = %hex::encode(requested_dest),
interface_id,
"not forwarding recursive path request — ingress PR burst active"
);
return;
}
debug!(
dest = %hex::encode(requested_dest),
"forwarding path request on other interfaces"
);
self.discovery_path_requests.insert(
requested_dest,
DiscoveryPathRequest {
requesting_interface: interface_id,
timeout: now + PATH_REQUEST_TIMEOUT,
},
);
self.forward_path_request(requested_dest, Some(interface_id), tag_bytes, true);
} else if self.has_local_client_interfaces() {
pr_log!(
self,
dest = %hex::encode(requested_dest),
"forwarding path request to local shared clients"
);
@@ -456,7 +519,8 @@ impl TransportActor {
self.send_path_request(requested_dest, local_id, None, false);
}
} else {
debug!(
pr_log!(
self,
dest = %hex::encode(requested_dest),
interface_id,
"ignoring unknown path request on non-discovery interface"
@@ -501,16 +565,61 @@ impl TransportActor {
raw
}
fn send_path_request(
pub(super) fn send_path_request(
&mut self,
destination_hash: [u8; 16],
interface_id: InterfaceId,
tag: Option<&[u8]>,
_recursive: bool,
recursive: bool,
) {
let raw = self.build_path_request_packet(destination_hash, tag);
let now = now_f64();
{
let Some(entry) = self.interfaces.get_mut(&interface_id) else {
return;
};
if !entry.direction.outbound {
return;
}
if recursive {
if entry.ingress.should_egress_limit_pr() {
trace!(
dest = %hex::encode(destination_hash),
interface_id,
"skipping recursive path request — egress PR limit active"
);
return;
}
if !entry.announce_queue.is_empty() {
trace!(
dest = %hex::encode(destination_hash),
interface_id,
"skipping recursive path request — announce queue is not empty"
);
return;
}
if now < entry.announce_allowed_at {
trace!(
dest = %hex::encode(destination_hash),
interface_id,
"skipping recursive path request — announce cap window active"
);
return;
}
let bitrate = entry.bitrate.max(1) as f64;
let tx_time = (raw.len() as f64 * 8.0) / bitrate;
let wait_time = tx_time / entry.announce_cap.max(0.001);
entry.announce_allowed_at = now + wait_time;
}
}
self.send_to_interface(interface_id, &raw);
self.path_requests.insert(destination_hash, now_f64());
if let Some(entry) = self.interfaces.get_mut(&interface_id) {
entry.ingress.sent_path_request();
}
self.path_requests.insert(destination_hash, now);
}
fn forward_path_request(
@@ -537,60 +646,29 @@ impl TransportActor {
}
pub(super) fn on_path_request(&mut self, destination_hash: [u8; 16]) {
let now = now_f64();
if let Some(last) = self.path_requests.get(&destination_hash) {
if now - last < PATH_REQUEST_MI {
return;
}
}
self.path_requests.insert(destination_hash, now);
self.broadcast_path_request(destination_hash);
}
pub(super) fn on_automatic_path_request(&mut self, destination_hash: [u8; 16]) {
if self.path_table.has_path(&destination_hash) {
return;
}
if let Some(last) = self.path_requests.get(&destination_hash) {
if now_f64() - last < PATH_REQUEST_MI {
return;
}
}
self.broadcast_path_request(destination_hash);
}
// Python Transport.request_path sends a PLAIN packet to the
// rnstransport.path.request destination. The payload is the requested
// destination hash, optionally followed by the transport identity hash,
// and a random tag used for request deduplication.
fn broadcast_path_request(&mut self, destination_hash: [u8; 16]) {
let mut request_tag = [0u8; 16];
{
use rand::RngCore;
rand::thread_rng().fill_bytes(&mut request_tag);
}
let mut request_data = Vec::with_capacity(48);
request_data.extend_from_slice(&destination_hash);
if self.is_transport_enabled {
if let Some(identity_hash) = self.transport_identity_hash {
request_data.extend_from_slice(&identity_hash);
}
}
request_data.extend_from_slice(&request_tag);
let path_request_dest = rns_identity::destination::Destination::hash_from_name_and_identity(
"rnstransport.path.request",
None,
);
let 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::Plain,
packet_type: rns_wire::flags::PacketType::Data,
};
let path_request_header = rns_wire::header::PacketHeader {
flags,
hops: 0,
transport_id: None,
destination_hash: path_request_dest,
context: rns_wire::context::PacketContext::None,
};
let mut request_raw = path_request_header.pack();
request_raw.extend_from_slice(&request_data);
self.broadcast_on_interfaces(&request_raw, None);
self.forward_path_request(destination_hash, None, Some(&request_tag), false);
debug!(
dest = hex::encode(destination_hash),
@@ -622,10 +700,19 @@ impl TransportActor {
if let Some(existing) = self.path_table.get(dest_hash) {
let old_hops = existing.hops;
let old_expires = existing.expires;
// Only overwrite a live path if the tunnel copy is at least
// as short, or the live entry is already stale.
if tunnel_path.hops <= old_hops || now > old_expires {
should_add = true;
let current_timebase =
path_timebase_from_random_blobs(existing.random_blobs.iter());
let tunnel_timebase =
path_timebase_from_random_blobs(tunnel_path.random_blobs.iter());
if tunnel_timebase >= current_timebase {
should_add = true;
} else {
debug!(
dest = hex::encode(dest_hash),
"did not restore tunnel path: existing path is more recent"
);
}
} else {
debug!(
dest = hex::encode(dest_hash),
@@ -644,12 +731,12 @@ impl TransportActor {
if should_add {
let entry = crate::path_table::PathEntry {
timestamp: now,
next_hop: None,
next_hop: tunnel_path.next_hop,
hops: tunnel_path.hops,
expires: tunnel_path.expires,
random_blobs: tunnel_path.random_blobs.iter().copied().collect(),
interface_id,
packet_hash: None,
packet_hash: tunnel_path.packet_hash,
};
self.path_table.insert(*dest_hash, entry);
self.state_dirty = true;
@@ -675,6 +762,7 @@ impl TransportActor {
);
}
}
self.state_dirty = true;
}
}
}
File diff suppressed because it is too large. Load diff
+138 -17
View File
@@ -1,4 +1,5 @@
use super::*;
use crate::now_f64;
impl TransportActor {
pub(super) fn handle_query(
@@ -10,7 +11,7 @@ impl TransportActor {
TransportQuery::GetPathTable => {
let entries: Vec<PathTableRpcEntry> = self
.path_table
.iter()
.iter_live()
.map(|(hash, entry)| {
let iface_name = self
.interfaces
@@ -24,12 +25,24 @@ impl TransportActor {
hops: entry.hops,
expires: entry.expires,
interface: iface_name,
interface_id: entry.interface_id,
interface_mode: self
.interfaces
.get(&entry.interface_id)
.map(|e| e.mode)
.unwrap_or(crate::constants::InterfaceMode::Full),
interface_role: self
.interfaces
.get(&entry.interface_id)
.map(|e| e.role)
.unwrap_or_default(),
}
})
.collect();
TransportQueryResponse::PathTable(entries)
}
TransportQuery::GetInterfaceStats => {
let now = now_f64();
let stats: Vec<InterfaceStatRpcEntry> = self
.interfaces
.iter()
@@ -66,7 +79,23 @@ impl TransportActor {
incoming_announce_frequency: entry
.ingress
.incoming_announce_frequency(),
outgoing_announce_frequency: 0.0,
outgoing_announce_frequency: entry
.ingress
.outgoing_announce_frequency(),
incoming_pr_frequency: entry.ingress.incoming_pr_frequency(),
outgoing_pr_frequency: entry.ingress.outgoing_pr_frequency(),
burst_active: entry.ingress.is_burst_active(),
burst_activated: activation_epoch(
now,
entry.ingress.is_burst_active(),
entry.ingress.burst_activated(),
),
pr_burst_active: entry.ingress.is_pr_burst_active(),
pr_burst_activated: activation_epoch(
now,
entry.ingress.is_pr_burst_active(),
entry.ingress.pr_burst_activated(),
),
clients: None,
announce_rate_target: entry.announce_rate_target,
announce_rate_grace: entry.announce_rate_grace,
@@ -101,14 +130,19 @@ impl TransportActor {
let mut entries: Vec<AnnounceRpcEntry> = self
.recent_announces
.values()
.map(|a| AnnounceRpcEntry {
dest_hash: a.dest_hash,
hops: a.hops,
app_data: a.app_data.clone(),
timestamp: a.timestamp,
public_key: a.public_key,
ratchet: a.ratchet,
retained: a.retained,
.map(|a| {
let is_path_response = a.is_path_response;
AnnounceRpcEntry {
dest_hash: a.dest_hash,
hops: a.hops,
app_data: a.app_data.clone(),
timestamp: a.timestamp,
public_key: a.public_key,
ratchet: a.ratchet,
name_hash: a.name_hash,
is_path_response,
retained: a.retained,
}
})
.collect();
// HashMap iteration order is unspecified; sort newest-first
@@ -122,14 +156,29 @@ impl TransportActor {
TransportQueryResponse::Announces(entries)
}
TransportQuery::GetNextHop { dest } => {
let next_hop = self.path_table.get(&dest).and_then(|e| e.next_hop);
// Python 1.3.8 Transport.py:2685-2688: local destinations
// resolve to Transport.identity.hash.
let next_hop = self
.path_table
.get_live(&dest)
.and_then(|e| e.next_hop)
.or_else(|| {
self.local_destinations
.contains(&dest)
.then_some(self.transport_identity_hash)
.flatten()
});
TransportQueryResponse::HashResult(next_hop)
}
TransportQuery::GetNextHopIfName { dest } => {
// Python 1.3.8 Transport.py:2691-2697: local destinations
// resolve to the shared-instance interface (None off shared hosts).
let name = self
.path_table
.get(&dest)
.and_then(|e| self.interfaces.get(&e.interface_id).map(|i| i.name.clone()));
.get_live(&dest)
.map(|e| e.interface_id)
.or_else(|| self.local_destination_interface_id(&dest))
.and_then(|id| self.interfaces.get(&id).map(|i| i.name.clone()));
TransportQueryResponse::StringResult(name)
}
TransportQuery::GetPacketRssi { packet_hash } => TransportQueryResponse::FloatResult(
@@ -157,12 +206,48 @@ impl TransportActor {
self.state_dirty = true;
TransportQueryResponse::Ok
}
TransportQuery::SuppressPathInterface {
dest,
interface_id,
duration,
} => TransportQueryResponse::BoolResult(self.suppress_path_interface(
dest,
interface_id,
duration,
)),
TransportQuery::SuppressCurrentPathInterface { dest, duration } => {
let interface_id = self
.path_table
.get_live(&dest)
.map(|entry| entry.interface_id);
TransportQueryResponse::BoolResult(interface_id.is_some_and(|interface_id| {
self.suppress_path_interface(dest, interface_id, duration)
}))
}
TransportQuery::DropAnnounceQueues => {
for entry in self.interfaces.values_mut() {
entry.announce_queue.clear();
}
TransportQueryResponse::Ok
}
TransportQuery::DropPathTable => {
let cleared = self.path_table.len();
self.path_table = crate::path_table::PathTable::new();
self.pending_path_entries.clear();
self.discovery_path_requests.clear();
self.pending_local_path_requests.clear();
self.pending_discovery_prs.clear();
self.state_dirty = true;
self.save_routing_state();
TransportQueryResponse::IntResult(cleared as i64)
}
TransportQuery::DropRecentAnnounces => {
let cleared = self.recent_announces.len();
self.recent_announces.clear();
self.state_dirty = true;
self.save_routing_state();
TransportQueryResponse::IntResult(cleared as i64)
}
TransportQuery::GetBlackholedIdentities => {
// Snapshot of identity hashes we have a current announce for —
// used to decorate each entry with `verified`.
@@ -224,12 +309,14 @@ impl TransportActor {
self.path_table.remove(&dest);
}
self.state_dirty = true;
self.publish_blackhole_snapshot();
TransportQueryResponse::Ok
}
TransportQuery::UnblackholeIdentity { hash } => {
let removed = self.blackhole_table.remove(&hash);
if removed {
self.state_dirty = true;
self.publish_blackhole_snapshot();
}
TransportQueryResponse::BoolResult(removed)
}
@@ -240,6 +327,7 @@ impl TransportActor {
let cleared = self.blackhole_table.clear_system_entries();
if cleared > 0 {
self.state_dirty = true;
self.publish_blackhole_snapshot();
}
TransportQueryResponse::IntResult(cleared as i64)
}
@@ -272,6 +360,7 @@ impl TransportActor {
);
if applied > 0 {
self.state_dirty = true;
self.publish_blackhole_snapshot();
}
TransportQueryResponse::IntResult(applied as i64)
}
@@ -386,19 +475,26 @@ impl TransportActor {
TransportQuery::GetNextHopBitrate { dest } => {
let bitrate = self
.path_table
.get(&dest)
.and_then(|e| self.interfaces.get(&e.interface_id))
.get_live(&dest)
.map(|e| e.interface_id)
.or_else(|| self.local_destination_interface_id(&dest))
.and_then(|id| self.interfaces.get(&id))
.map(|iface| iface.bitrate as f64);
TransportQueryResponse::FloatResult(bitrate)
}
TransportQuery::GetNextHopInterfaceId { dest } => {
let id = self.path_table.get(&dest).map(|e| e.interface_id as i64);
let id = self
.path_table
.get_live(&dest)
.map(|e| e.interface_id)
.or_else(|| self.local_destination_interface_id(&dest))
.map(|id| id as i64);
TransportQueryResponse::IntResult(id.unwrap_or(-1))
}
TransportQuery::FirstHopTimeout { dest } => {
let timeout = self
.path_table
.get(&dest)
.get_live(&dest)
.and_then(|e| self.interfaces.get(&e.interface_id))
.map(|iface| {
let per_byte_latency = 8.0 / iface.bitrate as f64;
@@ -515,9 +611,34 @@ impl TransportActor {
}
if purged > 0 {
self.state_dirty = true;
self.publish_blackhole_snapshot();
}
TransportQueryResponse::IntResult(purged as i64)
}
}
}
/// Next-hop interface for a local destination: the shared-instance server
/// interface, mirroring Python 1.3.8 Transport.next_hop_interface's
/// destinations_map fallback (Transport.py:2695-2696).
fn local_destination_interface_id(
&self,
dest: &[u8; 16],
) -> Option<crate::messages::InterfaceId> {
if !self.local_destinations.contains(dest) {
return None;
}
self.interfaces
.iter()
.find(|(_, e)| e.role == crate::messages::InterfaceRole::SharedServer)
.map(|(&id, _)| id)
}
}
fn activation_epoch(now: f64, active: bool, activated: std::time::Instant) -> f64 {
if active {
now - activated.elapsed().as_secs_f64()
} else {
0.0
}
}
+1 -1
View File
@@ -15,7 +15,7 @@ pub struct AnnounceEntry {
pub received_from: [u8; 16],
/// Hop count as observed on receipt.
pub hops: u8,
/// Outbound packet bytes with the hop count already incremented.
/// Outbound packet bytes with the Python-parity inbound-adjusted hop count.
pub packet_raw: Vec<u8>,
/// Count of duplicate rebroadcasts heard from neighbours — used to suppress flooding.
pub local_rebroadcasts: u32,
+2 -1
View File
@@ -2,7 +2,8 @@
//!
//! Mirrors Python `Transport.await_path(destination_hash, timeout=None)`
//! (RNS/Transport.py:2524). The helper sends an [`AwaitPath`] actor
//! message and races the oneshot reply against a caller-supplied timeout.
//! message and races the oneshot reply against a caller-supplied timeout. The
//! actor emits the upstream-compatible path request before parking the waiter.
//!
//! [`AwaitPath`]: crate::messages::TransportMessage::AwaitPath
+5 -17
View File
@@ -1,5 +1,4 @@
use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};
use rns_wire::types::IdentityHash;
use serde::{Deserialize, Serialize};
@@ -64,6 +63,7 @@ impl BlackholeEntry {
}
}
#[derive(Clone)]
pub struct BlackholeTable {
entries: HashMap<IdentityHash, BlackholeEntry>,
}
@@ -87,10 +87,7 @@ impl BlackholeTable {
ttl: Option<f64>,
reason: BlackholeReason,
) {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64();
let now = crate::now_f64();
self.entries.insert(
identity_hash.into(),
@@ -111,10 +108,7 @@ impl BlackholeTable {
reason: BlackholeReason,
reason_label: Option<String>,
) {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64();
let now = crate::now_f64();
self.entries.insert(
identity_hash.into(),
@@ -163,10 +157,7 @@ impl BlackholeTable {
match self.entries.get(identity_hash) {
Some(entry) => {
if let Some(ttl) = entry.ttl {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64();
let now = crate::now_f64();
now - entry.created < ttl
} else {
true
@@ -183,10 +174,7 @@ impl BlackholeTable {
/// Drop entries whose TTL has elapsed; returns the number removed.
pub fn cull_expired(&mut self) -> usize {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64();
let now = crate::now_f64();
let before = self.entries.len();
self.entries
+87 -16
View File
@@ -53,6 +53,12 @@ pub const PATH_REQUEST_TIMEOUT: f64 = 15.0;
/// Duplicate inbound path request tag retention (seconds).
pub const PATH_REQUEST_GATE_TIMEOUT: f64 = 120.0;
/// Maximum queued automatic discovery path requests after failed link setup.
pub const MAX_QUEUED_DISCOVERY_PRS: usize = 32;
/// Minimum spacing between queued discovery path-request transmissions.
pub const DISCOVERY_PR_TX_THROTTLE: f64 = 0.5;
/// Grace before path response (seconds).
pub const PATH_REQUEST_GRACE: f64 = 0.4;
@@ -76,7 +82,20 @@ pub const JOB_INTERVAL_BG_MS: u64 = 2000;
/// Cadence at which `on_tick` flushes routing-state files (path_table,
/// announce_cache, blackhole, tunnel_table) when dirty. Hashlist is excluded
/// (multi-MB on busy hubs); it saves on shutdown + foreground→background.
pub const STATE_SAVE_INTERVAL_SECS: f64 = 10.0;
/// Matches Python `Reticulum.GRACIOUS_PERSIST_INTERVAL` (5 min). On a live
/// announce feed the dirty bit is effectively always set, so this interval
/// IS the flush rate — at 10s the full-state clone+serialize+fsync cycle
/// dominated daemon RSS via allocator churn. Abrupt-exit safety comes from
/// the falling-edge save and `on_shutdown`, not from this cadence.
pub const STATE_SAVE_INTERVAL_SECS: f64 = 300.0;
/// Python `Transport.UNUSED_DESTINATION_LINGER`: never-used destinations
/// without a path are dropped from the announce cache after this idle time.
pub const UNUSED_DESTINATION_LINGER: f64 = 360.0;
/// Python `Transport.max_pr_tags`: hard count cap on the discovery
/// path-request tag gate, on top of the time-based retain.
pub const MAX_DISCOVERY_PR_TAGS: usize = 32_000;
/// Link table check interval.
pub const LINKS_CHECK_INTERVAL: f64 = 1.0;
@@ -93,6 +112,18 @@ pub const PENDING_PRS_CHECK_INTERVAL: f64 = 30.0;
/// Cache cleanup interval (5 minutes).
pub const CACHE_CLEAN_INTERVAL: f64 = 300.0;
/// On-disk announce cache sweep cadence — Python's 15-minute
/// `clean_announce_cache` interval. Independent of the RAM-cache clean
/// gate: Python's jobs thread cleans regardless of interface presence, so a
/// node that boots with no interfaces still collects backlog.
pub const ANNOUNCE_CACHE_SWEEP_INTERVAL: f64 = 900.0;
/// Never delete announce-cache files younger than this. The keep-set is
/// snapshotted on the actor while the cache writer keeps running on the
/// blocking pool, so a fresh announce can exist on disk before its path
/// entry does. Python accepts that race; we close it.
pub const ANNOUNCE_CACHE_SWEEP_GRACE_SECS: u64 = 300;
/// Table culling interval.
pub const TABLES_CULL_INTERVAL: f64 = 5.0;
@@ -116,41 +147,77 @@ pub const ANNOUNCE_CAP: f64 = 0.02;
pub const MAX_HELD_ANNOUNCES: usize = 256;
/// Held announce release interval (seconds).
/// Matches Python 1.2.4 `Interface.IC_HELD_RELEASE_INTERVAL = 2`.
pub const IC_HELD_RELEASE_INTERVAL: f64 = 2.0;
/// Matches Python 1.2.5 `Interface.IC_HELD_RELEASE_INTERVAL = 5`.
pub const IC_HELD_RELEASE_INTERVAL: f64 = 5.0;
/// Incoming announce frequency window samples.
/// Matches Python 1.2.4 `Interface.IA_FREQ_SAMPLES = 128`.
pub const IA_FREQ_SAMPLES: usize = 128;
/// Matches Python 1.2.5 `Interface.IA_FREQ_SAMPLES = 48`.
pub const IA_FREQ_SAMPLES: usize = 48;
/// Outgoing announce frequency window samples.
/// Matches Python 1.2.4 `Interface.OA_FREQ_SAMPLES = 128`.
pub const OA_FREQ_SAMPLES: usize = 128;
/// Matches Python 1.2.5 `Interface.OA_FREQ_SAMPLES = 48`.
pub const OA_FREQ_SAMPLES: usize = 48;
/// Incoming path-request frequency window samples.
/// Matches Python 1.2.5 `Interface.IP_FREQ_SAMPLES = 48`.
pub const IP_FREQ_SAMPLES: usize = 48;
/// Outgoing path-request frequency window samples.
/// Matches Python 1.2.5 `Interface.OP_FREQ_SAMPLES = 48`.
pub const OP_FREQ_SAMPLES: usize = 48;
/// Minimum non-zero announce frequency represented by the decay window.
pub const AR_MINFREQ_HZ: f64 = 0.1;
/// Minimum non-zero path-request frequency represented by the decay window.
pub const PR_MINFREQ_HZ: f64 = 0.1;
/// Frequency decay window for announces (seconds).
pub const AR_FREQ_DECAY: f64 = 1.0 / AR_MINFREQ_HZ;
/// Frequency decay window for path requests (seconds).
pub const PR_FREQ_DECAY: f64 = 1.0 / PR_MINFREQ_HZ;
/// Minimum samples required before frequency is considered defined.
/// Matches Python 1.2.4 `Interface.IC_DEQUE_MIN_SAMPLE = 32`.
pub const IC_DEQUE_MIN_SAMPLE: usize = 32;
/// Matches Python 1.2.5 `Interface.IC_DEQUE_MIN_SAMPLE = 2`.
pub const IC_DEQUE_MIN_SAMPLE: usize = 2;
/// Minimum samples required for burst state clearing / egress PR limiting.
/// Matches Python 1.2.5 `Interface.IC_BURST_MIN_SAMPLES = 6`.
pub const IC_BURST_MIN_SAMPLES: usize = 6;
/// Duration interface is treated as "new" (seconds).
/// Matches Python `Interface.IC_NEW_TIME = 2*60*60`.
pub const IC_NEW_TIME: f64 = 7200.0;
/// Burst threshold for new interfaces (announces/sec).
/// Matches Python 1.2.4 `Interface.IC_BURST_FREQ_NEW = 6`.
pub const IC_BURST_FREQ_NEW: f64 = 6.0;
/// Matches Python 1.2.5 `Interface.IC_BURST_FREQ_NEW = 3`.
pub const IC_BURST_FREQ_NEW: f64 = 3.0;
/// Burst threshold for established interfaces (announces/sec).
/// Matches Python 1.2.4 `Interface.IC_BURST_FREQ = 35`.
pub const IC_BURST_FREQ: f64 = 35.0;
/// Matches Python 1.2.5 `Interface.IC_BURST_FREQ = 10`.
pub const IC_BURST_FREQ: f64 = 10.0;
/// Path-request burst threshold for new interfaces (requests/sec).
pub const IC_PR_BURST_FREQ_NEW: f64 = 3.0;
/// Path-request burst threshold for established interfaces (requests/sec).
pub const IC_PR_BURST_FREQ: f64 = 8.0;
/// Burst detection active duration (seconds).
/// Matches Python `Interface.IC_BURST_HOLD = 1*60`.
pub const IC_BURST_HOLD: f64 = 60.0;
/// Matches Python 1.2.5 `Interface.IC_BURST_HOLD = 15`.
pub const IC_BURST_HOLD: f64 = 15.0;
/// Burst penalty delay (seconds).
/// Matches Python 1.2.4 `Interface.IC_BURST_PENALTY = 15`.
/// Matches Python 1.2.5 `Interface.IC_BURST_PENALTY = 15`.
pub const IC_BURST_PENALTY: f64 = 15.0;
/// Optional outgoing path-request limiter threshold (requests/sec).
pub const EC_PR_FREQ: f64 = 5.0;
/// Whether outgoing path-request limiting is active by default.
pub const EGRESS_CONTROL: bool = false;
/// Tunnel timeout (8 hours, in seconds).
/// Matches Python 1.1.6 `Transport.TUNNEL_TIMEOUT = 60*60*8`.
pub const TUNNEL_TIMEOUT: u64 = 28_800;
@@ -214,6 +281,10 @@ pub enum InterfaceMode {
AccessPoint,
Roaming,
Boundary,
/// Python 1.3.8 `MODE_INTERNAL` (Interface.py:51) — local/shared-instance
/// interfaces. Default path expiry (`path_expiry` wildcard arm) and a
/// discovery mode (`mode_discovers_unknown_paths`), like upstream.
Internal,
}
/// Which directions an interface carries traffic in.
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff. Show more