Compare commits

..
Author SHA1 Message Date
DeFiDude d9a1024a16 runtime: own finite announce discovery 2026-08-16 20:13:02 -06:00
DeFiDude bd8c2d8264 transport: isolate announce subscription ownership 2026-08-16 20:05:31 -06:00
DeFiDude b3bcd2b886 docs: distinguish Reticulum reference baselines 2026-08-16 18:41:18 -06:00
DeFiDude 31c5269695 runtime: preserve Rust 1.85 link cleanup syntax 2026-08-16 16:44:10 -06:00
DeFiDude 9300253cee link: keep invalid proof test pending 2026-08-16 16:44:06 -06:00
DeFiDude 0aeb4f02c9 runtime: cancel terminal pending Link binds 2026-08-16 16:31:59 -06:00
DeFiDude f66047e2a2 runtime: drain lifecycle before Link reuse 2026-08-16 16:27:46 -06:00
DeFiDude 3c527bd5cf runtime: fence Link cleanup generations 2026-08-16 16:20:10 -06:00
DeFiDude 2252b83470 transport: release atomic Link destinations on terminal drain 2026-08-16 16:13:35 -06:00
DeFiDude 1d38688b8f runtime: retain ordered Link cleanup ownership 2026-08-16 16:07:10 -06:00
DeFiDude 0049231139 docs: document established Link ownership 2026-08-16 15:41:16 -06:00
DeFiDude d1b5659169 runtime: bind all established Link owners 2026-08-16 15:40:32 -06:00
DeFiDude 2fd604b4aa transport: defer Link cleanup until teardown drains 2026-08-16 15:15:05 -06:00
DeFiDude a9d26472d0 link: ignore unauthenticated proof races 2026-08-16 15:13:54 -06:00
DeFiDude e43fefbc54 transport: drain Link teardown before unbind 2026-08-16 15:09:59 -06:00
DeFiDude e19944f6c1 transport: bound realtime Link egress 2026-08-16 15:00:27 -06:00
DeFiDude 921eac40c2 transport: bind established Links to exact interfaces 2026-08-16 14:56:51 -06:00
DeFiDude f7ae0274c3 link: enforce role-safe packet proofs 2026-08-16 14:54:59 -06:00
DeFiDude fbc2f1938b auto: retry multicast membership joins 2026-08-16 12:43:15 -06:00
DeFiDude 2e0d0a6888 transport: preserve ordered Link delivery outcomes 2026-08-14 13:49:37 -06:00
DeFiDude 6c77c9e69d transport: preserve BLE and Link delivery under pressure 2026-08-13 22:53:30 -06:00
DeFiDude 27352fd0d4 ble: fence reconnect writer leases 2026-08-13 21:58:44 -06:00
DeFiDude fd973420f2 rnode: gate feature-bound admission test 2026-08-13 15:09:01 -06:00
DeFiDude b12f331082 rnode: expose typed capability admission failure class 2026-08-13 14:56:29 -06:00
DeFiDude 04300ecdf4 rnode: admit unprovisioned eeprom images without model bounds 2026-08-13 14:56:17 -06:00
DeFiDude a1b78564e0 resource: bound split payload memory 2026-08-13 12:42:25 -06:00
DeFiDude 70b739988b android: harden native RNode recovery 2026-08-13 05:10:13 -06:00
DeFiDude 140d0aeed4 rncp: settle proven Resources before teardown 2026-08-13 00:44:54 -06:00
DeFiDude ec61a566d3 runtime: harden proof and Link control delivery 2026-08-12 23:58:10 -06:00
DeFiDude 1285e06cf6 ci: install PCSC headers for all-feature lint 2026-08-07 00:12:19 -06:00
DeFiDude bc419b109d ci: enforce strict Clippy across supported targets 2026-08-06 18:49:06 -06:00
DeFiDude eee619ef3b interfaces: align Android USB and RNodeMulti behavior 2026-08-06 14:59:18 -06:00
DeFiDude e47a1d4932 transport: bound control request admission 2026-08-05 13:38:33 -06:00
DeFiDude 07ca72179e runtime: clean Windows shared-instance build 2026-08-02 13:20:46 -06:00
DeFiDude d24e4e3ce3 runtime: simplify resource policy callback type 2026-08-02 01:04:20 -06:00
DeFiDude 869322fa80 transport: route same-runtime links internally 2026-07-28 15:57:03 -06:00
DeFiDude 2bce74c74c transport: document link timeout policy boundary 2026-07-27 03:41:15 -06:00
DeFiDude 8e58e1b708 transport: bound relay link proof lifetime 2026-07-27 03:38:34 -06:00
DeFiDude 7a187a7aa0 transport: centralize pending link proof deadlines 2026-07-27 03:35:46 -06:00
DeFiDude d424c96fa3 runtime: expose responder policy options 2026-07-27 00:09:19 -06:00
DeFiDude 6547f8370d runtime: carry default app data in announces 2026-07-27 00:00:02 -06:00
DeFiDude 740051c41e runtime: allow responder sends while links recover 2026-07-26 23:57:09 -06:00
DeFiDude 04db8c9f46 runtime: make link packet delivery lossless 2026-07-26 23:55:04 -06:00
DeFiDude 9928abed26 runtime: remove closed links from destinations 2026-07-26 23:17:28 -06:00
dude.eth 9e7dd7d9b6 Merge pull request #17 from ratspeak/feature/api-parity
runtime: complete application API parity and RNode hardening
2026-07-26 13:23:13 -06:00
DeFiDude 690c0faf05 tests: await RNode packet accounting completion 2026-07-26 13:17:20 -06:00
DeFiDude 5db4ca3eb5 tests: remove wall-clock delay from RNode fragments 2026-07-26 13:13:29 -06:00
DeFiDude 5d010fb6fb ci: restore MSRV and stabilise RNode preflight test 2026-07-26 13:09:35 -06:00
DeFiDude 7119f8019d release: prepare v1.1.0 2026-07-26 12:53:08 -06:00
DeFiDude df7c8decc1 ci: keep public rustdoc warning-free 2026-07-26 06:57:55 -06:00
DeFiDude 8c8ec46da8 docs: repair public API links 2026-07-26 06:55:43 -06:00
DeFiDude b2068105ae runtime: keep handle-drop shutdown quiet 2026-07-26 04:42:38 -06:00
DeFiDude fb250c7a83 rnsh: register protocol channel types 2026-07-26 04:42:33 -06:00
DeFiDude 52e501fcfc channel: isolate consumer callback panics 2026-07-26 02:19:47 -06:00
DeFiDude dabe75fbb5 link: expose established metric helpers 2026-07-26 02:18:30 -06:00
DeFiDude b9130e6002 identity: isolate persistence test storage 2026-07-26 02:15:47 -06:00
DeFiDude 126d974909 transport: order routing snapshot publication 2026-07-26 02:15:00 -06:00
DeFiDude f9b457d329 transport: reject foreign IFAC ingress 2026-07-26 02:11:21 -06:00
DeFiDude 93c4e3c4b1 runtime: make inbound Resource accounting terminal-safe 2026-07-25 21:02:17 -06:00
DeFiDude 5003e0ec8d runtime: add lossless Link accounting 2026-07-25 20:13:05 -06:00
DeFiDude ed58938c99 runtime: derive Link establishment timing 2026-07-25 19:34:54 -06:00
DeFiDude ac3239d221 runtime: enforce shared control authority 2026-07-25 19:24:09 -06:00
DeFiDude fc97b9931a runtime: stream exact RNode state 2026-07-25 18:25:57 -06:00
DeFiDude e7b76f8272 runtime: expose strict RNode startup options 2026-07-25 18:03:06 -06:00
DeFiDude ba2845e166 rnode: admit Android USB capabilities 2026-07-25 18:02:59 -06:00
DeFiDude f9bb83e089 rnode: admit BLE startup capabilities 2026-07-25 18:02:51 -06:00
DeFiDude 808430d26d rnode: gate startup on validated capabilities 2026-07-25 17:11:38 -06:00
DeFiDude 01fa84bf1f rnode: centralize capability admission 2026-07-25 16:41:27 -06:00
DeFiDude 52998569fb runtime: expose startup RNode observers 2026-07-25 16:20:48 -06:00
DeFiDude 5e310b7069 runtime: return exact observers from RNode spawns 2026-07-25 14:51:09 -06:00
DeFiDude 580ff63224 rnode: validate BLE and USB settings before I/O 2026-07-25 14:51:01 -06:00
DeFiDude 6f24711a38 runtime: expose exact RNode readiness observers 2026-07-25 14:35:53 -06:00
DeFiDude 12b43cebac rnodeconf: verify configuration transactions 2026-07-25 13:56:40 -06:00
DeFiDude 97193439db tools: fix SIGTERM persistence fixture 2026-07-25 13:54:16 -06:00
DeFiDude fb976c4bc3 rnode: restore Rust 1.85 compatibility 2026-07-25 13:51:56 -06:00
DeFiDude 6b79393f58 rnode: share validated radio settings 2026-07-25 13:21:49 -06:00
DeFiDude b9287b7ecf runtime: drain interfaces before transport shutdown 2026-07-25 13:13:00 -06:00
DeFiDude 76410efa50 runtime: retain exact RNode drivers 2026-07-25 12:15:36 -06:00
DeFiDude b671acd51b interface: reclaim rejected accepted children 2026-07-25 11:55:52 -06:00
DeFiDude 2aada8b4db runtime: own interface tasks per instance 2026-07-25 11:42:13 -06:00
DeFiDude 390146247d rnode: request exact driver shutdown 2026-07-25 03:29:48 -06:00
DeFiDude 31632d7a90 rnode: project Android USB lifecycle state 2026-07-25 03:12:35 -06:00
DeFiDude 4146eeb743 rnode: own Android USB teardown deterministically 2026-07-25 02:53:33 -06:00
DeFiDude 60a3b72146 rnode: expose native BLE lifecycle observations 2026-07-25 01:31:16 -06:00
DeFiDude 4e1abca4ea tools: share RNode capability inspection 2026-07-25 01:28:53 -06:00
DeFiDude b1854b62aa rnode: add bounded EEPROM capability parser 2026-07-25 01:14:33 -06:00
DeFiDude b59e8849a7 rnode: expose desktop BLE lifecycle observations 2026-07-25 01:10:24 -06:00
DeFiDude 88d3d38277 rnode: restore TCP application idle probes 2026-07-25 00:46:32 -06:00
DeFiDude b2aee9dc2c rnode: consume flow permits at write boundary 2026-07-25 00:14:16 -06:00
DeFiDude ba4ee2881f rnode: serialize generation writes and teardown 2026-07-24 23:50:28 -06:00
DeFiDude d6c3a010c0 rnode: project protocol readiness into driver state 2026-07-24 22:54:38 -06:00
DeFiDude 3cccd8c7b0 rnode: preserve negative protocol observations 2026-07-24 22:33:23 -06:00
DeFiDude 74eb9949cb rnode: expose local driver lifecycle snapshots 2026-07-24 22:24:58 -06:00
DeFiDude 731fddcf73 rnode: validate generic radio configuration 2026-07-24 22:04:54 -06:00
DeFiDude 6f43913a6c tools: render Backbone inspection counts 2026-07-24 21:37:56 -06:00
DeFiDude 987cc947c7 runtime: expose aggregate Backbone inspection stats 2026-07-24 21:35:30 -06:00
DeFiDude 1c7a0ea035 rnode: add deterministic protocol reducer 2026-07-24 21:19:19 -06:00
DeFiDude aeeb3c1ab9 backbone: block fast-flapping clients 2026-07-24 21:16:46 -06:00
DeFiDude 7100021b75 discovery: align RNS 1.4 defaults 2026-07-24 20:51:25 -06:00
DeFiDude 59d59d335a transport: adopt canonical raw packet hashlist 2026-07-24 20:51:12 -06:00
DeFiDude e3bb3d171f discovery: bound stamp validation load 2026-07-24 20:35:52 -06:00
DeFiDude 0362446b74 rnode: preserve Android USB control frames 2026-07-24 20:25:19 -06:00
DeFiDude 2ec94069a4 link: preserve asymmetric keepalive liveness 2026-07-24 20:15:50 -06:00
DeFiDude bb7395b284 packet: centralize destination-aware packing 2026-07-24 19:22:11 -06:00
DeFiDude 4ae8638b3e destination: own persistent ratchet runtime 2026-07-24 19:05:25 -06:00
DeFiDude 69d9e8a5b5 packet: add resend and receipt controls 2026-07-24 18:44:53 -06:00
DeFiDude 06a9bdd63f link: expose live physical metrics 2026-07-24 18:25:48 -06:00
DeFiDude ca9bcae376 api: close compatibility surface gaps 2026-07-24 18:07:41 -06:00
DeFiDude 2be764308e runtime: close responder handshake races 2026-07-24 15:22:26 -06:00
DeFiDude a72c1215c1 build: enforce Rust 1.85 API gates 2026-07-24 13:11:03 -06:00
DeFiDude a788ab984a link: expire zero-duration requests immediately 2026-07-24 12:51:47 -06:00
DeFiDude 2a67960f1d runtime: add build-checked API examples 2026-07-24 12:42:07 -06:00
DeFiDude 8370a1be66 runtime: own inbound destination lifecycles 2026-07-24 12:16:51 -06:00
DeFiDude 30b40d8333 runtime: route large link requests through resources 2026-07-24 12:09:32 -06:00
DeFiDude a319855c62 runtime: add destination Link connector 2026-07-24 11:48:46 -06:00
DeFiDude ee2b882a50 destination: report announce preconditions 2026-07-24 11:44:21 -06:00
DeFiDude 24b3dc3cbc runtime: pin responder links to interfaces 2026-07-24 11:40:40 -06:00
DeFiDude acc0a3f93b transport: expose next-hop link metrics 2026-07-24 11:38:02 -06:00
DeFiDude e663260b11 transport: expose path request options 2026-07-24 11:32:06 -06:00
DeFiDude 69fa830d52 runtime: apply forced shared-instance bitrate 2026-07-24 11:26:13 -06:00
DeFiDude d406d76b35 transport: use path response on shared registration 2026-07-24 11:19:04 -06:00
DeFiDude 9eed85392e runtime: align cache cleanup lifetimes 2026-07-24 11:16:59 -06:00
DeFiDude 82195eb2de runtime: dispatch destination request handlers 2026-07-24 11:13:52 -06:00
DeFiDude 1562d72ce1 link: expose plaintext request parsing 2026-07-24 10:59:47 -06:00
DeFiDude 8ae733e68a runtime: expose live Destination controls 2026-07-24 10:54:05 -06:00
DeFiDude 9b64aea819 runtime: add explicit shared-instance init options 2026-07-24 10:51:16 -06:00
DeFiDude d9f510a5ad destination: complete library API helpers 2026-07-24 10:43:44 -06:00
DeFiDude cd816bee68 identity: expose ratchet decryption metadata 2026-07-24 10:37:07 -06:00
DeFiDude 10ec9e9b3e runtime: activate Destination packet dispatch 2026-07-24 07:55:18 -06:00
DeFiDude 4830142458 runtime: add owned announce subscriptions 2026-07-24 07:40:58 -06:00
DeFiDude dfe42f2194 transport: honor unfiltered announce deregistration 2026-07-24 07:31:00 -06:00
DeFiDude 2bf531180e runtime: add channel-backed Buffer streams 2026-07-24 07:28:32 -06:00
DeFiDude f284317d8d channel: expose outbound drain state 2026-07-24 07:19:16 -06:00
DeFiDude e15466bfb8 runtime: expose responder resource lifecycle 2026-07-24 07:14:34 -06:00
DeFiDude 226f4fa800 runtime: expose responder resource policy 2026-07-24 07:02:12 -06:00
DeFiDude a1ca1daa39 runtime: add inbound Link resource offers 2026-07-24 06:54:08 -06:00
DeFiDude 062170c541 runtime: add Link session resource lifecycle 2026-07-24 06:22:11 -06:00
DeFiDude 8777f62a38 runtime: expose reliable Link session channels 2026-07-24 05:40:11 -06:00
DeFiDude 8645fdfacd channel: complete handler and MDU semantics 2026-07-24 05:24:07 -06:00
DeFiDude b9819d3d66 runtime: add Link session request API 2026-07-24 05:17:25 -06:00
DeFiDude 4220b8d3d7 runtime: add tracked packet send API 2026-07-24 05:06:14 -06:00
DeFiDude e5cbded53f wire: distinguish packet and Link payload limits 2026-07-24 04:54:37 -06:00
DeFiDude 8a8256cf1c runtime: expose typed interface stats 2026-07-24 04:35:16 -06:00
DeFiDude 1605709a48 runtime: add typed path queries 2026-07-24 04:31:40 -06:00
DeFiDude a945ba0744 runtime: add keyed destination recall 2026-07-24 04:24:25 -06:00
DeFiDude 0c71ce1e09 runtime: drive resource watchdogs 2026-07-24 04:17:06 -06:00
DeFiDude d986749660 resource: retry lost advertisements 2026-07-24 04:11:59 -06:00
DeFiDude 065741d22b link: drive request receipt lifecycle 2026-07-24 04:10:34 -06:00
DeFiDude 6e12be1489 interface: reconnect Unix shared clients 2026-07-24 04:05:32 -06:00
DeFiDude ea9163338f runtime: await orderly signal shutdown 2026-07-24 03:58:56 -06:00
DeFiDude a9d3d7998f transport: authenticate delivery proofs 2026-07-24 03:48:23 -06:00
DeFiDude 25c5e448cf runtime: test stale link heartbeat recovery 2026-07-23 13:26:12 -06:00
DeFiDude 9b909c2093 runtime: pin persistent links to proof interface 2026-07-23 12:30:47 -06:00
DeFiDude d90f9390ca runtime: allow packets while links recover 2026-07-23 11:45:06 -06:00
DeFiDude 739e30d3da rnsh: preserve live authorization semantics 2026-07-21 21:26:33 -06:00
DeFiDude 44d8a13c62 rnid: register one-shot announce destinations 2026-07-21 20:30:20 -06:00
DeFiDude e8819edc3c runtime: add persistent application Link sessions 2026-07-21 18:52:08 -06:00
DeFiDude 3f8feb169c rnode: fix battery and temperature decoding 2026-07-21 16:28:09 -06:00
DeFiDude a79b9b3210 runtime: satisfy strict link cleanup lint 2026-07-21 13:28:17 -06:00
DeFiDude 8ac58e5f5e identity: replace state atomically on Windows 2026-07-20 17:33:42 -06:00
DeFiDude 670875008d identity: expose exact tagged path responses 2026-07-20 17:23:58 -06:00
DeFiDude f853086237 identity: make ratchet rotation crash-safe 2026-07-20 17:15:04 -06:00
DeFiDude 36fcfeb953 identity: verify atomic state persistence 2026-07-20 16:59:12 -06:00
DeFiDude 7267bd4f69 identity: preserve ratchet flag in path-response cache 2026-07-20 16:55:53 -06:00
DeFiDude 4095022ea6 rnsh: harden listener state model and add auth-bypass regression tests 2026-07-19 13:28:39 -06:00
DeFiDude c4c9f14448 runtime: gate request-resources, tear down invalid advertisements, route HMU cancels 2026-07-19 13:28:39 -06:00
DeFiDude 141a6e8889 resource: gate solicited HMUs and cancel on empty or invalid updates 2026-07-19 13:28:39 -06:00
DeFiDude 4509145b70 link: enforce first-verified-identity-wins on established links 2026-07-19 13:28:39 -06:00
DeFiDude 17e6107aa8 interface: refresh ble_peer module doc — no ID characteristic 2026-07-18 19:58:02 -06:00
DeFiDude c4b1301e6f interface: drop vestigial ble_peer feature alias (ble gates all BLE deps) 2026-07-17 08:38:48 -06:00
DeFiDude c65ce4c430 ratkey: drop internal hardware status ledger from the public tree 2026-07-17 08:38:11 -06:00
DeFiDude 27e6d03235 docs: retarget README to Reticulum 1.3.8 2026-07-17 08:38:11 -06:00
DeFiDude 6c8dba7dd4 tools: bump emulated Reticulum compat version to 1.3.8 2026-07-15 20:39:49 -06:00
DeFiDude 87ac41d93c style: rustfmt 2026-07-15 19:06:26 -06:00
DeFiDude ef1ff3f90c parity: 1.3.8 wave 3 — local_hops_delta (1.3.7 semantics) + logtimestamps in all binaries 2026-07-15 13:35:38 -06:00
DeFiDude 0baf1b4ad6 parity: 1.3.8 wave 2 — msgpack shared-instance RPC, config plumbing for new interface/identity/blackhole/logging keys, rnstatus monitor+internal mode 2026-07-15 12:40:20 -06:00
DeFiDude 3c1b43d8f6 parity: 1.3.8 wave 1 — transport announce/hop/mode/identity/blackhole, link stats, weave board-init, rnid signed messages 2026-07-15 11:18:41 -06:00
DeFiDude 46b699af1f tools: align prettysize output and rnprobe/rnpath default waits with Python, refresh README usage 2026-07-10 18:10:09 -05:00
DeFiDude 7d38b3f8d9 transport: prune on-disk announce cache against live references 2026-07-10 01:36:39 -05:00
DeFiDude 05f38400b9 runtime: inherit listener IFAC on accepted server children 2026-07-09 23:48:08 -05:00
DeFiDude 4aa505a7b6 interface: clear linux ble_peer clippy lints 2026-07-09 21:35:56 -05:00
DeFiDude 4afefd6bba interface: gate poll_read behind serial feature 2026-07-09 21:27:19 -05:00
DeFiDude 7e178ce8c4 test(rns-runtime): supply multipoint arg at interface registration test sites 2026-07-02 23:24:32 -06:00
DeFiDude ceafedd4ee style(ble-peer): rustfmt normalize 2026-07-02 02:08:02 -06:00
DeFiDude cbb0fc83bc feat(ble-peer): cross-platform mesh peer disconnect helper 2026-07-01 21:51:47 -06:00
DeFiDude 2336f166d7 chore: update Cargo.lock for rns-interface rns-identity dep 2026-07-01 21:47:19 -06:00
DeFiDude 011da1459c perf(ble-peer): scan/fan-out robustness pass
- RSSI-sort connect candidates so crowded rooms fill slots with nearest peers
- idle scan cadence when no actionable (unconnected/non-backoff) peer remains
- fan-out uses try_send so one slow peer can't head-of-line-block the broadcast
- bound per-peer btleplug writes with a timeout
- prune finished per-peer task handles instead of growing the vec per reconnect
- run blocking Android JNI disconnects off the async runtime
2026-07-01 21:47:11 -06:00
DeFiDude fade1f2e47 fix(ble-peer): stop advertising plaintext app name on Linux 2026-07-01 21:39:42 -06:00
DeFiDude 5e213f75cf fix(ble-peer): drop static identity-hash GATT read (MAC-rotation tracking vector) 2026-07-01 21:39:17 -06:00
DeFiDude a5ab014510 fix(ble-peer): bind peer identity only from a signature-verified announce 2026-07-01 21:30:53 -06:00
DeFiDude 198564c65d fix(ble-peer): engage backoff on connect-drop churn; stop rotation misclassification
Generic remote disconnects were classified as RPA rotation and cleared the
reconnect backoff on every drop; a churn tracker now backs off peers that keep
connecting and dropping within the stability window.
2026-07-01 21:22:59 -06:00
DeFiDude 24fc3e2912 fix(ble-peer): preserve Apple write order under radio backpressure 2026-07-01 21:16:03 -06:00
DeFiDude 20ad6061d8 fix(ble-peer): size writes to the real MTU to stop silent truncation
Apple central now reads maximumWriteValueLengthForType: (fixes truncation on
smaller-MTU links and unlocks larger writes); btleplug drops to the iOS-safe
182-byte floor since it exposes no MTU getter and there is no length field.
2026-07-01 21:14:24 -06:00
DeFiDude 7fb33dc83d fix(ble-peer): track real interface online state for transport + Halt/Resume 2026-07-01 21:11:39 -06:00
DeFiDude f2751f4b57 fix(transport): relay announces among peers of a multipoint interface
BLE Peer presents many hidden-from-each-other GATT links as one interface;
without back-out relay a hub never propagates announces between its peers,
breaking multi-hop discovery past two nodes.
2026-07-01 21:09:07 -06:00
DeFiDude 7d5ee2121d docs(ble-peer): correct false anti-loop claim on desktop notify legs 2026-07-01 21:02:49 -06:00
DeFiDude 1f6865c996 fix(ble-peer): correct central-role teardown (reset Apple scan lifecycle, disconnect desktop GATT links) 2026-07-01 20:59:48 -06:00
DeFiDude 753b49b83c fix(ble-peer): re-settable Apple peripheral manager across enable cycles 2026-07-01 20:49:30 -06:00
DeFiDude e9169eecbd fix(ble-peer): cap fragment reassembly total to bound memory use 2026-07-01 20:46:50 -06:00
DeFiDude 6d2b284753 ci: run BLE feature tests on macOS 2026-07-01 19:32:34 -06:00
DeFiDude 468d330322 transport: deflake periodic-save test by modeling tick retry 2026-07-01 19:08:06 -06:00
DeFiDude be3ac91d8a protocol: fix resource window-grow underflow after demote-then-promote 2026-07-01 18:48:25 -06:00
DeFiDude 936f19a200 docs: update Reticulum compatibility target 2026-07-01 01:57:31 -06:00
DeFiDude b9522bfab1 rnode: avoid duplicate BLE airtime init 2026-06-30 20:06:25 -06:00
DeFiDude e6dd6b3ab3 rnode: reset radio before init sequence 2026-06-17 10:30:01 -06:00
DeFiDude 3b91b36f3e runtime: group backbone IFAC spawn options 2026-06-13 23:27:57 -06:00
DeFiDude 3d7b989262 release: bump rsReticulum to 1.0.1 2026-06-13 23:21:14 -06:00
DeFiDude fdfbf09515 tools: report package version from CLIs 2026-06-13 23:12:57 -06:00
DeFiDude 5bfbcef47f runtime: add IFAC spawn support 2026-06-13 22:54:25 -06:00
DeFiDude 117f32e03e ci: satisfy release branch clippy 2026-06-13 21:51:02 -06:00
DeFiDude 07f0ecd900 release: align crates at 1.0.0 2026-06-13 21:40:21 -06:00
DeFiDude 4b8bc21a9b style: rustfmt transport cleanup 2026-06-13 19:56:34 -06:00
DeFiDude 6638c80c55 transport: skip path requests for outbound proofs 2026-06-13 19:56:20 -06:00
DeFiDude d2ad997caf rnode: trace queued packet writes 2026-06-13 19:56:08 -06:00
DeFiDude d8ff9f85b7 transport: disk-backed announce cache, 5-min state flush, cleanup linger parity 2026-06-12 11:50:14 -06:00
DeFiDude 069b653ee6 ble: run pairing read before subscribe on Android 2026-06-10 21:25:37 -06:00
DeFiDude 4158c5a8a9 transport: move periodic and falling-edge state flushes off the actor 2026-06-10 13:49:10 -06:00
DeFiDude ed66c62468 tools: register rncp and rnsh signal handlers before runtime init 2026-06-10 12:27:16 -06:00
DeFiDude f5ec2fb16f lifecycle: register SIGINT handler synchronously; de-flake listener signal tests 2026-06-10 04:34:46 -06:00
DeFiDude 01d0bb411b perf: gate debug hex in auto hot paths, snapshot peer fan-out, persistent rnsd log handle, single-pass receipt cull 2026-06-10 00:04:29 -06:00
DeFiDude 41587f80de interface, ratkey: remove dead trait and constants, wire pin re-verify with zeroized buffers 2026-06-09 23:57:12 -06:00
DeFiDude 83710bc24a runtime: extract shared-instance client adoption helper 2026-06-09 23:45:22 -06:00
DeFiDude 69b5f40d2d local: shared stream wiring for unix and tcp-fallback variants 2026-06-09 23:43:16 -06:00
DeFiDude 7d749a4f8b link: collapse prove and identify variants onto fallible cores 2026-06-09 23:40:02 -06:00
DeFiDude 51f4e56002 interface: shared blocking serial io shuttles 2026-06-09 23:38:04 -06:00
DeFiDude 72e49affa0 kiss: classic deframer delegates to raw engine 2026-06-09 23:33:04 -06:00
DeFiDude 8ead1d477c interface: generic socket tuning helpers over raw fd borrow 2026-06-09 23:31:43 -06:00
DeFiDude b27a7ce69f i2p: consolidate reconnect backoff into pacer and dereg on give-up 2026-06-09 23:29:38 -06:00
DeFiDude 5460f013f8 transport, tools: consolidate now_f64 and compat-version constants 2026-06-09 23:26:56 -06:00
DeFiDude 442c9441a0 runtime: validate config ports and ifac_size, wire udp device, dereg tcp on initial give-up 2026-06-09 23:21:36 -06:00
DeFiDude a5dcd3caf7 interface: flip shared online flag on deregister and scope rnode-multi subs independently 2026-06-09 23:14:45 -06:00
DeFiDude 8a41710550 tcp: apply tuned keepalive and user timeout on client, accepted, and i2p sockets 2026-06-09 23:03:59 -06:00
DeFiDude 3fd3fa9077 rnode: apply RSSI offset when decoding signal stats 2026-06-09 22:59:37 -06:00
DeFiDude 2262f9ee7e transport: route table persistence through shared fsync atomic-write helper 2026-06-09 22:56:53 -06:00
DeFiDude f0b564be0b protocol: bound hashmap-update segment writes by total_parts 2026-06-09 22:54:32 -06:00
DeFiDude 366ca6f02a protocol: bound inbound resource part count against advertised size 2026-06-09 22:52:16 -06:00
DeFiDude ac98369011 auto: tolerate transient recv errors in discovery and data loops 2026-06-09 20:58:34 -06:00
DeFiDude 849c23e624 ble: update rnode tests for init-sequence airtime and flow-control parity 2026-06-09 18:28:06 -06:00
DeFiDude db47d10d5a lint: rustfmt and clippy cleanup 2026-06-09 18:21:53 -06:00
DeFiDude a5f06b6d00 interfaces: config-key parity, station-ID beacons, explicit radio params 2026-06-09 17:45:05 -06:00
DeFiDude b0cfa3be78 identity: derive Clone/Copy on ReceivedRatchet 2026-06-09 17:45:05 -06:00
DeFiDude 72ad363435 runtime: support live RNode interface modes 2026-06-08 18:17:01 -06:00
DeFiDude bb2c1eab65 ble: satisfy peer feature clippy 2026-06-03 23:58:52 -06:00
DeFiDude 21aa4f6308 ble: redundantly fan out proof packets 2026-06-03 23:07:22 -06:00
DeFiDude f9b407ef5a ble: suppress peer role collisions 2026-06-03 20:50:46 -06:00
DeFiDude 924d27f4b1 interface: expose Android BLE availability 2026-06-03 15:53:17 -06:00
DeFiDude 36706c1eff interface: emit BLE peer status events 2026-06-03 15:46:14 -06:00
DeFiDude 5a0ea04ad0 runtime: seed BLE reconnects by address 2026-06-03 15:41:15 -06:00
DeFiDude 104f425b4f interface: prefer single BLE peer path 2026-06-03 15:34:48 -06:00
DeFiDude c3b75f7577 interface: key BLE peer writers 2026-06-03 15:31:37 -06:00
DeFiDude c460a7c9d4 interface: reset BLE peer sessions cleanly 2026-06-03 15:26:31 -06:00
DeFiDude 27f901ec5d tests: move interop generator to harness 2026-05-30 21:07:59 -06:00
DeFiDude ab529e875c runtime: support legacy Python RPC auth 2026-05-30 20:37:08 -06:00
DeFiDude 7942aee235 tests: track Python artifact generator 2026-05-30 17:24:06 -06:00
DeFiDude cd58bbc0ac ratkey: satisfy clippy 2026-05-29 23:52:58 -06:00
DeFiDude 4ee47d40ac style: apply rustfmt 2026-05-29 23:49:09 -06:00
DeFiDude a8daa46958 ratkey: switch recoverable phrases to 12 words 2026-05-29 22:52:53 -06:00
DeFiDude eeb3e4589a ratkey: add PIV PIN recovery support 2026-05-29 22:38:34 -06:00
DeFiDude 132d7a2d79 runtime: route backend link signing 2026-05-29 20:28:47 -06:00
DeFiDude 27beef4564 ratkey: extract testable APDU response-chaining fn + unit tests 2026-05-29 19:24:41 -06:00
DeFiDude 6cd28f0337 ratkey: hardware-validate attestation chain (on-card ATTEST + F9 fetch, response chaining, hw attest) 2026-05-29 19:18:26 -06:00
DeFiDude 4f011314d4 ratkey: document recovery-phrase re-display (persisted, protection tracks the key) 2026-05-29 18:59:49 -06:00
DeFiDude 88677cef2f ratkey: implement TDES (3DES EDE3) management keys for pre-5.7 YubiKeys 2026-05-29 18:41:43 -06:00
DeFiDude 6181a18254 ratkey: document recoverable-identity model (seed-restore, mnemonic create, passcode vault) 2026-05-29 16:15:18 -06:00
DeFiDude dda2470987 ratkey: document desktop-only release scope + mobile/seed-restore plan 2026-05-29 14:52:35 -06:00
DeFiDude 6c9792846e ratkey: add backend lock() to drop the on-card PIN cache 2026-05-29 10:37:52 -06:00
DeFiDude cc8927f0f9 ratkey: provision_hardware_only + read_existing helpers
Shared finalize_provision builds the .hwid for all real flows; provision_hardware_only generates on-device, read_existing registers an already-provisioned token.
2026-05-29 00:26:17 -06:00
DeFiDude a4083bd4fe ratkey: PIV key import + recoverable provisioning/restore
IMPORT ASYMMETRIC KEY APDU (Ed25519 tag 0x07 / X25519 0x08) + PivSession import methods (mgmt-key gated). provision_recoverable derives from a fresh 24-word phrase and imports both keys; restore does the same from an existing phrase. Mirrors ratkey-py's import path.
2026-05-29 00:07:25 -06:00
DeFiDude ad279dfb67 ratkey: BIP-39 seed-phrase identity derivation
24-word mnemonic -> deterministic Reticulum identity (scheme v1: PBKDF2-SHA512 seed -> HKDF-SHA256), verified byte-for-byte against ratkey-py. Foundation for recoverable hardware-key backup.
2026-05-29 00:01:44 -06:00
DeFiDude 1c63de4e0f rns-runtime: optional link signing key for hardware identities
LinkManager::with_destination takes Option<Ed25519PrivateKey>; hardware identities pass None (link-mode packet proofs skip until routed through the backend, TODO). Software callers wrap Some(...). Opportunistic delivery is unaffected.
2026-05-28 23:19:38 -06:00
DeFiDude a475caf407 ratkey: Identity LocalKeyBackend seam + hardware-backed identity
Identity gains an optional LocalKeyBackend (Ed25519 sign + X25519 ECDH delegation, used only when the in-memory key is absent; None for software identities, so wire output is unchanged). rns-ratkey HardwareBackend runs the PIV session on a card-service thread (Send+Sync) and load_hardware_identity builds an Identity::from_backend. Backend-aware Identity::clone keeps both clone_identity sites working for hardware (Arc-shared) without extracting a private key.
2026-05-28 23:10:52 -06:00
DeFiDude f6afe585ce ratkey: X.509 attestation chain verification
RSA PKCS#1 v1.5 chain from the per-key/F9 attestation certs to a fingerprint-pinned Yubico root (legacy + new-PKI A/B/B2 intermediates bundled) with validity-window checks. chain_verified is set only on a real signature verification; no revocation/OCSP/name-constraints. Pending validation against a physical device's ATTEST output.
2026-05-28 23:10:52 -06:00
DeFiDude 4623436c93 ratkey: PIV management-key auth for on-device provisioning
Witness/challenge mutual auth on slot 9B (AES-128/192/256; 5.7 default is AES-192) gates GENERATE, so hw provision now creates keys on-device. TDES (pre-5.7) left as a TODO. Validated end-to-end on a YubiKey 5.7.4.
2026-05-28 22:20:56 -06:00
DeFiDude fac4dc870d ratkey: PivTransport seam; back HardwareIdentity by real PIV session
PivSession<T> is transport-agnostic (PC/SC behind `hardware`); HardwareIdentity holds Box<dyn IdentityBackend>, ending the mock-only runtime and leaving room for a mobile transport. hw provision still lacks PIV management-key auth.
2026-05-28 21:59:37 -06:00
dude.eth 4e427a7ad5 Merge pull request #7 from kujeger/bzip2_vers
update bzip2 depencency
2026-05-28 20:18:06 -06:00
Nikolai Vincent Vaags a65fd2097f update bzip2 depencency
bzip2 0.6 (latest) is also fully in rust, making it easier to cross-compile.
2026-05-28 15:28:49 +02:00
DeFiDude 26e4919ce1 transport: align announce replay with upstream 2026-05-26 19:45:10 -06:00
DeFiDude bfb4bb4e14 transport: stop shared client announce replay 2026-05-26 19:19:05 -06:00
DeFiDude 8263bfbf4a tests: cover shared instance lifecycle edges 2026-05-24 23:51:37 -06:00
DeFiDude da56d5559a runtime: harden shared instance lifecycle 2026-05-24 22:59:36 -06:00
dude.eth 6e11324b6b Merge pull request #5 from strijar/fix/rnsd_log
Disable ansi for log file
2026-05-24 12:20:20 -06:00
Belousov Oleg b89e434a00 Disable ansi for log file 2026-05-20 15:34:16 +03:00
162 changed files with 76621 additions and 7940 deletions

No files matched your search

+31 -8
View File
@@ -26,12 +26,14 @@ jobs:
cache-bin: false
- name: Install system deps (Linux)
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev libpcsclite-dev pkg-config
- name: Test (default features)
run: cargo test --workspace
- name: Test BLE interface features (Linux)
if: runner.os == 'Linux'
run: cargo test -p rns-interface --features ble,ble_peer
run: cargo test --workspace --locked
- name: Build application examples
run: cargo build -p rns-runtime --examples --locked
- name: Test BLE interface features (Linux/macOS)
if: runner.os != 'Windows'
run: cargo test -p rns-interface --features ble --locked
lint:
name: Lint
@@ -43,7 +45,28 @@ jobs:
with:
components: clippy, rustfmt
- name: Install system deps
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev libpcsclite-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 --workspace --all-targets --all-features --locked -- -D warnings
- name: Check public API documentation
env:
RUSTDOCFLAGS: "-D warnings"
run: cargo doc --workspace --no-deps --locked
- run: cargo check --workspace --no-default-features --locked
msrv:
name: Rust 1.85 MSRV
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@1.85.0
with:
components: clippy
- uses: Swatinem/rust-cache@v2
with:
cache-bin: false
- name: Install system deps
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev libpcsclite-dev pkg-config
- name: Clippy (all targets and features)
run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
+1 -1
View File
@@ -6,4 +6,4 @@ __pycache__/
/interop_artifacts/
/rust_artifacts/
proptest-regressions/
/tools/
/tools/*
+43
View File
@@ -0,0 +1,43 @@
# Changelog
## Unreleased
- Isolate exact announce subscriptions from legacy aspect-wide deregistration,
and resolve finite destination identities through validated recall plus
deadline-bounded path discovery instead of temporary announce handlers.
- Distinguished the Reticulum 1.3.8 compatibility-floor corpus from the
current 1.4.2 behavior reference instead of presenting the old oracle as the
newest upstream target.
- Enforce role-specific Link packet proofs: initiators sign with the transient
LINKREQUEST key, responders sign with the destination identity, and external
identity backends no longer fall back to an unrelated key.
- Ignore unauthenticated invalid LRPROOF candidates without closing a pending
initiator, allowing the authentic proof to win an interface race.
- Bind every locally owned established Link endpoint to its validated
interface and role, with fail-closed routing, bounded ordered control egress,
terminal interface-loss notification, and bounded best-effort realtime
egress. Typed send rejection closes only the exact owner, while final
LINKCLOSE and temporary-destination cleanup drain atomically in order.
Initial LINKREQUEST discovery remains path-routed or broadcast.
- Forward authenticated non-Link packet delivery proofs from `LinkManager` to
owning applications through a lossless completion channel.
- Retain and retry destination announcements, including path responses, when
the bounded transport ingress is temporarily saturated.
- Let one-shot Link clients reuse a validated cached identity when its route is
still live, matching Python recall behavior and avoiding redundant path
discovery.
- Keep completed `rncp` Links alive for Python's receiver-side Resource
conclusion callback before sending the authenticated teardown.
## 1.1.0 - 2026-07-26
- Added application-facing Destination, announce, receipt, Link, request,
Channel, Buffer, and Resource APIs.
- Added resilient long-running Link sessions with recovery, liveness,
cancellation, progress, metrics, and responder lifecycle support.
- Hardened delivery proofs, shared-instance authority and reconnection, IFAC
ingress, persistence, routing snapshots, and orderly shutdown.
- Expanded RNode lifecycle, capability, BLE, USB, TCP, serial, and safe
`rnodeconf-rs` support.
- Added compiled examples and stricter MSRV, Clippy, interoperability, and
public-documentation gates.
Generated
+270 -42
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"
@@ -1026,6 +1074,12 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "libm"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
@@ -1062,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"
@@ -1111,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"
@@ -1122,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"
@@ -1129,6 +1229,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
"libm",
]
[[package]]
@@ -1230,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"
@@ -1256,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"
@@ -1461,7 +1582,7 @@ dependencies = [
[[package]]
name = "rns-crypto"
version = "0.9.4"
version = "1.1.0"
dependencies = [
"aes",
"cbc",
@@ -1482,7 +1603,7 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "0.9.4"
version = "1.1.0"
dependencies = [
"hex",
"proptest",
@@ -1492,14 +1613,16 @@ dependencies = [
"rns-crypto",
"rns-wire",
"serde",
"serde_bytes",
"thiserror 2.0.18",
"tracing",
"windows-sys 0.61.2",
"zeroize",
]
[[package]]
name = "rns-interface"
version = "0.9.4"
version = "1.1.0"
dependencies = [
"bluer",
"btleplug",
@@ -1509,11 +1632,13 @@ dependencies = [
"if-addrs",
"jni",
"libc",
"md-5",
"objc2",
"objc2-core-bluetooth",
"objc2-foundation",
"rand 0.8.5",
"rns-crypto",
"rns-identity",
"rns-transport",
"rns-wire",
"serde",
@@ -1529,7 +1654,7 @@ dependencies = [
[[package]]
name = "rns-link"
version = "0.9.4"
version = "1.1.0"
dependencies = [
"hex",
"proptest",
@@ -1545,7 +1670,7 @@ dependencies = [
[[package]]
name = "rns-protocol"
version = "0.9.4"
version = "1.1.0"
dependencies = [
"bzip2",
"hex",
@@ -1562,27 +1687,38 @@ dependencies = [
[[package]]
name = "rns-ratkey"
version = "0.9.4"
version = "1.1.0"
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.4"
version = "1.1.0"
dependencies = [
"bytes",
"hex",
"hmac",
"md-5",
"nix 0.29.0",
"rmp-serde",
"rmpv",
@@ -1603,7 +1739,7 @@ dependencies = [
[[package]]
name = "rns-tools"
version = "0.9.4"
version = "1.1.0"
dependencies = [
"base64",
"bytes",
@@ -1630,7 +1766,7 @@ dependencies = [
[[package]]
name = "rns-transport"
version = "0.9.4"
version = "1.1.0"
dependencies = [
"bytes",
"hex",
@@ -1650,7 +1786,7 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "0.9.4"
version = "1.1.0"
dependencies = [
"proptest",
"rns-crypto",
@@ -1658,6 +1794,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"
@@ -1811,6 +1968,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"
@@ -1831,12 +1999,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"
@@ -1853,6 +2015,7 @@ version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
dependencies = [
"digest",
"rand_core 0.6.4",
]
@@ -1888,6 +2051,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"
@@ -2022,6 +2191,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"
@@ -2200,6 +2405,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"
@@ -2753,6 +2967,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"
+14 -11
View File
@@ -14,7 +14,7 @@ members = [
]
[workspace.package]
version = "0.9.4"
version = "1.1.0"
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"] }
@@ -40,13 +42,14 @@ base64 = "0.22"
rmp-serde = "1"
rmpv = "1"
serde = { version = "1", features = ["derive"] }
serde_bytes = "0.11"
serde_json = "1"
# Async
tokio = { version = "1", features = ["full"] }
# Compression
bzip2 = "0.5"
bzip2 = "0.6"
# Serial
serialport = { version = "4", default-features = false }
@@ -77,12 +80,12 @@ nix = { version = "0.29", features = ["term", "fs"] }
proptest = "1"
# Workspace crates
rns-crypto = { path = "crates/rns-crypto", default-features = false }
rns-wire = { path = "crates/rns-wire", default-features = false }
rns-identity = { path = "crates/rns-identity" }
rns-transport = { path = "crates/rns-transport" }
rns-link = { path = "crates/rns-link" }
rns-protocol = { path = "crates/rns-protocol" }
rns-interface = { path = "crates/rns-interface" }
rns-runtime = { path = "crates/rns-runtime" }
rns-ratkey = { path = "crates/rns-ratkey" }
rns-crypto = { path = "crates/rns-crypto", version = "1.1.0", default-features = false }
rns-wire = { path = "crates/rns-wire", version = "1.1.0", default-features = false }
rns-identity = { path = "crates/rns-identity", version = "1.1.0" }
rns-transport = { path = "crates/rns-transport", version = "1.1.0" }
rns-link = { path = "crates/rns-link", version = "1.1.0" }
rns-protocol = { path = "crates/rns-protocol", version = "1.1.0" }
rns-interface = { path = "crates/rns-interface", version = "1.1.0" }
rns-runtime = { path = "crates/rns-runtime", version = "1.1.0" }
rns-ratkey = { path = "crates/rns-ratkey", version = "1.1.0" }
+37 -12
View File
@@ -7,7 +7,8 @@
[![License: AGPL-3.0-or-later](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue.svg)](LICENSE)
[![Rust 1.85+](https://img.shields.io/badge/rust-1.85%2B-orange.svg)](https://www.rust-lang.org)
[![Reticulum 1.2.5](https://img.shields.io/badge/target-Reticulum%201.2.5-success.svg)](https://reticulum.network/)
[![Compatibility floor: Reticulum 1.3.8](https://img.shields.io/badge/compatibility%20floor-Reticulum%201.3.8-success.svg)](https://reticulum.network/)
[![Current reference: Reticulum 1.4.2](https://img.shields.io/badge/current%20reference-Reticulum%201.4.2-blue.svg)](https://github.com/markqvist/Reticulum)
[![Status](https://img.shields.io/badge/status-experimental-yellow.svg)](#feature-status)
[Reticulum Manual](https://reticulum.network/manual/) |
@@ -116,14 +117,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 +132,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 +151,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 +175,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 +187,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,18 +253,37 @@ instance_control_port = 37433
| BLE RNode | Config-backed with the `ble` feature. |
| Bluetooth Peer | Runtime API used by Ratspeak. |
| Android USB-OTG | Runtime API for Android app embeddings. |
| Weave | Not implemented. |
| Weave | Partial: interface driver implemented, not yet config-wired in the runtime. |
| Bluetooth Classic RFCOMM | Not implemented. |
## Established Link Routing
An initial Link Request uses normal Reticulum path discovery and may be
broadcast when no path is known. Once the responder accepts that request and
the initiator validates its proof, each local Link endpoint is bound to the
exact interface and role selected by the handshake. Later Link packets,
Channels, Resources, proofs, keepalives, and teardown never fall back to a
different path or interface; loss of the selected interface closes that Link.
Reliable Link control uses a bounded ordered queue, while realtime media has a
separate bounded best-effort path that cannot overtake retained control
traffic. Initiator packet proofs use the temporary signing key advertised in
the Link Request, and responder packet proofs use the accepting destination
identity.
## Compatibility Notes
Most daemon and utility flows are implemented for the public `*-rs` tools:
`rnsd-rs`, `rnstatus-rs`, `rnpath-rs`, `rnid-rs`, `rnprobe-rs`, `rncp-rs`,
`rnsh-rs`, and `rnodeconf-rs`.
The current compatibility target is Reticulum 1.2.4 where the matching Rust
surface is implemented and tested. `rnid-rs` has explicit 1.2.4 coverage for
the normal identity utility flow.
The compatibility floor is Reticulum 1.3.8 where the matching Rust surface is
implemented and tested, including version-specific utility and byte-exact
fixtures. Current protocol and daemon behavior is also audited and
interoperability-tested against Reticulum 1.4.2. The older corpus remains
deliberate backward-compatibility evidence rather than a claim that 1.3.8 is
the newest upstream. `rnid-rs` has explicit 1.3.8 coverage for the normal
identity utility flow.
Known gaps and intentional limits:
+1
View File
@@ -3,6 +3,7 @@ name = "rns-crypto"
description = "Cryptographic primitives for Reticulum"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[features]
+33 -3
View File
@@ -2,14 +2,25 @@
use alloc::vec::Vec;
use thiserror::Error;
use zeroize::Zeroizing;
use crate::aes_cbc;
use crate::hmac::{hmac_sha256, hmac_verify};
use crate::pkcs7;
use crate::random::random_16;
use crate::random::{random_16, random_bytes};
/// IV (16) + HMAC (32). A token is this plus the PKCS7-padded ciphertext.
pub const TOKEN_OVERHEAD: usize = 48;
/// AES block size used by legacy AES-128 tokens.
pub const AES128_BLOCKSIZE: usize = 16;
/// AES block size used by current AES-256 tokens.
pub const AES256_BLOCKSIZE: usize = 16;
/// AES-256 token key size: 32-byte signing key + 32-byte encryption key.
pub const KEY_LENGTH: usize = 64;
/// Legacy AES-128 token key size: 16-byte signing key + 16-byte encryption key.
pub const LEGACY_KEY_LENGTH: usize = 32;
/// Python `Identity.DERIVED_KEY_LENGTH_LEGACY`.
pub const DERIVED_KEY_LENGTH_LEGACY: usize = LEGACY_KEY_LENGTH;
/// Errors surfaced by [`encrypt`] and [`decrypt`].
#[derive(Debug, Error)]
@@ -35,12 +46,17 @@ pub enum TokenError {
/// 64 → 32/32 (AES-256 + HMAC-SHA256); 32 → 16/16 (AES-128, legacy).
fn split_key(key: &[u8]) -> Result<(&[u8], &[u8]), TokenError> {
match key.len() {
64 => Ok((&key[..32], &key[32..])),
32 => Ok((&key[..16], &key[16..])),
KEY_LENGTH => Ok((&key[..32], &key[32..])),
LEGACY_KEY_LENGTH => Ok((&key[..16], &key[16..])),
n => Err(TokenError::InvalidKeyLength(n)),
}
}
/// Generate a fresh AES-256 token key with the operating-system CSPRNG.
pub fn generate_key() -> Zeroizing<Vec<u8>> {
Zeroizing::new(random_bytes(KEY_LENGTH))
}
/// Token encrypt (Modified Fernet — no version byte, no timestamp).
/// Wire: `IV(16) || AES-CBC(PKCS7(plaintext)) || HMAC-SHA256(IV || ciphertext)(32)`.
pub fn encrypt(plaintext: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
@@ -112,6 +128,20 @@ mod tests {
assert_eq!(&decrypted, plaintext);
}
#[test]
fn generated_key_is_valid_and_unique() {
let first = generate_key();
let second = generate_key();
assert_eq!(first.len(), KEY_LENGTH);
assert_eq!(second.len(), KEY_LENGTH);
assert_ne!(&*first, &*second);
assert_eq!(
decrypt(&encrypt(b"generated", &first).unwrap(), &first).unwrap(),
b"generated"
);
}
#[test]
fn test_encrypt_produces_correct_structure() {
let key = [0x42u8; 64];
+5
View File
@@ -3,6 +3,7 @@ name = "rns-identity"
description = "Identity, Destination, and Announce system for Reticulum"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[dependencies]
@@ -13,9 +14,13 @@ thiserror = { workspace = true }
rmp-serde = { workspace = true }
rmpv = { workspace = true }
serde = { workspace = true }
serde_bytes = { workspace = true }
rand = { workspace = true }
tracing = { workspace = true }
hex = { workspace = true }
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem"] }
[dev-dependencies]
proptest = { workspace = true }
+42 -7
View File
@@ -12,6 +12,9 @@ const RANDOM_HASH_SIZE: usize = 10;
const SIGNATURE_SIZE: usize = 64;
const RATCHET_SIZE: usize = 32;
/// Maximum value carried in the low five bytes of an announce random hash.
pub const ANNOUNCE_TIME_MAX: u64 = (1u64 << 40) - 1;
const MIN_ANNOUNCE_SIZE: usize = PUBKEY_SIZE + NAME_HASH_SIZE + RANDOM_HASH_SIZE + SIGNATURE_SIZE;
#[derive(Debug, Error)]
@@ -28,6 +31,8 @@ pub enum AnnounceError {
InvalidPublicKey,
#[error("hash collision detected for destination")]
HashCollision,
#[error("announce wire time exceeds 40-bit field: {0}")]
InvalidWireTime(u64),
}
/// Parsed announce data.
@@ -52,18 +57,33 @@ impl AnnounceData {
app_data: Option<&[u8]>,
ratchet_pub: Option<&[u8; 32]>,
) -> Result<Self, AnnounceError> {
let public_key = identity.get_public_key();
let nh = name_hash(app_name);
let random_bytes = rns_crypto::random::random_bytes(5);
let ts = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let ts_bytes = ts.to_be_bytes();
Self::create_at(identity, app_name, app_data, ratchet_pub, ts)
}
/// Create and sign an announce with an explicit persisted 40-bit ordering
/// value. Rotation and expiry clocks must be managed separately.
pub fn create_at(
identity: &Identity,
app_name: &str,
app_data: Option<&[u8]>,
ratchet_pub: Option<&[u8; 32]>,
wire_time: u64,
) -> Result<Self, AnnounceError> {
if wire_time > ANNOUNCE_TIME_MAX {
return Err(AnnounceError::InvalidWireTime(wire_time));
}
let public_key = identity.get_public_key();
let nh = name_hash(app_name);
let random_bytes = rns_crypto::random::random_bytes(5);
let ts_bytes = wire_time.to_be_bytes();
let mut random_hash = [0u8; 10];
random_hash[..5].copy_from_slice(&random_bytes);
// Low 5 bytes of the u64 timestamp; wraps ~every 34 000 years.
// The value was range checked, so these are the complete 40 bits.
random_hash[5..].copy_from_slice(&ts_bytes[3..8]);
let dest_hash = crate::destination::Destination::hash_from_name_and_identity(
@@ -241,7 +261,7 @@ impl AnnounceData {
}
/// Validate destination-hash binding and first-seen public-key continuity
/// after [`verify_signature`] has succeeded.
/// after [`Self::verify_signature`] has succeeded.
pub fn validate_destination_binding(
&self,
packet_dest_hash: &[u8; 16],
@@ -302,6 +322,21 @@ mod tests {
assert_eq!(validated_id.hash, id.hash);
}
#[test]
fn explicit_wire_time_uses_exact_40_bit_value() {
let id = Identity::new();
let wire_time = 0x12_3456_789Au64;
let announce = AnnounceData::create_at(&id, "test.time", None, None, wire_time).unwrap();
assert_eq!(&announce.random_hash[5..], &wire_time.to_be_bytes()[3..]);
let maximum = AnnounceData::create_at(&id, "test.time", None, None, ANNOUNCE_TIME_MAX);
assert!(maximum.is_ok());
assert!(matches!(
AnnounceData::create_at(&id, "test.time", None, None, ANNOUNCE_TIME_MAX + 1,),
Err(AnnounceError::InvalidWireTime(_))
));
}
#[test]
fn test_create_and_validate_with_ratchet() {
let id = Identity::new();
+303
View File
@@ -0,0 +1,303 @@
//! Durable control-plane state for ratcheted announces.
//!
//! The signed Python-compatible ratchet ring contains only private keys. This
//! sidecar deliberately keeps local policy metadata separate: the last wall
//! time used for rotation and the last 40-bit value emitted on the wire.
use std::path::Path;
use serde::{Deserialize, Serialize};
use zeroize::Zeroizing;
use crate::announce::ANNOUNCE_TIME_MAX;
use crate::identity::Identity;
use crate::persistence;
const CONTROL_STATE_VERSION: u8 = 1;
const CONTROL_STATE_MAX_BYTES: usize = 4096;
fn invalid_data(message: impl Into<String>) -> std::io::Error {
std::io::Error::new(std::io::ErrorKind::InvalidData, message.into())
}
/// Signed, identity- and destination-bound state used to plan a ratcheted
/// announce without mutating live state before persistence succeeds.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RatchetControlState {
identity_hash: [u8; 16],
destination_hash: [u8; 16],
last_rotation_wall: Option<u64>,
last_announce_wire: Option<u64>,
}
impl RatchetControlState {
pub fn new(identity_hash: [u8; 16], destination_hash: [u8; 16]) -> Self {
Self {
identity_hash,
destination_hash,
last_rotation_wall: None,
last_announce_wire: None,
}
}
pub fn identity_hash(&self) -> [u8; 16] {
self.identity_hash
}
pub fn destination_hash(&self) -> [u8; 16] {
self.destination_hash
}
pub fn last_rotation_wall(&self) -> Option<u64> {
self.last_rotation_wall
}
pub fn last_announce_wire(&self) -> Option<u64> {
self.last_announce_wire
}
/// Anchor unknown rotation age at the current wall time. Existing age is
/// never overwritten by this operation.
pub fn anchor_rotation_if_unknown(&mut self, wall_now: u64) {
if self.last_rotation_wall.is_none() {
self.last_rotation_wall = Some(wall_now);
}
}
/// Rotation is due only when a persisted age exists and the wall clock has
/// advanced by the full interval. Clock rollback never looks elapsed.
pub fn rotation_due(&self, wall_now: u64, interval_secs: u64) -> bool {
self.last_rotation_wall
.is_some_and(|last| wall_now >= last && wall_now.saturating_sub(last) >= interval_secs)
}
/// Return a cloned candidate recording a successful rotation.
pub fn with_rotation_at(&self, wall_now: u64) -> Self {
let mut candidate = self.clone();
candidate.last_rotation_wall = Some(wall_now);
candidate
}
/// Prepare the next wire-ordering value without mutating this live state.
///
/// `None` means wall time has not advanced beyond the last durable value;
/// callers must coalesce/defer instead of inventing `last + 1`, which could
/// make an announce appear to come from the future.
pub fn prepare_announce(&self, wall_now: u64) -> std::io::Result<Option<Self>> {
if wall_now > ANNOUNCE_TIME_MAX {
return Err(invalid_data(format!(
"wall time {wall_now} exceeds 40-bit announce field"
)));
}
if self.last_announce_wire.is_some_and(|last| wall_now <= last) {
return Ok(None);
}
let mut candidate = self.clone();
candidate.last_announce_wire = Some(wall_now);
Ok(Some(candidate))
}
/// Persist this state as a signed, bounded MessagePack envelope.
pub fn save_verified(&self, path: &Path, identity: &Identity) -> std::io::Result<()> {
if identity.hash != self.identity_hash {
return Err(invalid_data("control state identity binding mismatch"));
}
self.validate()?;
let body = ControlStateBody {
version: CONTROL_STATE_VERSION,
identity_hash: self.identity_hash.to_vec(),
destination_hash: self.destination_hash.to_vec(),
last_rotation_wall: self.last_rotation_wall,
last_announce_wire: self.last_announce_wire,
};
let packed = Zeroizing::new(
rmp_serde::to_vec_named(&body).map_err(|e| std::io::Error::other(e.to_string()))?,
);
let signature = identity.sign(&packed).ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"identity cannot sign ratchet control state",
)
})?;
let envelope = ControlStateEnvelope {
signature: signature.to_vec(),
state: packed.to_vec(),
};
let encoded = Zeroizing::new(
rmp_serde::to_vec_named(&envelope).map_err(|e| std::io::Error::other(e.to_string()))?,
);
if encoded.len() > CONTROL_STATE_MAX_BYTES {
return Err(invalid_data("ratchet control state exceeds size limit"));
}
persistence::atomic_write(path, &encoded)
}
/// Load and verify state for exactly `identity` and `destination_hash`.
pub fn load_verified(
path: &Path,
identity: &Identity,
destination_hash: [u8; 16],
) -> std::io::Result<Self> {
let encoded = Zeroizing::new(
persistence::read_file_bounded(path, CONTROL_STATE_MAX_BYTES)?
.ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound))?,
);
let envelope: ControlStateEnvelope =
rmp_serde::from_slice(&encoded).map_err(|e| std::io::Error::other(e.to_string()))?;
if envelope.signature.len() != 64 {
return Err(invalid_data("invalid control-state signature length"));
}
let signature: [u8; 64] = envelope
.signature
.as_slice()
.try_into()
.map_err(|_| invalid_data("invalid control-state signature length"))?;
let packed = Zeroizing::new(envelope.state);
if !identity.verify(&packed, &signature) {
return Err(invalid_data("invalid ratchet control-state signature"));
}
let body: ControlStateBody =
rmp_serde::from_slice(&packed).map_err(|e| std::io::Error::other(e.to_string()))?;
if body.version != CONTROL_STATE_VERSION {
return Err(invalid_data(format!(
"unsupported ratchet control-state version {}",
body.version
)));
}
let identity_hash: [u8; 16] = body
.identity_hash
.as_slice()
.try_into()
.map_err(|_| invalid_data("invalid control-state identity hash"))?;
let stored_destination: [u8; 16] = body
.destination_hash
.as_slice()
.try_into()
.map_err(|_| invalid_data("invalid control-state destination hash"))?;
if identity_hash != identity.hash {
return Err(invalid_data("control state belongs to another identity"));
}
if stored_destination != destination_hash {
return Err(invalid_data("control state belongs to another destination"));
}
let state = Self {
identity_hash,
destination_hash: stored_destination,
last_rotation_wall: body.last_rotation_wall,
last_announce_wire: body.last_announce_wire,
};
state.validate()?;
Ok(state)
}
fn validate(&self) -> std::io::Result<()> {
if self
.last_announce_wire
.is_some_and(|value| value > ANNOUNCE_TIME_MAX)
{
return Err(invalid_data("stored announce time exceeds 40-bit field"));
}
Ok(())
}
}
#[derive(Serialize, Deserialize)]
struct ControlStateBody {
version: u8,
#[serde(with = "serde_bytes")]
identity_hash: Vec<u8>,
#[serde(with = "serde_bytes")]
destination_hash: Vec<u8>,
last_rotation_wall: Option<u64>,
last_announce_wire: Option<u64>,
}
#[derive(Serialize, Deserialize)]
struct ControlStateEnvelope {
#[serde(with = "serde_bytes")]
signature: Vec<u8>,
#[serde(with = "serde_bytes")]
state: Vec<u8>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn announce_time_never_moves_into_the_future() {
let identity = Identity::new();
let destination = [0x22; 16];
let state = RatchetControlState::new(identity.hash, destination);
let state = state.prepare_announce(100).unwrap().unwrap();
assert_eq!(state.last_announce_wire(), Some(100));
assert!(state.prepare_announce(100).unwrap().is_none());
assert!(state.prepare_announce(99).unwrap().is_none());
let next = state.prepare_announce(101).unwrap().unwrap();
assert_eq!(next.last_announce_wire(), Some(101));
}
#[test]
fn unknown_rotation_age_is_anchored_without_immediate_rotation() {
let identity = Identity::new();
let mut state = RatchetControlState::new(identity.hash, [0x33; 16]);
assert!(!state.rotation_due(100, 30));
state.anchor_rotation_if_unknown(100);
assert!(!state.rotation_due(100, 30));
assert!(!state.rotation_due(99, 30));
assert!(!state.rotation_due(129, 30));
assert!(state.rotation_due(130, 30));
}
#[test]
fn signed_state_roundtrip_enforces_identity_and_destination_binding() {
let dir = std::env::temp_dir().join("reticulum_ratchet_control_state");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("control");
let identity = Identity::new();
let wrong_identity = Identity::new();
let destination = [0x44; 16];
let mut state = RatchetControlState::new(identity.hash, destination);
state.anchor_rotation_if_unknown(100);
let state = state.prepare_announce(101).unwrap().unwrap();
state.save_verified(&path, &identity).unwrap();
assert_eq!(
RatchetControlState::load_verified(&path, &identity, destination).unwrap(),
state
);
assert!(RatchetControlState::load_verified(&path, &wrong_identity, destination).is_err());
assert!(RatchetControlState::load_verified(&path, &identity, [0x55; 16]).is_err());
assert!(
path.exists(),
"rejected state remains available for recovery"
);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn failed_candidate_persistence_cannot_mutate_live_state() {
let identity = Identity::new();
let destination = [0x66; 16];
let live = RatchetControlState::new(identity.hash, destination);
let candidate = live.prepare_announce(100).unwrap().unwrap();
let missing_parent = std::env::temp_dir()
.join("reticulum_missing_control_parent")
.join("nested")
.join("state");
let _ = std::fs::remove_dir_all(
missing_parent
.parent()
.and_then(Path::parent)
.unwrap_or_else(|| Path::new("/tmp")),
);
assert!(candidate.save_verified(&missing_parent, &identity).is_err());
assert_eq!(live.last_announce_wire(), None);
}
}
File diff suppressed because it is too large. Load diff
+239 -8
View File
@@ -8,8 +8,22 @@ use thiserror::Error;
use zeroize::{Zeroize, Zeroizing};
use crate::persistence;
use std::fmt;
use std::path::Path;
use std::sync::Arc;
/// Elliptic curve used for identity encryption and ratchets.
pub const CURVE: &str = "Curve25519";
/// Combined X25519 and Ed25519 public/private key size, in bits.
pub const KEY_SIZE_BITS: usize = 512;
/// X25519 ratchet key size, in bits.
pub const RATCHET_SIZE_BITS: usize = 256;
/// X25519 ratchet key size, in bytes (Python `Identity.RATCHETSIZE`).
pub const RATCHETSIZE: usize = RATCHET_SIZE_BITS / 8;
/// Addressable identity hash size, in bits.
pub const HASH_LENGTH_BITS: usize = 128;
/// Ratchet identifier size, in bytes.
pub const RATCHET_ID_LENGTH: usize = 10;
/// HKDF-derived key length: 32 bytes AES key || 32 bytes HMAC key.
pub const DERIVED_KEY_LENGTH: usize = 64;
@@ -33,6 +47,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 +73,38 @@ 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>>,
}
/// Successful identity decryption plus the ratchet that authenticated it.
///
/// `ratchet_id` is absent when the identity's base key performed decryption.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecryptionResult {
pub plaintext: Vec<u8>,
pub ratchet_id: Option<[u8; RATCHET_ID_LENGTH]>,
}
impl Clone for Identity {
/// Software identities clone their key material; hardware-backed identities
/// share the same `LocalKeyBackend` (Arc) — there is no extractable key to copy.
fn clone(&self) -> Self {
Self {
prv: self
.prv
.as_ref()
.map(|k| X25519PrivateKey::from_bytes(&k.to_bytes())),
sig_prv: self
.sig_prv
.as_ref()
.map(|k| Ed25519PrivateKey::from_bytes(&k.to_bytes())),
pub_key: self.pub_key.clone(),
sig_pub: self.sig_pub.clone(),
hash: self.hash,
backend: self.backend.clone(),
}
}
}
impl Default for Identity {
@@ -54,6 +114,12 @@ impl Default for Identity {
}
impl Identity {
pub const CURVE: &'static str = CURVE;
pub const KEY_SIZE_BITS: usize = KEY_SIZE_BITS;
pub const RATCHET_SIZE_BITS: usize = RATCHET_SIZE_BITS;
pub const RATCHETSIZE: usize = RATCHET_SIZE_BITS / 8;
pub const HASH_LENGTH_BITS: usize = HASH_LENGTH_BITS;
pub fn new() -> Self {
let prv = X25519PrivateKey::generate();
let sig_prv = Ed25519PrivateKey::generate();
@@ -67,6 +133,7 @@ impl Identity {
pub_key,
sig_pub,
hash,
backend: None,
}
}
@@ -91,6 +158,7 @@ impl Identity {
pub_key,
sig_pub,
hash,
backend: None,
})
}
@@ -114,9 +182,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> {
@@ -163,19 +244,41 @@ impl Identity {
key
}
/// Lowercase, delimiter-free hexadecimal identity hash.
pub fn hexhash(&self) -> String {
hex::encode(self.hash)
}
pub fn has_private_key(&self) -> bool {
self.prv.is_some() && self.sig_prv.is_some()
}
/// True if private operations are served by a hardware backend.
pub fn has_backend(&self) -> bool {
self.backend.is_some()
}
/// 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 {
@@ -224,6 +327,21 @@ impl Identity {
ratchets: Option<&[&[u8; 32]]>,
enforce_ratchets: bool,
) -> Result<Vec<u8>, IdentityError> {
self.decrypt_with_ratchet_id(ciphertext, ratchets, enforce_ratchets)
.map(|result| result.plaintext)
}
/// Decrypt ciphertext and report the ratchet key that authenticated it.
///
/// The identifier is `SHA-256(ratchet_public_key)[:10]`, matching the
/// reference implementation. Base-identity decryption returns no ratchet
/// identifier.
pub fn decrypt_with_ratchet_id(
&self,
ciphertext: &[u8],
ratchets: Option<&[&[u8; 32]]>,
enforce_ratchets: bool,
) -> Result<DecryptionResult, IdentityError> {
if ciphertext.len() < 32 {
return Err(IdentityError::DecryptionFailed);
}
@@ -241,7 +359,12 @@ impl Identity {
shared.zeroize();
if let Ok(derived) = derived_result {
if let Ok(plaintext) = token::decrypt(ct, &derived) {
return Ok(plaintext);
return Ok(DecryptionResult {
plaintext,
ratchet_id: Some(Self::ratchet_id(
&ratchet_prv.public_key().to_bytes(),
)),
});
}
}
}
@@ -251,15 +374,34 @@ impl Identity {
return Err(IdentityError::DecryptionFailed);
}
let prv = self.prv.as_ref().ok_or(IdentityError::DecryptionFailed)?;
let mut shared = prv.exchange(&peer_pub);
// Identity-key ECDH: in-memory key if present, else the hardware backend.
let mut shared: [u8; 32] = if let Some(prv) = self.prv.as_ref() {
prv.exchange(&peer_pub)
} else if let Some(backend) = self.backend.as_ref() {
backend
.ecdh(&peer_pub_bytes)
.ok_or(IdentityError::DecryptionFailed)?
} else {
return Err(IdentityError::DecryptionFailed);
};
let derived_result =
derive_key_64(&shared, &self.hash).map_err(|_| IdentityError::DecryptionFailed);
shared.zeroize();
let derived = derived_result?;
let plaintext =
token::decrypt(ct, &derived).map_err(|_| IdentityError::DecryptionFailed)?;
Ok(plaintext)
Ok(DecryptionResult {
plaintext,
ratchet_id: None,
})
}
/// Derive the stable 80-bit identifier for a ratchet public key.
pub fn ratchet_id(ratchet_public_key: &[u8; 32]) -> [u8; RATCHET_ID_LENGTH] {
let full = rns_crypto::sha::sha256(ratchet_public_key);
let mut id = [0u8; RATCHET_ID_LENGTH];
id.copy_from_slice(&full[..RATCHET_ID_LENGTH]);
id
}
/// Sign `packet_hash` and return proof bytes.
@@ -293,6 +435,12 @@ impl Identity {
}
}
impl fmt::Display for Identity {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "<{}>", self.hexhash())
}
}
// Msgpack envelope wrapping the raw 64-byte private key on disk.
#[derive(Serialize, Deserialize)]
struct IdentityPersisted {
@@ -306,6 +454,8 @@ mod tests {
#[test]
fn test_generate_identity() {
let id = Identity::new();
assert_eq!(Identity::CURVE, "Curve25519");
assert_eq!(Identity::RATCHETSIZE, 32);
assert!(id.has_private_key());
assert_ne!(id.hash, [0u8; 16]);
}
@@ -365,8 +515,38 @@ mod tests {
assert!(id.decrypt(&ct, None, false).is_err());
let ratchets: Vec<&[u8; 32]> = vec![&ratchet_prv_bytes];
let pt = id.decrypt(&ct, Some(&ratchets), false).unwrap();
assert_eq!(&pt, plaintext);
let decrypted = id
.decrypt_with_ratchet_id(&ct, Some(&ratchets), false)
.unwrap();
assert_eq!(&decrypted.plaintext, plaintext);
assert_eq!(
decrypted.ratchet_id,
Some(Identity::ratchet_id(&ratchet_pub))
);
}
#[test]
fn base_identity_decryption_reports_no_ratchet() {
let id = Identity::new();
let ciphertext = id.encrypt(b"base identity", None).unwrap();
let decrypted = id
.decrypt_with_ratchet_id(&ciphertext, None, false)
.unwrap();
assert_eq!(decrypted.plaintext, b"base identity");
assert_eq!(decrypted.ratchet_id, None);
}
#[test]
fn identity_metadata_and_display_match_wire_identity() {
let id = Identity::new();
assert_eq!(CURVE, "Curve25519");
assert_eq!(KEY_SIZE_BITS, id.get_public_key().len() * 8);
assert_eq!(RATCHET_SIZE_BITS, 32 * 8);
assert_eq!(HASH_LENGTH_BITS, id.hash.len() * 8);
assert_eq!(id.hexhash(), hex::encode(id.hash));
assert_eq!(id.to_string(), format!("<{}>", hex::encode(id.hash)));
}
#[test]
@@ -483,4 +663,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");
}
}
+6 -2
View File
@@ -2,8 +2,12 @@ use rns_crypto::hkdf::hkdf_sha256;
use rns_crypto::sha::sha256;
use thiserror::Error;
// Fixed IFAC HKDF salt. Shared with the Python reference; changing it breaks interop.
const IFAC_SALT: &str = "adf54d882c9a9b80771eb4995d702d4a3e733391b2a0f53f416d9f907e55cff8";
/// Fixed IFAC HKDF salt shared with the Python reference.
///
/// This is public for applications that need to derive or inspect
/// Python-compatible IFAC material outside the runtime helper. Changing it
/// would break interoperability.
pub const IFAC_SALT: &str = "adf54d882c9a9b80771eb4995d702d4a3e733391b2a0f53f416d9f907e55cff8";
#[derive(Debug, Error)]
pub enum IfacError {
+1
View File
@@ -3,6 +3,7 @@
//! Python reference: `RNS/Identity.py`, `RNS/Destination.py`.
pub mod announce;
pub mod announce_state;
pub mod destination;
pub mod identity;
pub mod ifac;
+272 -16
View File
@@ -1,34 +1,169 @@
use std::fs;
use std::io::Write;
use std::path::Path;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
/// Write `data` to `path` via `<path>.tmp` + `rename`, fsyncing first.
static TEMP_FILE_COUNTER: AtomicU64 = AtomicU64::new(0);
static ATOMIC_WRITE_LOCK: Mutex<()> = Mutex::new(());
fn invalid_data(message: &'static str) -> std::io::Error {
std::io::Error::new(std::io::ErrorKind::InvalidData, message)
}
fn unique_temp_path(path: &Path) -> std::io::Result<PathBuf> {
let parent = path.parent().unwrap_or_else(|| Path::new("."));
let file_name = path.file_name().ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"atomic-write target has no file name",
)
})?;
let sequence = TEMP_FILE_COUNTER.fetch_add(1, Ordering::Relaxed);
let mut temp_name = file_name.to_os_string();
temp_name.push(format!(".tmp-{}-{sequence}", std::process::id()));
Ok(parent.join(temp_name))
}
#[cfg(not(windows))]
fn atomic_replace(source: &Path, destination: &Path) -> std::io::Result<()> {
fs::rename(source, destination)
}
#[cfg(windows)]
fn atomic_replace(source: &Path, destination: &Path) -> std::io::Result<()> {
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Storage::FileSystem::{
MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW,
};
let source: Vec<u16> = source.as_os_str().encode_wide().chain(Some(0)).collect();
let destination: Vec<u16> = destination
.as_os_str()
.encode_wide()
.chain(Some(0))
.collect();
// Same-directory temporary files keep this on one volume. MoveFileExW is
// the Windows replacement primitive; std::fs::rename rejects an existing
// destination on Windows instead of replacing it.
let replaced = unsafe {
MoveFileExW(
source.as_ptr(),
destination.as_ptr(),
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
)
};
if replaced == 0 {
Err(std::io::Error::last_os_error())
} else {
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(not(test), allow(dead_code))]
enum InjectedFailure {
Create,
Write,
Flush,
Sync,
VerifyTemp,
Rename,
VerifyFinal,
}
fn fail_if(stage: InjectedFailure, injected: Option<InjectedFailure>) -> std::io::Result<()> {
if injected == Some(stage) {
Err(std::io::Error::other(format!(
"injected atomic-write failure at {stage:?}"
)))
} else {
Ok(())
}
}
/// Write `data` to `path` via a unique same-directory temporary file and
/// atomic rename.
///
/// On Unix the temp file is created with mode `0600` so that key material is
/// not world-readable even during the write.
/// not world-readable even during the write. The bytes are flushed, fsynced,
/// and verified before the rename, then verified again at the final path. After
/// the rename the parent directory is fsynced best-effort so the directory
/// entry itself survives power loss.
pub fn atomic_write(path: &Path, data: &[u8]) -> std::io::Result<()> {
let tmp_path = path.with_extension("tmp");
atomic_write_inner(path, data, None)
}
fn atomic_write_inner(
path: &Path,
data: &[u8],
injected: Option<InjectedFailure>,
) -> std::io::Result<()> {
let _write_guard = ATOMIC_WRITE_LOCK
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let tmp_path = unique_temp_path(path)?;
let result = (|| {
fail_if(InjectedFailure::Create, injected)?;
{
#[cfg(unix)]
let mut f = {
use std::os::unix::fs::OpenOptionsExt;
std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.create_new(true)
.mode(0o600)
.open(&tmp_path)?
};
#[cfg(not(unix))]
let mut f = fs::File::create(&tmp_path)?;
let mut f = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp_path)?;
fail_if(InjectedFailure::Write, injected)?;
f.write_all(data)?;
fail_if(InjectedFailure::Flush, injected)?;
f.flush()?;
fail_if(InjectedFailure::Sync, injected)?;
f.sync_all()?;
drop(f);
fail_if(InjectedFailure::VerifyTemp, injected)?;
let temp_data = read_file_bounded(&tmp_path, data.len())?
.ok_or_else(|| invalid_data("atomic-write temp file disappeared"))?;
if temp_data != data {
return Err(invalid_data("atomic-write temp verification failed"));
}
fail_if(InjectedFailure::Rename, injected)?;
atomic_replace(&tmp_path, path)?;
fail_if(InjectedFailure::VerifyFinal, injected)?;
let final_data = read_file_bounded(path, data.len())?
.ok_or_else(|| invalid_data("atomic-write target disappeared"))?;
if final_data != data {
return Err(invalid_data("atomic-write final verification failed"));
}
#[cfg(unix)]
if let Some(dir) = path.parent() {
if let Ok(d) = fs::File::open(dir) {
let _ = d.sync_all();
}
}
Ok(())
})();
if result.is_err() {
let _ = fs::remove_file(&tmp_path);
}
fs::rename(&tmp_path, path)?;
Ok(())
result
}
/// Read `path` in full, returning `None` if the file does not exist.
@@ -40,29 +175,150 @@ pub fn read_file(path: &Path) -> std::io::Result<Option<Vec<u8>>> {
}
}
/// Read at most `max_len` bytes from `path`.
///
/// A file larger than the supplied bound is rejected before it can be handed
/// to a deserializer. `None` means the path did not exist.
pub fn read_file_bounded(path: &Path, max_len: usize) -> std::io::Result<Option<Vec<u8>>> {
let file = match fs::File::open(path) {
Ok(file) => file,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e),
};
let mut data = Vec::with_capacity(max_len.min(4096));
file.take(max_len.saturating_add(1) as u64)
.read_to_end(&mut data)?;
if data.len() > max_len {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("file exceeds {max_len}-byte limit"),
));
}
Ok(Some(data))
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn unique_test_dir(label: &str) -> PathBuf {
static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let id = NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
std::env::temp_dir().join(format!(
"reticulum-{label}-{}-{}-{id}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos()
))
}
#[test]
fn test_atomic_write_and_read() {
let dir = std::env::temp_dir().join("reticulum_test_persistence");
let _ = fs::create_dir_all(&dir);
let dir = unique_test_dir("persistence");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("test_atomic");
atomic_write(&path, b"hello world").unwrap();
let data = read_file(&path).unwrap().unwrap();
assert_eq!(data, b"hello world");
let _ = fs::remove_file(&path);
let _ = fs::remove_dir(&dir);
atomic_write(&path, b"replacement").unwrap();
let data = read_file(&path).unwrap().unwrap();
assert_eq!(
data, b"replacement",
"Windows must replace an existing state file instead of failing after the first write"
);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn test_read_nonexistent() {
let path = PathBuf::from("/tmp/reticulum_nonexistent_file_xyz");
let path = unique_test_dir("nonexistent").join("missing");
let result = read_file(&path).unwrap();
assert!(result.is_none());
}
#[test]
fn test_bounded_read_rejects_oversize_file() {
let dir = unique_test_dir("bounded-read");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("bounded");
fs::write(&path, [0xA5; 17]).unwrap();
let err = read_file_bounded(&path, 16).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
assert_eq!(read_file_bounded(&path, 17).unwrap().unwrap().len(), 17);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn test_atomic_write_faults_before_rename_preserve_previous_file() {
let dir = unique_test_dir("atomic-faults");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("state");
fs::write(&path, b"previous").unwrap();
for stage in [
InjectedFailure::Create,
InjectedFailure::Write,
InjectedFailure::Flush,
InjectedFailure::Sync,
InjectedFailure::VerifyTemp,
InjectedFailure::Rename,
] {
let err = atomic_write_inner(&path, b"candidate", Some(stage)).unwrap_err();
assert!(err.to_string().contains("injected"));
assert_eq!(fs::read(&path).unwrap(), b"previous", "stage {stage:?}");
}
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn test_atomic_write_final_readback_failure_is_reported() {
let dir = unique_test_dir("atomic-readback-fault");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("state");
fs::write(&path, b"previous").unwrap();
let err = atomic_write_inner(&path, b"candidate", Some(InjectedFailure::VerifyFinal))
.unwrap_err();
assert!(err.to_string().contains("injected"));
assert_eq!(
fs::read(&path).unwrap(),
b"candidate",
"the caller must not commit live state even if replacement reached disk"
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn concurrent_atomic_writers_do_not_share_temp_paths() {
let dir = unique_test_dir("atomic-concurrent");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("state");
let mut writers = Vec::new();
for byte in 0u8..16 {
let path = path.clone();
writers.push(std::thread::spawn(move || atomic_write(&path, &[byte; 64])));
}
for writer in writers {
writer.join().unwrap().unwrap();
}
let final_data = fs::read(&path).unwrap();
assert_eq!(final_data.len(), 64);
assert!(final_data.iter().all(|byte| *byte == final_data[0]));
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_dir_all(dir).unwrap();
}
}
+708 -62
View File
@@ -5,10 +5,104 @@ use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use zeroize::Zeroize;
use zeroize::{Zeroize, Zeroizing};
use crate::identity::Identity;
use crate::persistence;
const RATCHET_FILE_MAX_BYTES: usize = 64 * 1024;
const RATCHET_PACKED_MAX_BYTES: usize = 32 * 1024;
const RECEIVED_RATCHET_FILE_MAX_BYTES: usize = 1024;
fn wall_time_secs() -> f64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64()
}
fn invalid_data(message: impl Into<String>) -> std::io::Error {
std::io::Error::new(std::io::ErrorKind::InvalidData, message.into())
}
fn pack_ratchet_keys(keys: &[[u8; 32]]) -> std::io::Result<Zeroizing<Vec<u8>>> {
let byte_keys: Vec<&serde_bytes::Bytes> = keys
.iter()
.map(|key| serde_bytes::Bytes::new(key))
.collect();
let packed = Zeroizing::new(
rmp_serde::to_vec(&byte_keys).map_err(|e| std::io::Error::other(e.to_string()))?,
);
if packed.len() > RATCHET_PACKED_MAX_BYTES {
return Err(invalid_data("packed ratchet ring exceeds size limit"));
}
Ok(packed)
}
fn unpack_ratchet_keys(packed: &[u8]) -> std::io::Result<Vec<[u8; 32]>> {
if packed.len() > RATCHET_PACKED_MAX_BYTES {
return Err(invalid_data("packed ratchet ring exceeds size limit"));
}
let mut encoded_keys: Vec<serde_bytes::ByteBuf> =
rmp_serde::from_slice(packed).map_err(|e| std::io::Error::other(e.to_string()))?;
if encoded_keys.len() > RATCHET_COUNT {
for key in &mut encoded_keys {
key.as_mut().zeroize();
}
return Err(invalid_data(format!(
"ratchet ring contains {} keys; maximum is {RATCHET_COUNT}",
encoded_keys.len()
)));
}
if encoded_keys.iter().any(|key| key.len() != 32) {
for key in &mut encoded_keys {
key.as_mut().zeroize();
}
return Err(invalid_data("ratchet private key must be exactly 32 bytes"));
}
let mut keys = Vec::with_capacity(RATCHET_COUNT);
for encoded in &mut encoded_keys {
let mut key = [0u8; 32];
key.copy_from_slice(encoded);
keys.push(key);
encoded.as_mut().zeroize();
}
Ok(keys)
}
/// On-disk format accepted by [`RatchetRing::load_verified`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RatchetRingFormat {
/// Python-compatible `{signature, ratchets}` with a signature over the
/// packed private-key list.
Canonical,
/// Historical Rust envelope whose signature covered only the current
/// public ratchet and whose unsigned `last_rotation` field is ignored.
LegacyRust,
}
/// A verified ratchet ring plus the format that was read from disk.
pub struct LoadedRatchetRing {
ring: RatchetRing,
format: RatchetRingFormat,
}
impl LoadedRatchetRing {
pub fn ring(&self) -> &RatchetRing {
&self.ring
}
pub fn format(&self) -> RatchetRingFormat {
self.format
}
pub fn into_ring(self) -> RatchetRing {
self.ring
}
}
/// A bounded history of X25519 private ratchet keys for forward secrecy.
///
/// Index 0 is the most recent key; older keys are retained so decryption can
@@ -24,7 +118,7 @@ pub struct RatchetRing {
impl RatchetRing {
pub fn new() -> Self {
Self {
keys: Vec::new(),
keys: Vec::with_capacity(RATCHET_COUNT),
last_rotation: 0.0,
retained_count: RATCHET_COUNT,
rotation_interval: RATCHET_INTERVAL,
@@ -35,33 +129,97 @@ impl RatchetRing {
///
/// Any keys evicted past `retained_count` are zeroised before drop.
pub fn rotate(&mut self) -> [u8; 32] {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64();
self.rotate_at(wall_time_secs())
}
/// Generate a fresh ratchet while recording an explicit wall-clock time.
///
/// Callers that need crash safety should use [`Self::prepare_rotation_at`],
/// persist its candidate ring, and only then call
/// [`Self::commit_prepared_rotation`].
pub fn rotate_at(&mut self, now: f64) -> [u8; 32] {
let prv = X25519PrivateKey::generate();
let pub_key = prv.public_key().to_bytes();
self.keys.insert(0, prv.to_bytes());
if self.keys.len() > self.retained_count {
for key in &mut self.keys[self.retained_count..] {
key.zeroize();
}
self.keys.truncate(self.retained_count);
// Make room before insertion so a full ring never reallocates an
// uncleared backing buffer containing every retained private key.
while self.keys.len() >= self.retained_count {
let last = self.keys.len() - 1;
self.keys[last].zeroize();
self.keys.truncate(last);
}
self.last_rotation = now;
self.keys.insert(0, prv.to_bytes());
self.last_rotation = if now.is_finite() && now >= 0.0 {
now
} else {
0.0
};
pub_key
}
/// True when at least `rotation_interval` seconds have elapsed since the last rotate.
pub fn needs_rotation(&self) -> bool {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64();
now - self.last_rotation >= self.rotation_interval as f64
self.needs_rotation_at(wall_time_secs())
}
/// Test rotation age against an explicit wall-clock value.
///
/// A missing age (`last_rotation == 0`) is due. A clock rollback is not:
/// callers can anchor an unknown age with [`Self::anchor_rotation_at`] and
/// wait one normal interval instead of rotating immediately.
pub fn needs_rotation_at(&self, now: f64) -> bool {
if !now.is_finite() || now < 0.0 {
return false;
}
if self.last_rotation <= 0.0 {
return true;
}
now >= self.last_rotation && now - self.last_rotation >= self.rotation_interval as f64
}
/// Set the age anchor without generating or discarding any key material.
pub fn anchor_rotation_at(&mut self, now: f64) -> bool {
if !now.is_finite() || now < 0.0 {
return false;
}
self.last_rotation = now;
true
}
pub fn last_rotation(&self) -> f64 {
self.last_rotation
}
/// Prepare a candidate rotation without changing the live ring.
pub fn prepare_rotation_at(&self, now: f64) -> PreparedRatchetRotation {
let mut candidate = self.duplicate();
let public_key = candidate.rotate_at(now);
PreparedRatchetRotation {
candidate,
public_key,
}
}
/// Replace the live ring with a previously persisted candidate.
pub fn commit_prepared_rotation(&mut self, prepared: PreparedRatchetRotation) -> [u8; 32] {
let PreparedRatchetRotation {
mut candidate,
public_key,
} = prepared;
std::mem::swap(self, &mut candidate);
public_key
}
fn duplicate(&self) -> Self {
let mut keys = Vec::with_capacity(RATCHET_COUNT);
keys.extend_from_slice(&self.keys);
Self {
keys,
last_rotation: self.last_rotation,
retained_count: self.retained_count,
rotation_interval: self.rotation_interval,
}
}
/// Public key of the most recent ratchet, if the ring has been rotated at least once.
@@ -85,9 +243,9 @@ impl RatchetRing {
self.keys.is_empty()
}
/// Set `retained_count`; returns `false` if `count == 0`.
/// Set `retained_count`; returns `false` outside `1..=RATCHET_COUNT`.
pub fn set_retained_ratchets(&mut self, count: usize) -> bool {
if count > 0 {
if (1..=RATCHET_COUNT).contains(&count) {
self.retained_count = count;
self.clean();
true
@@ -116,27 +274,56 @@ impl RatchetRing {
fn clean(&mut self) {
if self.keys.len() > self.retained_count {
for key in &mut self.keys[self.retained_count..] {
key.zeroize();
}
self.keys.truncate(self.retained_count);
}
}
/// Persist to `path` as a Python-compatible msgpack envelope.
/// Persist to `path` as the exact Python-compatible msgpack envelope.
///
/// Python writes `{signature, ratchets}`. Rust also includes
/// `last_rotation`, which Python ignores and Rust defaults when loading a
/// Python-written file. `ratchets` is itself the msgpack-encoded key list
/// signed by the owning identity.
/// `signature` must cover the packed `ratchets` list. Production callers
/// should prefer [`Self::save_verified`], which cannot sign the wrong data.
pub fn save(&self, path: &Path, signature: &[u8; 64]) -> std::io::Result<()> {
let ratchets_packed =
rmp_serde::to_vec(&self.keys).map_err(|e| std::io::Error::other(e.to_string()))?;
let ratchets_packed = pack_ratchet_keys(&self.keys)?;
let persisted = RatchetRingPersisted {
let persisted = Zeroizing::new(RatchetRingPersistedWrite {
signature: signature.to_vec(),
ratchets: ratchets_packed,
last_rotation: self.last_rotation,
};
let buf =
rmp_serde::to_vec(&persisted).map_err(|e| std::io::Error::other(e.to_string()))?;
ratchets: ratchets_packed.to_vec(),
});
let buf = Zeroizing::new(
rmp_serde::to_vec_named(&*persisted)
.map_err(|e| std::io::Error::other(e.to_string()))?,
);
if buf.len() > RATCHET_FILE_MAX_BYTES {
return Err(invalid_data("ratchet ring file exceeds size limit"));
}
persistence::atomic_write(path, &buf)
}
/// Sign the packed key list with `identity`, persist it, and verify the
/// final bytes before returning.
pub fn save_verified(&self, path: &Path, identity: &Identity) -> std::io::Result<()> {
let ratchets_packed = pack_ratchet_keys(&self.keys)?;
let signature = identity.sign(&ratchets_packed).ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"identity cannot sign ratchet ring",
)
})?;
let persisted = Zeroizing::new(RatchetRingPersistedWrite {
signature: signature.to_vec(),
ratchets: ratchets_packed.to_vec(),
});
let buf = Zeroizing::new(
rmp_serde::to_vec_named(&*persisted)
.map_err(|e| std::io::Error::other(e.to_string()))?,
);
if buf.len() > RATCHET_FILE_MAX_BYTES {
return Err(invalid_data("ratchet ring file exceeds size limit"));
}
persistence::atomic_write(path, &buf)
}
@@ -152,7 +339,7 @@ impl RatchetRing {
}
match Self::try_load(path) {
Ok(result) => return Ok(result),
Ok(decoded) => return Ok((decoded.ring, decoded.signature)),
Err(e) => {
if attempt < delays_ms.len() - 1 {
tracing::warn!(
@@ -170,10 +357,40 @@ impl RatchetRing {
Err(last_err.unwrap())
}
fn try_load(path: &Path) -> std::io::Result<(Self, [u8; 64])> {
let data = std::fs::read(path)?;
/// Load a bounded ring and verify that its signature belongs to `identity`.
///
/// Canonical files are verified over the packed key list. Historical Rust
/// files are accepted only when their old current-public-key signature is
/// valid; their unsigned rotation timestamp is deliberately ignored.
pub fn load_verified(path: &Path, identity: &Identity) -> std::io::Result<LoadedRatchetRing> {
let decoded = Self::try_load(path)?;
let persisted: RatchetRingPersisted =
let format = if identity.verify(&decoded.packed, &decoded.signature) {
RatchetRingFormat::Canonical
} else if decoded.had_legacy_rotation
&& decoded
.ring
.current_public_key()
.is_some_and(|public| identity.verify(&public, &decoded.signature))
{
RatchetRingFormat::LegacyRust
} else {
return Err(invalid_data("invalid ratchet ring signature"));
};
Ok(LoadedRatchetRing {
ring: decoded.ring,
format,
})
}
fn try_load(path: &Path) -> std::io::Result<DecodedRatchetRing> {
let data = Zeroizing::new(
persistence::read_file_bounded(path, RATCHET_FILE_MAX_BYTES)?
.ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound))?,
);
let persisted: RatchetRingPersistedRead =
rmp_serde::from_slice(&data).map_err(|e| std::io::Error::other(e.to_string()))?;
if persisted.signature.len() != 64 {
@@ -186,27 +403,171 @@ impl RatchetRing {
let mut signature = [0u8; 64];
signature.copy_from_slice(&persisted.signature);
let keys: Vec<[u8; 32]> = rmp_serde::from_slice(&persisted.ratchets)
.map_err(|e| std::io::Error::other(e.to_string()))?;
let packed = Zeroizing::new(persisted.ratchets);
let keys = unpack_ratchet_keys(&packed)?;
let had_legacy_rotation = persisted.last_rotation.is_some();
Ok((
Self {
Ok(DecodedRatchetRing {
ring: Self {
keys,
last_rotation: persisted.last_rotation,
// Rotation age is control-plane metadata, not part of the
// Python ring signature. Never trust the historical unsigned
// value from disk.
last_rotation: 0.0,
retained_count: RATCHET_COUNT,
rotation_interval: RATCHET_INTERVAL,
},
signature,
))
had_legacy_rotation,
packed,
})
}
}
#[derive(Serialize, Deserialize)]
struct RatchetRingPersisted {
/// A verified ratchet ring bound to one crash-safe persistence path.
///
/// This is the high-level counterpart to Python's
/// `Destination.enable_ratchets(path)`: opening loads and verifies an existing
/// Python-compatible ring or creates a signed empty one. Rotations persist a
/// candidate before replacing the live secret state.
pub struct PersistentRatchetRing {
path: PathBuf,
ring: RatchetRing,
}
impl std::fmt::Debug for PersistentRatchetRing {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("PersistentRatchetRing")
.field("path", &self.path)
.field("retained_keys", &self.ring.len())
.finish_non_exhaustive()
}
}
impl PersistentRatchetRing {
/// Load and verify `path`, or initialize it with a signed empty ring.
pub fn open(path: impl AsRef<Path>, identity: &Identity) -> std::io::Result<Self> {
let path = path.as_ref().to_path_buf();
let ring = if path.is_file() {
RatchetRing::load_verified(&path, identity)?.into_ring()
} else {
let ring = RatchetRing::new();
ring.save_verified(&path, identity)?;
ring
};
Ok(Self { path, ring })
}
/// Persistence path for this ring.
pub fn path(&self) -> &Path {
&self.path
}
/// Borrow the underlying secret ring for policy inspection.
pub fn ring(&self) -> &RatchetRing {
&self.ring
}
/// Most recently persisted ratchet public key.
pub fn current_public_key(&self) -> Option<[u8; 32]> {
self.ring.current_public_key()
}
/// Retained private keys, newest first, for destination decryption.
pub fn private_keys(&self) -> &[[u8; 32]] {
self.ring.private_keys()
}
/// Number of retained private ratchets.
pub fn len(&self) -> usize {
self.ring.len()
}
/// Whether no ratchet has been generated yet.
pub fn is_empty(&self) -> bool {
self.ring.is_empty()
}
/// Return a usable current public key, rotating first when due.
pub fn ensure_current(&mut self, identity: &Identity) -> std::io::Result<[u8; 32]> {
self.ensure_current_at(identity, wall_time_secs())
}
/// Deterministic form of [`Self::ensure_current`] for runtime/tests.
pub fn ensure_current_at(
&mut self,
identity: &Identity,
now: f64,
) -> std::io::Result<[u8; 32]> {
if self.ring.is_empty() || self.ring.needs_rotation_at(now) {
self.rotate_at(identity, now)
} else {
self.ring
.current_public_key()
.ok_or_else(|| invalid_data("ratchet ring has no current key"))
}
}
/// Force a crash-safe rotation now.
pub fn rotate(&mut self, identity: &Identity) -> std::io::Result<[u8; 32]> {
self.rotate_at(identity, wall_time_secs())
}
/// Force a crash-safe rotation at an explicit wall-clock time.
pub fn rotate_at(&mut self, identity: &Identity, now: f64) -> std::io::Result<[u8; 32]> {
if !now.is_finite() || now < 0.0 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"ratchet rotation time must be finite and non-negative",
));
}
let prepared = self.ring.prepare_rotation_at(now);
prepared.ring().save_verified(&self.path, identity)?;
Ok(self.ring.commit_prepared_rotation(prepared))
}
}
struct DecodedRatchetRing {
ring: RatchetRing,
signature: [u8; 64],
had_legacy_rotation: bool,
packed: Zeroizing<Vec<u8>>,
}
/// A rotation candidate owns a duplicate secret ring and zeroises it on drop
/// unless it is committed into the live ring.
pub struct PreparedRatchetRotation {
candidate: RatchetRing,
public_key: [u8; 32],
}
impl PreparedRatchetRotation {
pub fn ring(&self) -> &RatchetRing {
&self.candidate
}
pub fn public_key(&self) -> [u8; 32] {
self.public_key
}
}
#[derive(Serialize, Zeroize)]
struct RatchetRingPersistedWrite {
#[serde(with = "serde_bytes")]
signature: Vec<u8>,
#[serde(with = "serde_bytes")]
ratchets: Vec<u8>,
}
#[derive(Deserialize)]
struct RatchetRingPersistedRead {
#[serde(with = "serde_bytes")]
signature: Vec<u8>,
#[serde(with = "serde_bytes")]
ratchets: Vec<u8>,
#[serde(default)]
last_rotation: f64,
last_rotation: Option<f64>,
}
impl Zeroize for RatchetRing {
@@ -233,6 +594,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,
@@ -241,28 +603,33 @@ pub struct ReceivedRatchet {
// On-disk shape shared with the Python reference: `{"ratchet": bytes, "received": float}`.
#[derive(Serialize, Deserialize)]
struct ReceivedRatchetPersisted {
#[serde(with = "serde_bytes")]
ratchet: Vec<u8>,
received: f64,
}
impl ReceivedRatchet {
pub fn new(ratchet_pub: [u8; 32]) -> Self {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64();
Self::new_at(ratchet_pub, wall_time_secs())
}
pub fn new_at(ratchet_pub: [u8; 32], received_at: f64) -> Self {
Self {
ratchet_pub,
received_at: now,
received_at: if received_at.is_finite() && received_at >= 0.0 {
received_at
} else {
0.0
},
}
}
pub fn is_expired(&self) -> bool {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64();
now - self.received_at > RATCHET_EXPIRY as f64
self.is_expired_at(wall_time_secs())
}
pub fn is_expired_at(&self, now: f64) -> bool {
now.is_finite() && now >= self.received_at && now - self.received_at > RATCHET_EXPIRY as f64
}
pub fn ratchet_id(&self) -> Vec<u8> {
@@ -275,8 +642,8 @@ impl ReceivedRatchet {
ratchet: self.ratchet_pub.to_vec(),
received: self.received_at,
};
let buf =
rmp_serde::to_vec(&persisted).map_err(|e| std::io::Error::other(e.to_string()))?;
let buf = rmp_serde::to_vec_named(&persisted)
.map_err(|e| std::io::Error::other(e.to_string()))?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
@@ -286,7 +653,8 @@ impl ReceivedRatchet {
}
pub fn load(path: &Path) -> std::io::Result<Self> {
let data = std::fs::read(path)?;
let data = persistence::read_file_bounded(path, RECEIVED_RATCHET_FILE_MAX_BYTES)?
.ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound))?;
let persisted: ReceivedRatchetPersisted =
rmp_serde::from_slice(&data).map_err(|e| std::io::Error::other(e.to_string()))?;
@@ -296,6 +664,9 @@ impl ReceivedRatchet {
"invalid ratchet public key length",
));
}
if !persisted.received.is_finite() || persisted.received < 0.0 {
return Err(invalid_data("invalid received-ratchet timestamp"));
}
let mut ratchet_pub = [0u8; 32];
ratchet_pub.copy_from_slice(&persisted.ratchet);
@@ -386,13 +757,19 @@ impl ReceivedRatchetStore {
/// Record `ratchet_pub` for `dest_hash`. Re-inserting the identical key is a no-op;
/// any other value replaces the entry and is written to disk when backed.
pub fn remember(&mut self, dest_hash: [u8; 16], ratchet_pub: [u8; 32]) {
self.remember_at(dest_hash, ratchet_pub, wall_time_secs());
}
/// Record a ratchet with an explicit local receive time. Re-inserting the
/// same key remains a no-op and therefore cannot extend its lifetime.
pub fn remember_at(&mut self, dest_hash: [u8; 16], ratchet_pub: [u8; 32], received_at: f64) {
if let Some(existing) = self.entries.get(&dest_hash) {
if existing.ratchet_pub == ratchet_pub {
return;
}
}
let received = ReceivedRatchet::new(ratchet_pub);
let received = ReceivedRatchet::new_at(ratchet_pub, received_at);
if let Some(ref dir) = self.storage_dir {
let hexhash = hex::encode(dest_hash);
@@ -412,6 +789,10 @@ impl ReceivedRatchetStore {
/// Return the current ratchet public key for `dest_hash`, loading from
/// disk on miss. Yields `None` if the entry is expired or absent.
pub fn get(&mut self, dest_hash: &[u8; 16]) -> Option<[u8; 32]> {
self.get_at(dest_hash, wall_time_secs())
}
pub fn get_at(&mut self, dest_hash: &[u8; 16], now: f64) -> Option<[u8; 32]> {
if !self.entries.contains_key(dest_hash) {
if let Some(ref dir) = self.storage_dir {
let hexhash = hex::encode(dest_hash);
@@ -419,7 +800,7 @@ impl ReceivedRatchetStore {
if path.exists() {
match ReceivedRatchet::load(&path) {
Ok(ratchet) => {
if !ratchet.is_expired() && ratchet.ratchet_pub.len() == 32 {
if !ratchet.is_expired_at(now) {
self.entries.insert(*dest_hash, ratchet);
} else {
return None;
@@ -440,7 +821,7 @@ impl ReceivedRatchetStore {
self.entries
.get(dest_hash)
.filter(|r| !r.is_expired())
.filter(|r| !r.is_expired_at(now))
.map(|r| r.ratchet_pub)
}
@@ -475,6 +856,7 @@ impl Default for ReceivedRatchetStore {
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
#[test]
fn test_ratchet_ring_rotate() {
@@ -490,13 +872,56 @@ mod tests {
assert_ne!(pub1, pub2);
}
#[test]
fn prepared_rotation_does_not_mutate_live_ring_until_commit() {
let mut ring = RatchetRing::new();
ring.rotate_at(100.0);
let before = ring.private_keys().to_vec();
let abandoned = ring.prepare_rotation_at(200.0);
assert_eq!(ring.private_keys(), before);
assert_eq!(abandoned.ring().len(), 2);
drop(abandoned);
assert_eq!(ring.private_keys(), before);
let prepared = ring.prepare_rotation_at(200.0);
let expected_public = prepared.public_key();
let committed_public = ring.commit_prepared_rotation(prepared);
assert_eq!(committed_public, expected_public);
assert_eq!(ring.len(), 2);
assert_eq!(ring.current_public_key(), Some(expected_public));
assert_eq!(ring.last_rotation(), 200.0);
}
#[test]
fn rotation_clock_rollback_never_looks_elapsed() {
let mut ring = RatchetRing::new();
ring.set_ratchet_interval(30);
assert!(ring.needs_rotation_at(100.0));
ring.rotate_at(100.0);
assert!(!ring.needs_rotation_at(99.0));
assert!(!ring.needs_rotation_at(129.999));
assert!(ring.needs_rotation_at(130.0));
let mut unknown_age = RatchetRing::new();
assert!(unknown_age.needs_rotation_at(100.0));
assert!(unknown_age.anchor_rotation_at(100.0));
assert!(!unknown_age.needs_rotation_at(100.0));
}
#[test]
fn test_ratchet_ring_max_keys() {
let mut ring = RatchetRing::new();
let initial_capacity = ring.keys.capacity();
for _ in 0..RATCHET_COUNT + 10 {
ring.rotate();
}
assert_eq!(ring.len(), RATCHET_COUNT);
assert_eq!(
ring.keys.capacity(),
initial_capacity,
"rotating a full secret ring must not reallocate uncleared storage"
);
}
#[test]
@@ -521,6 +946,197 @@ mod tests {
let _ = std::fs::remove_dir(&dir);
}
#[test]
fn persistent_ring_initializes_rotates_and_verifies_before_use() {
let identity = Identity::new();
let wrong_identity = Identity::new();
let dir = std::env::temp_dir().join(format!(
"reticulum_persistent_ratchets_{}",
identity.hexhash()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("ratchets");
let mut persistent = PersistentRatchetRing::open(&path, &identity).unwrap();
assert!(path.is_file());
assert!(persistent.is_empty());
let first = persistent.ensure_current_at(&identity, 100.0).unwrap();
assert_eq!(persistent.current_public_key(), Some(first));
assert_eq!(persistent.len(), 1);
assert!(PersistentRatchetRing::open(&path, &wrong_identity).is_err());
let mut reloaded = PersistentRatchetRing::open(&path, &identity).unwrap();
assert_eq!(reloaded.current_public_key(), Some(first));
let second = reloaded.ensure_current_at(&identity, 200.0).unwrap();
assert_ne!(first, second);
assert_eq!(reloaded.len(), 2);
assert_eq!(
RatchetRing::load_verified(&path, &identity)
.unwrap()
.ring()
.current_public_key(),
Some(second)
);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn persistent_ring_does_not_commit_when_rotation_cannot_be_saved() {
let identity = Identity::new();
let dir = std::env::temp_dir().join(format!(
"reticulum_persistent_ratchet_failure_{}",
identity.hexhash()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("ratchets");
let mut persistent = PersistentRatchetRing::open(&path, &identity).unwrap();
let first = persistent.ensure_current_at(&identity, 100.0).unwrap();
std::fs::remove_dir_all(&dir).unwrap();
assert!(persistent.rotate_at(&identity, 200.0).is_err());
assert_eq!(persistent.current_public_key(), Some(first));
assert_eq!(persistent.len(), 1);
}
#[test]
fn verified_ring_file_is_python_map_of_signed_binary_keys() {
let dir = std::env::temp_dir().join("reticulum_ratchet_python_wire");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("ratchets");
let identity = Identity::new();
let mut ring = RatchetRing::new();
ring.rotate_at(100.0);
ring.rotate_at(200.0);
ring.save_verified(&path, &identity).unwrap();
let data = std::fs::read(&path).unwrap();
let envelope = rmpv::decode::read_value(&mut Cursor::new(&data)).unwrap();
let map = envelope.as_map().expect("Python envelope must be a map");
assert_eq!(map.len(), 2);
let signature = map
.iter()
.find(|(key, _)| key.as_str() == Some("signature"))
.and_then(|(_, value)| value.as_slice())
.expect("signature must be MessagePack binary");
let packed = map
.iter()
.find(|(key, _)| key.as_str() == Some("ratchets"))
.and_then(|(_, value)| value.as_slice())
.expect("ratchets must be MessagePack binary");
let signature: [u8; 64] = signature.try_into().unwrap();
assert!(identity.verify(packed, &signature));
let packed_value = rmpv::decode::read_value(&mut Cursor::new(packed)).unwrap();
let keys = packed_value.as_array().expect("ratchets must be a list");
assert_eq!(keys.len(), 2);
assert!(
keys.iter()
.all(|key| key.as_slice().is_some_and(|b| b.len() == 32))
);
let loaded = RatchetRing::load_verified(&path, &identity).unwrap();
assert_eq!(loaded.format(), RatchetRingFormat::Canonical);
assert_eq!(loaded.ring().private_keys(), ring.private_keys());
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn verified_ring_rejects_wrong_identity_signature() {
let dir = std::env::temp_dir().join("reticulum_ratchet_wrong_signature");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("ratchets");
let owner = Identity::new();
let wrong = Identity::new();
let mut ring = RatchetRing::new();
ring.rotate_at(100.0);
ring.save_verified(&path, &owner).unwrap();
let err = RatchetRing::load_verified(&path, &wrong)
.err()
.expect("wrong owner must be rejected");
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
assert!(
path.exists(),
"a rejected key file must be preserved for recovery"
);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn verified_ring_accepts_exact_legacy_rust_shape_but_ignores_age() {
#[derive(Serialize)]
struct LegacyRustRatchets {
signature: Vec<u8>,
ratchets: Vec<u8>,
last_rotation: f64,
}
let dir = std::env::temp_dir().join("reticulum_ratchet_legacy_rust");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("ratchets");
let identity = Identity::new();
let keys = vec![[0x11; 32], [0x22; 32]];
// This intentionally recreates the pre-fix Rust encoding: compact
// struct, byte vectors as integer arrays, and signature over only the
// current public ratchet.
let ratchets = rmp_serde::to_vec(&keys).unwrap();
let current_public = ratchet_public_bytes(&keys[0]);
let signature = identity.sign(&current_public).unwrap();
let legacy = LegacyRustRatchets {
signature: signature.to_vec(),
ratchets,
last_rotation: f64::MAX,
};
std::fs::write(&path, rmp_serde::to_vec(&legacy).unwrap()).unwrap();
let loaded = RatchetRing::load_verified(&path, &identity).unwrap();
assert_eq!(loaded.format(), RatchetRingFormat::LegacyRust);
assert_eq!(loaded.ring().private_keys(), keys);
assert_eq!(loaded.ring().last_rotation(), 0.0);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn ring_load_rejects_oversize_and_overcount_without_retrying() {
let dir = std::env::temp_dir().join("reticulum_ratchet_bounds");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("ratchets");
let identity = Identity::new();
std::fs::write(&path, vec![0u8; RATCHET_FILE_MAX_BYTES + 1]).unwrap();
assert_eq!(
RatchetRing::load_verified(&path, &identity)
.err()
.expect("oversize ring must fail")
.kind(),
std::io::ErrorKind::InvalidData
);
let keys = vec![[0x44; 32]; RATCHET_COUNT + 1];
let packed = rmp_serde::to_vec(&keys).unwrap();
let envelope = RatchetRingPersistedWrite {
signature: vec![0u8; 64],
ratchets: packed,
};
std::fs::write(&path, rmp_serde::to_vec_named(&envelope).unwrap()).unwrap();
assert_eq!(
RatchetRing::load_verified(&path, &identity)
.err()
.expect("overcount ring must fail")
.kind(),
std::io::ErrorKind::InvalidData
);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn test_ratchet_ring_loads_python_shape_without_last_rotation() {
#[derive(Serialize)]
@@ -596,6 +1212,17 @@ mod tests {
assert!((loaded.received_at - received.received_at).abs() < 0.001);
assert!(!loaded.is_expired());
let encoded = std::fs::read(&path).unwrap();
let envelope = rmpv::decode::read_value(&mut Cursor::new(encoded)).unwrap();
let map = envelope.as_map().expect("Python envelope must be a map");
assert_eq!(map.len(), 2);
assert!(
map.iter()
.find(|(key, _)| key.as_str() == Some("ratchet"))
.and_then(|(_, value)| value.as_slice())
.is_some_and(|ratchet| ratchet.len() == 32)
);
let _ = std::fs::remove_file(&path);
let _ = std::fs::remove_dir(&dir);
}
@@ -641,6 +1268,25 @@ mod tests {
assert_eq!(store.get(&dest_hash), Some(ratchet_pub2));
}
#[test]
fn identical_received_ratchet_does_not_refresh_expiry() {
let mut store = ReceivedRatchetStore::new();
let dest_hash = [0xBC; 16];
let ratchet = [0xCD; 32];
store.remember_at(dest_hash, ratchet, 10.0);
store.remember_at(dest_hash, ratchet, 20.0);
assert_eq!(
store.get_at(&dest_hash, 10.0 + RATCHET_EXPIRY as f64),
Some(ratchet)
);
assert_eq!(
store.get_at(&dest_hash, 10.0 + RATCHET_EXPIRY as f64 + 0.001),
None,
"same-key reannounce must not extend the original receive age"
);
}
#[test]
fn test_get_ratchet_id() {
let pub_bytes = rns_crypto::random::random_32();
+10 -1
View File
@@ -3,6 +3,7 @@ name = "rns-interface"
description = "Network interface trait and implementations for Reticulum"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[features]
@@ -10,7 +11,6 @@ default = []
serial = ["dep:serialport"]
rnode-tcp = []
ble = ["dep:btleplug", "dep:futures", "dep:uuid", "dep:bluer"]
ble_peer = ["ble"]
# See rns-transport's mobile-throttle. When enabled, auto-interface beacons
# and reverse-peering probes slow down in the background; BLE peer scan
# cadence adjusts to `is_foreground`. Disabled on desktop builds.
@@ -19,6 +19,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 }
@@ -34,6 +35,7 @@ rand = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
hex = { workspace = true }
md-5 = { workspace = true }
# Apple BLE Peripheral (CoreBluetooth GATT server, iOS + macOS).
# Version pinned to match btleplug's internal objc2 version so the shared
@@ -49,6 +51,13 @@ objc2-core-bluetooth = "0.2"
[target.'cfg(target_os = "macos")'.dependencies]
libc = "0.2"
[dev-dependencies]
tokio = { workspace = true, features = ["test-util"] }
# Keepalive-tuning tests read socket options back via getsockopt.
[target.'cfg(unix)'.dev-dependencies]
libc = "0.2"
# Android JNI (BLE Peripheral, USB Serial)
[target.'cfg(target_os = "android")'.dependencies]
jni = "0.19"
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+222 -111
View File
@@ -3,7 +3,7 @@
//! Beacons go to a multicast group derived from `SHA-256(group_id)` every
//! ~1.6 s; data flows over unicast UDP. Peers age out after 22 s of silence.
use std::collections::{HashMap, VecDeque};
use std::collections::{HashMap, HashSet, VecDeque};
use std::net::{Ipv6Addr, SocketAddr, SocketAddrV6};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};
@@ -161,10 +161,10 @@ impl std::fmt::Display for McastAddrType {
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum AutoInterfaceEvent {
/// `IPV6_JOIN_GROUP` was rejected by the OS. On Apple this is the
/// canonical signal for missing `com.apple.developer.networking.multicast`
/// entitlement (free dev team can't sign it). On Linux it usually means
/// the interface vanished between enumeration and join.
/// `IPV6_JOIN_GROUP` was rejected by the OS. On Apple this can indicate a
/// missing `com.apple.developer.networking.multicast` entitlement or Local
/// Network authorization that has not been granted yet. On Linux it
/// usually means the interface vanished between enumeration and join.
JoinFailed {
interface_name: String,
ifname: String,
@@ -1021,6 +1021,17 @@ fn hex_prefix(bytes: &[u8], n: usize) -> String {
s
}
fn multicast_join_candidates(
link_locals: &[(String, Ipv6Addr, u32)],
joined_memberships: &HashSet<(String, u32)>,
) -> Vec<(String, Ipv6Addr, u32)> {
link_locals
.iter()
.filter(|(ifname, _, scope_id)| !joined_memberships.contains(&(ifname.clone(), *scope_id)))
.cloned()
.collect()
}
/// Spawn the auto-discovery interface.
pub async fn spawn_auto_interface(
config: AutoInterfaceConfig,
@@ -1070,6 +1081,8 @@ pub async fn spawn_auto_interface(
})?);
tracing::info!(name = %config.name, port = config.discovery_port, "auto discovery socket bound");
let mut joined_memberships: HashSet<(String, u32)> = HashSet::new();
let mut reported_join_failures: HashSet<(String, u32)> = HashSet::new();
for (iface_name, _ll_addr, scope_id) in &initial_link_locals {
if let Err(e) = set_multicast_if_v6(disc_sock.as_ref(), *scope_id) {
tracing::warn!(
@@ -1080,28 +1093,33 @@ pub async fn spawn_auto_interface(
"failed to set IPv6 multicast outbound interface"
);
}
if let Err(e) = disc_sock.join_multicast_v6(&mcast_group, *scope_id) {
// EPERM/EACCES on Apple is the canonical signal that the
// multicast networking entitlement isn't provisioned (e.g. iOS
// PermissionDenied covers EPERM/EACCES/Windows ERROR_ACCESS_DENIED.
// Surfaced as an event so UIs can show pending Apple approval.
if e.kind() == std::io::ErrorKind::PermissionDenied {
tracing::warn!(
iface = %iface_name,
error = %e,
"multicast join denied by OS — entitlement / firewall / capability missing"
);
dispatch_auto_event(AutoInterfaceEvent::JoinFailed {
interface_name: config.name.clone(),
ifname: iface_name.clone(),
reason: format!("os_permission_denied: {e}"),
});
} else {
tracing::debug!(
iface = %iface_name,
error = %e,
"failed to join multicast group"
);
match disc_sock.join_multicast_v6(&mcast_group, *scope_id) {
Ok(()) => {
joined_memberships.insert((iface_name.clone(), *scope_id));
}
Err(e) => {
// iOS can reject the first operation while Local Network
// authorization is being resolved. Keep the interface alive;
// the jobs task retries missing memberships periodically.
if e.kind() == std::io::ErrorKind::PermissionDenied {
reported_join_failures.insert((iface_name.clone(), *scope_id));
tracing::warn!(
iface = %iface_name,
error = %e,
"multicast join denied by OS — permission, entitlement, firewall, or capability missing"
);
dispatch_auto_event(AutoInterfaceEvent::JoinFailed {
interface_name: config.name.clone(),
ifname: iface_name.clone(),
reason: format!("os_permission_denied: {e}"),
});
} else {
tracing::debug!(
iface = %iface_name,
error = %e,
"failed to join multicast group"
);
}
}
}
}
@@ -1199,12 +1217,17 @@ pub async fn spawn_auto_interface(
let disc_sock_recv = disc_sock.clone();
tokio::spawn(async move {
let mut buf = [0u8; 256];
// Python's read loops swallow exceptions and keep serving; Linux
// surfaces transient async errors (ICMP unreachable) via recv_from,
// so only sustained failure may kill the loop.
let mut consecutive_errors = 0u32;
loop {
if !online_d.load(Ordering::SeqCst) {
break;
}
match disc_sock_recv.recv_from(&mut buf).await {
Ok((n, src)) => {
consecutive_errors = 0;
if n < 32 {
tracing::debug!(src = %src, n, "auto-instr mcast RX too short");
continue;
@@ -1220,20 +1243,21 @@ pub async fn spawn_auto_interface(
.map(|(name, _, _)| name.clone())
};
let is_self = self_iface.is_some();
let received_hash = hex32(&buf[..32]);
let expected = make_beacon(&auth_group_id, &peer_ip);
let expected_hex = hex32(&expected);
let match_ok = expected[..] == buf[..32];
tracing::debug!(
src = %src_v6,
scope_id = src_v6.scope_id(),
n,
is_self,
recv_hash = %received_hash,
expected_hash = %expected_hex,
match_ok,
"auto-instr mcast RX"
);
// Hash hex strings only materialize when debug is on.
if tracing::enabled!(tracing::Level::DEBUG) {
tracing::debug!(
src = %src_v6,
scope_id = src_v6.scope_id(),
n,
is_self,
recv_hash = %hex32(&buf[..32]),
expected_hash = %hex32(&expected),
match_ok,
"auto-instr mcast RX"
);
}
if let Some(ifname) = self_iface {
// Self-echo: carrier confirmed; record for jobs task.
let mut echoes = disc_echoes.lock().await;
@@ -1267,8 +1291,12 @@ pub async fn spawn_auto_interface(
}
}
Err(e) => {
tracing::warn!(error = %e, "auto discovery recv error");
break;
consecutive_errors += 1;
tracing::warn!(error = %e, consecutive_errors, "auto discovery recv error");
if consecutive_errors >= 50 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
}
@@ -1300,12 +1328,14 @@ pub async fn spawn_auto_interface(
let urecv_link_locals = unicast_link_locals.clone();
tokio::spawn(async move {
let mut buf = [0u8; 256];
let mut consecutive_errors = 0u32;
loop {
if !urecv_online.load(Ordering::SeqCst) {
break;
}
match urecv_sock.recv_from(&mut buf).await {
Ok((n, src)) => {
consecutive_errors = 0;
if n < 32 {
continue;
}
@@ -1341,8 +1371,16 @@ pub async fn spawn_auto_interface(
}
}
Err(e) => {
tracing::debug!(error = %e, "auto unicast discovery recv error");
break;
consecutive_errors += 1;
tracing::debug!(
error = %e,
consecutive_errors,
"auto unicast discovery recv error"
);
if consecutive_errors >= 50 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
}
@@ -1381,39 +1419,52 @@ pub async fn spawn_auto_interface(
}
let snapshot = { rev_link_locals.lock().await.clone() };
let now = Instant::now();
let mut table = rev_peers.lock().await;
for (_key, peer) in table.iter_mut() {
if now.duration_since(peer.last_reverse).as_secs_f64()
>= REVERSE_PEERING_INTERVAL
{
let mut targets: Vec<_> = snapshot
.iter()
.filter(|(_, _, scope_id)| {
peer.scope_id == 0 || *scope_id == peer.scope_id
})
.collect();
if targets.is_empty() {
targets = snapshot.iter().collect();
// Snapshot due peers under a short lock; sends happen lock-free
// so discovery/data tasks aren't stalled by the fan-out.
let due: Vec<(PeerKey, Peer)> = {
let table = rev_peers.lock().await;
table
.iter()
.filter(|(_, peer)| {
now.duration_since(peer.last_reverse).as_secs_f64()
>= REVERSE_PEERING_INTERVAL
})
.map(|(key, peer)| (*key, peer.clone()))
.collect()
};
for (_, peer) in &due {
let mut targets: Vec<_> = snapshot
.iter()
.filter(|(_, _, scope_id)| peer.scope_id == 0 || *scope_id == peer.scope_id)
.collect();
if targets.is_empty() {
targets = snapshot.iter().collect();
}
for (_name, ll_addr, scope_id) in targets {
let beacon = make_beacon(&rev_group_id, ll_addr);
let dest =
SocketAddrV6::new(*peer.addr.ip(), unicast_disc_port, 0, *scope_id);
if let Err(e) = unicast_sock.send_to(&beacon, dest).await {
tracing::debug!(
peer = %peer.ip,
peer_ifname = %peer.ifname,
peer_scope_id = peer.scope_id,
local_iface = %_name,
local_scope_id = scope_id,
dst = %dest,
error = %e,
raw_os_error = ?e.raw_os_error(),
"auto: reverse peering TX failed"
);
}
for (_name, ll_addr, scope_id) in targets {
let beacon = make_beacon(&rev_group_id, ll_addr);
let dest =
SocketAddrV6::new(*peer.addr.ip(), unicast_disc_port, 0, *scope_id);
if let Err(e) = unicast_sock.send_to(&beacon, dest).await {
tracing::debug!(
peer = %peer.ip,
peer_ifname = %peer.ifname,
peer_scope_id = peer.scope_id,
local_iface = %_name,
local_scope_id = scope_id,
dst = %dest,
error = %e,
raw_os_error = ?e.raw_os_error(),
"auto: reverse peering TX failed"
);
}
}
}
if !due.is_empty() {
let mut table = rev_peers.lock().await;
for (key, _) in &due {
if let Some(peer) = table.get_mut(key) {
peer.last_reverse = now;
}
peer.last_reverse = now;
}
}
}
@@ -1476,7 +1527,9 @@ pub async fn spawn_auto_interface(
"AutoInterface link-local set changed"
);
}
for (ifname, addr, scope_id) in &added {
let join_candidates = multicast_join_candidates(&new_set, &joined_memberships);
for (ifname, addr, scope_id) in &join_candidates {
let membership = (ifname.clone(), *scope_id);
if let Err(e) = set_multicast_if_v6(jobs_disc_sock.as_ref(), *scope_id) {
tracing::warn!(
iface = %jobs_iface_name,
@@ -1489,32 +1542,50 @@ pub async fn spawn_auto_interface(
);
}
match jobs_disc_sock.join_multicast_v6(&jobs_mcast, *scope_id) {
Ok(()) => tracing::info!(
iface = %jobs_iface_name,
nic = %ifname,
addr = %addr,
scope_id,
"AutoInterface joined multicast on new NIC"
),
Ok(()) => {
joined_memberships.insert(membership.clone());
reported_join_failures.remove(&membership);
tracing::info!(
iface = %jobs_iface_name,
nic = %ifname,
addr = %addr,
scope_id,
"AutoInterface joined multicast on NIC"
);
}
Err(e) => {
if e.kind() == std::io::ErrorKind::PermissionDenied {
let first_report = reported_join_failures.insert(membership);
if first_report && e.kind() == std::io::ErrorKind::PermissionDenied {
dispatch_auto_event(AutoInterfaceEvent::JoinFailed {
interface_name: jobs_iface_name.clone(),
ifname: ifname.clone(),
reason: format!("os_permission_denied: {e}"),
});
}
tracing::warn!(
iface = %jobs_iface_name,
nic = %ifname,
error = %e,
"AutoInterface multicast join failed on new NIC"
);
if first_report {
tracing::warn!(
iface = %jobs_iface_name,
nic = %ifname,
error = %e,
"AutoInterface multicast join failed; will retry"
);
} else {
tracing::debug!(
iface = %jobs_iface_name,
nic = %ifname,
error = %e,
"AutoInterface multicast join retry failed"
);
}
}
}
}
for (ifname, _addr, scope_id) in &removed {
let _ = jobs_disc_sock.leave_multicast_v6(&jobs_mcast, *scope_id);
let membership = (ifname.clone(), *scope_id);
if joined_memberships.remove(&membership) {
let _ = jobs_disc_sock.leave_multicast_v6(&jobs_mcast, *scope_id);
}
reported_join_failures.remove(&membership);
jobs_echoes.lock().await.remove(ifname);
carrier_state.remove(ifname);
}
@@ -1572,32 +1643,46 @@ pub async fn spawn_auto_interface(
tokio::spawn(async move {
while let Some(data) = rx.recv().await {
let len = data.len();
let prefix = hex_prefix(&data, 16);
let table = peers_write.lock().await;
let peer_count = table.len();
if peer_count == 0 {
// Hex prefix only materializes when debug logging is active; the
// error path below recomputes it (errors are rare).
let debug_enabled = tracing::enabled!(tracing::Level::DEBUG);
let prefix = if debug_enabled {
hex_prefix(&data, 16)
} else {
String::new()
};
// Snapshot under a short lock so the discovery/jobs tasks are not
// blocked while we await per-peer sends.
let targets: Vec<Peer> = {
let table = peers_write.lock().await;
table.values().cloned().collect()
};
let peer_count = targets.len();
if peer_count == 0 && debug_enabled {
tracing::debug!(
len,
prefix = %prefix,
"auto-instr data TX skipped: no discovered peers"
);
}
for (_key, peer) in table.iter() {
for peer in &targets {
let res = data_sock_w.send_to(&data, peer.addr).await;
match res {
Ok(n) => {
tracing::debug!(
peer = %peer.ip,
ifname = %peer.ifname,
scope_id = peer.scope_id,
scope_source = ?peer.scope_source,
dst = %peer.addr,
len,
sent_bytes = n,
prefix = %prefix,
peer_count,
"auto-instr data TX"
);
if debug_enabled {
tracing::debug!(
peer = %peer.ip,
ifname = %peer.ifname,
scope_id = peer.scope_id,
scope_source = ?peer.scope_source,
dst = %peer.addr,
len,
sent_bytes = n,
prefix = %prefix,
peer_count,
"auto-instr data TX"
);
}
task_txb.fetch_add(len as u64, Ordering::Relaxed);
}
Err(e) => {
@@ -1608,7 +1693,7 @@ pub async fn spawn_auto_interface(
scope_source = ?peer.scope_source,
dst = %peer.addr,
len,
prefix = %prefix,
prefix = %hex_prefix(&data, 16),
peer_count,
error = %e,
raw_os_error = ?e.raw_os_error(),
@@ -1625,9 +1710,11 @@ pub async fn spawn_auto_interface(
let dedup = Arc::new(Mutex::new(MultiIfDedup::new()));
let read_task = tokio::spawn(async move {
let mut buf = [0u8; 2048];
let mut consecutive_errors = 0u32;
loop {
match data_sock.recv_from(&mut buf).await {
Ok((n, _src)) => {
consecutive_errors = 0;
if n == 0 {
continue;
}
@@ -1658,8 +1745,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;
}
}
}
@@ -1684,6 +1775,7 @@ pub async fn spawn_auto_interface(
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: None,
tx,
read_task,
})
@@ -1711,6 +1803,26 @@ mod tests {
assert_eq!(group.segments()[7], 0x31e1);
}
#[test]
fn multicast_join_candidates_retries_unchanged_missing_membership() {
let en0_addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
let en1_addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
let link_locals = vec![
("en0".to_string(), en0_addr, 4),
("en1".to_string(), en1_addr, 7),
];
let joined = HashSet::from([("en0".to_string(), 4)]);
assert_eq!(
multicast_join_candidates(&link_locals, &joined),
vec![("en1".to_string(), en1_addr, 7)]
);
assert_eq!(
multicast_join_candidates(&link_locals, &HashSet::new()),
link_locals
);
}
#[test]
fn test_derive_multicast_address_all_scopes() {
// High u16 = 0xff_T_S; bytes 2-13 of SHA-256("reticulum") fill the body.
@@ -1950,7 +2062,6 @@ mod tests {
#[test]
fn test_constants() {
assert_eq!(HW_MTU, 1196);
const { assert!(FIXED_MTU) };
assert_eq!(DISCOVERY_PORT, 29716);
assert_eq!(DATA_PORT, 42671);
assert_eq!(UNICAST_DISCOVERY_PORT, 29717);
+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;
}
@@ -425,6 +407,7 @@ pub async fn spawn_ax25kiss_interface(
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: None,
tx,
read_task,
})
+734 -5
View File
@@ -4,10 +4,11 @@
//! buffers. Inbound deframer is capped (vs Python's unbounded) to avoid
//! malformed-peer memory blow-up.
use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
use bytes::Bytes;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
@@ -16,8 +17,12 @@ use tokio::sync::mpsc;
use crate::hdlc;
use crate::socket_tuning::{iface_addr_for, set_keepalive_tuned, set_socket_buffers};
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
use rns_transport::messages::{InboundPacket, TransportMessage};
use crate::traits::{
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
};
use rns_transport::messages::{
InboundPacket, InterfaceInspectionSnapshot, InterfaceInspectionSource, TransportMessage,
};
/// 1 MiB MTU — also the SO_RCVBUF/SNDBUF target (kernel clamps).
pub const HW_MTU: u32 = 1_048_576;
@@ -37,8 +42,21 @@ pub const TCP_PROBES: u32 = 12;
/// Linux TCP_USER_TIMEOUT — drops stuck conns when peer goes silent without RST.
pub const TCP_USER_TIMEOUT: u32 = 24;
pub const BLOCK_FAST_FLAPPING: bool = true;
pub const FAST_FLAPPING_THRESHOLD: Duration = Duration::from_secs(20);
pub const FAST_FLAPPING_GRACE: u64 = 5;
pub const FAST_FLAPPING_BLOCK_TIME: Duration = Duration::from_secs(12 * 60 * 60);
const TX_CHANNEL_DEPTH: usize = 1024;
/// Bounds process-global fast-flap state to a conservative few hundred KiB.
///
/// Once full, unexpired tracked (including blocked) IPs retain their state and
/// new IPs remain admissible but are not tracked. Strictly expired entries can
/// be reclaimed. This prevents an address spray from turning the abuse
/// safeguard itself into an unbounded allocation.
const MAX_TRACKED_FAST_FLAP_IPS: usize = 4096;
#[derive(Debug, Clone)]
pub struct BackboneServerConfig {
pub name: String,
@@ -48,6 +66,14 @@ pub struct BackboneServerConfig {
pub mode: InterfaceMode,
/// Optional kernel ifname; binds to its current IP (falls back to `listen_ip`).
pub device: Option<String>,
/// Reject an IP after more than `fast_flapping_grace` short connections.
pub block_fast_flapping: bool,
/// Connections shorter than this duration count as fast flaps.
pub fast_flapping_threshold: Duration,
/// Number of short connections tolerated before blocking starts.
pub fast_flapping_grace: u64,
/// Time since the latest short connection before its state expires.
pub fast_flapping_block_time: Duration,
}
impl BackboneServerConfig {
@@ -59,6 +85,10 @@ impl BackboneServerConfig {
prefer_ipv6: false,
mode: InterfaceMode::Full,
device: None,
block_fast_flapping: BLOCK_FAST_FLAPPING,
fast_flapping_threshold: FAST_FLAPPING_THRESHOLD,
fast_flapping_grace: FAST_FLAPPING_GRACE,
fast_flapping_block_time: FAST_FLAPPING_BLOCK_TIME,
}
}
}
@@ -88,6 +118,222 @@ impl BackboneClientConfig {
}
}
#[derive(Debug, Clone, Copy)]
struct FastFlapPolicy {
enabled: bool,
threshold: Duration,
grace: u64,
block_time: Duration,
}
impl From<&BackboneServerConfig> for FastFlapPolicy {
fn from(config: &BackboneServerConfig) -> Self {
Self {
enabled: config.block_fast_flapping,
threshold: config.fast_flapping_threshold,
grace: config.fast_flapping_grace,
block_time: config.fast_flapping_block_time,
}
}
}
trait MonotonicClock: Send + Sync {
fn now(&self) -> Duration;
}
struct SystemMonotonicClock;
impl MonotonicClock for SystemMonotonicClock {
fn now(&self) -> Duration {
static EPOCH: OnceLock<Instant> = OnceLock::new();
EPOCH.get_or_init(Instant::now).elapsed()
}
}
#[derive(Debug, Clone, Copy)]
struct FastFlapEntry {
last_flap: Duration,
flaps: u64,
}
struct FastFlapTable {
entries: HashMap<IpAddr, FastFlapEntry>,
capacity: usize,
}
impl FastFlapTable {
fn new(capacity: usize) -> Self {
Self {
entries: HashMap::new(),
capacity,
}
}
fn prune_expired(&mut self, now: Duration, block_time: Duration) {
self.entries
.retain(|_, entry| now.saturating_sub(entry.last_flap) <= block_time);
}
}
#[derive(Clone)]
struct FastFlapRuntime {
clock: Arc<dyn MonotonicClock>,
table: Arc<Mutex<FastFlapTable>>,
}
impl FastFlapRuntime {
fn production() -> Self {
static TABLE: OnceLock<Arc<Mutex<FastFlapTable>>> = OnceLock::new();
Self {
clock: Arc::new(SystemMonotonicClock),
table: Arc::clone(TABLE.get_or_init(|| {
Arc::new(Mutex::new(FastFlapTable::new(MAX_TRACKED_FAST_FLAP_IPS)))
})),
}
}
fn admit(&self, remote_ip: IpAddr, policy: FastFlapPolicy) -> FastFlapAdmission {
let started_at = self.clock.now();
if !policy.enabled {
return FastFlapAdmission::Allowed(FastFlapConnection {
remote_ip,
started_at: Some(started_at),
policy,
runtime: self.clone(),
});
}
let mut table = self.table.lock().unwrap_or_else(|e| e.into_inner());
if let Some(entry) = table.entries.get(&remote_ip).copied() {
if started_at.saturating_sub(entry.last_flap) > policy.block_time {
table.entries.remove(&remote_ip);
} else if entry.flaps > policy.grace {
return FastFlapAdmission::Rejected { flaps: entry.flaps };
}
} else if table.entries.len() >= table.capacity {
table.prune_expired(started_at, policy.block_time);
}
drop(table);
FastFlapAdmission::Allowed(FastFlapConnection {
remote_ip,
started_at: Some(started_at),
policy,
runtime: self.clone(),
})
}
fn record_disconnect(&self, remote_ip: IpAddr, started_at: Duration, policy: FastFlapPolicy) {
if !policy.enabled {
return;
}
let now = self.clock.now();
if now.saturating_sub(started_at) >= policy.threshold {
return;
}
let mut table = self.table.lock().unwrap_or_else(|e| e.into_inner());
if let Some(entry) = table.entries.get_mut(&remote_ip) {
entry.last_flap = now;
entry.flaps = entry.flaps.saturating_add(1);
return;
}
if table.entries.len() >= table.capacity {
table.prune_expired(now, policy.block_time);
}
if table.entries.len() >= table.capacity {
tracing::debug!(
remote_ip = %remote_ip,
capacity = table.capacity,
"backbone fast-flap table is full; declining to track new IP",
);
return;
}
table.entries.insert(
remote_ip,
FastFlapEntry {
last_flap: now,
flaps: 1,
},
);
}
fn inspection_snapshot(
&self,
policy: FastFlapPolicy,
active_clients: &AtomicU64,
) -> InterfaceInspectionSnapshot {
let blocked_ips = if policy.enabled {
let now = self.clock.now();
let mut table = self.table.lock().unwrap_or_else(|e| e.into_inner());
table.prune_expired(now, policy.block_time);
table
.entries
.values()
.filter(|entry| entry.flaps > policy.grace)
.count() as u64
} else {
0
};
InterfaceInspectionSnapshot {
active_clients: Some(active_clients.load(Ordering::Relaxed)),
blocked_ips: Some(blocked_ips),
}
}
}
enum FastFlapAdmission {
Allowed(FastFlapConnection),
Rejected { flaps: u64 },
}
struct FastFlapConnection {
remote_ip: IpAddr,
started_at: Option<Duration>,
policy: FastFlapPolicy,
runtime: FastFlapRuntime,
}
impl FastFlapConnection {
fn record_disconnect(&mut self) {
if let Some(started_at) = self.started_at.take() {
self.runtime
.record_disconnect(self.remote_ip, started_at, self.policy);
}
}
fn disconnected(mut self) {
self.record_disconnect();
}
}
impl Drop for FastFlapConnection {
fn drop(&mut self) {
// The guard lives in the child read-task future, so cancellation and
// panic exits account for the connection just like normal EOF/errors.
self.record_disconnect();
}
}
struct ActiveClientGuard {
active_clients: Arc<AtomicU64>,
}
impl ActiveClientGuard {
fn new(active_clients: Arc<AtomicU64>) -> Self {
active_clients.fetch_add(1, Ordering::Relaxed);
Self { active_clients }
}
}
impl Drop for ActiveClientGuard {
fn drop(&mut self) {
self.active_clients.fetch_sub(1, Ordering::Relaxed);
}
}
fn keepalive_durations() -> (Duration, Duration, u32, Duration) {
(
Duration::from_secs(TCP_PROBE_AFTER as u64),
@@ -220,6 +466,25 @@ pub async fn spawn_backbone_server(
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
spawn_backbone_server_with_runtime(
config,
id,
id_gen,
transport_tx,
handle_tx,
FastFlapRuntime::production(),
)
.await
}
async fn spawn_backbone_server_with_runtime(
config: BackboneServerConfig,
id: InterfaceId,
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
fast_flap_runtime: FastFlapRuntime,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let listen_ip = resolve_listen_addr(&config);
let bind_addr = if listen_ip.starts_with('[') {
@@ -230,6 +495,26 @@ pub async fn spawn_backbone_server(
format!("{}:{}", listen_ip, config.listen_port)
};
let listener = TcpListener::bind(&bind_addr).await?;
spawn_backbone_server_on_listener(
config,
id,
id_gen,
transport_tx,
handle_tx,
fast_flap_runtime,
listener,
)
}
fn spawn_backbone_server_on_listener(
config: BackboneServerConfig,
id: InterfaceId,
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
fast_flap_runtime: FastFlapRuntime,
listener: TcpListener,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let local_addr = listener.local_addr()?;
tracing::info!(name = %config.name, addr = %local_addr, "backbone server listening");
@@ -237,6 +522,14 @@ pub async fn spawn_backbone_server(
let online2 = online.clone();
let name = config.name.clone();
let mode = config.mode;
let fast_flap_policy = FastFlapPolicy::from(&config);
let active_clients = Arc::new(AtomicU64::new(0));
let inspection_runtime = fast_flap_runtime.clone();
let inspection_active_clients = Arc::clone(&active_clients);
let inspection = InterfaceInspectionSource::new(move || {
inspection_runtime.inspection_snapshot(fast_flap_policy, inspection_active_clients.as_ref())
});
let task_active_clients = Arc::clone(&active_clients);
// Parent listener is inbound-only; drain task warns on stray writes.
let (tx, mut listener_rx) = mpsc::channel::<Bytes>(1);
@@ -254,6 +547,19 @@ pub async fn spawn_backbone_server(
loop {
match listener.accept().await {
Ok((stream, peer)) => {
let fast_flap_connection =
match fast_flap_runtime.admit(peer.ip(), fast_flap_policy) {
FastFlapAdmission::Allowed(connection) => connection,
FastFlapAdmission::Rejected { flaps } => {
tracing::warn!(
remote_ip = %peer.ip(),
flaps,
"backbone: rejecting fast-flapping connection",
);
continue;
}
};
let client_id = id_gen.fetch_add(1, Ordering::SeqCst);
let client_name = format!("{}/client_{}", config.name, client_id);
tracing::info!(
@@ -279,9 +585,13 @@ pub async fn spawn_backbone_server(
let transport_tx2 = transport_tx.clone();
let dereg_tx = transport_tx.clone();
let cname = client_name.clone();
let active_client_guard =
ActiveClientGuard::new(Arc::clone(&task_active_clients));
let read_handle = tokio::spawn(async move {
let _active_client_guard = active_client_guard;
backbone_read_loop(reader, client_id, transport_tx2, c_online_r, c_rxb_r)
.await;
fast_flap_connection.disconnected();
tracing::info!(name = %cname, "backbone client disconnected");
// Proactive notify so broadcasts don't target dead tx.
let _ = dereg_tx
@@ -305,10 +615,14 @@ pub async fn spawn_backbone_server(
online: c_online,
rxb: Some(c_rxb),
txb: Some(c_txb),
inspection: None,
tx: c_tx,
read_task: read_handle,
};
if handle_tx.send(handle).await.is_err() {
if handoff_accepted_interface(&handle_tx, handle)
.await
.is_err()
{
tracing::warn!("backbone handle registry closed");
break;
}
@@ -338,6 +652,7 @@ pub async fn spawn_backbone_server(
online,
rxb: Some(Arc::new(AtomicU64::new(0))),
txb: Some(Arc::new(AtomicU64::new(0))),
inspection: Some(inspection),
tx,
read_task,
})
@@ -506,6 +821,7 @@ pub async fn spawn_backbone_client(
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: None,
tx,
read_task,
})
@@ -514,6 +830,102 @@ pub async fn spawn_backbone_client(
#[cfg(test)]
mod tests {
use super::*;
use std::net::{Ipv4Addr, SocketAddr};
#[derive(Clone)]
struct TestClock {
now: Arc<Mutex<Duration>>,
}
impl TestClock {
fn new() -> Self {
Self {
now: Arc::new(Mutex::new(Duration::ZERO)),
}
}
fn advance(&self, duration: Duration) {
let mut now = self.now.lock().unwrap_or_else(|e| e.into_inner());
*now = now
.checked_add(duration)
.expect("test monotonic clock overflow");
}
}
impl MonotonicClock for TestClock {
fn now(&self) -> Duration {
*self.now.lock().unwrap_or_else(|e| e.into_inner())
}
}
fn test_runtime(capacity: usize) -> (FastFlapRuntime, TestClock) {
let clock = TestClock::new();
(
FastFlapRuntime {
clock: Arc::new(clock.clone()),
table: Arc::new(Mutex::new(FastFlapTable::new(capacity))),
},
clock,
)
}
fn default_policy() -> FastFlapPolicy {
FastFlapPolicy {
enabled: BLOCK_FAST_FLAPPING,
threshold: FAST_FLAPPING_THRESHOLD,
grace: FAST_FLAPPING_GRACE,
block_time: FAST_FLAPPING_BLOCK_TIME,
}
}
fn allow_connection(
runtime: &FastFlapRuntime,
ip: IpAddr,
policy: FastFlapPolicy,
) -> FastFlapConnection {
match runtime.admit(ip, policy) {
FastFlapAdmission::Allowed(connection) => connection,
FastFlapAdmission::Rejected { flaps } => {
panic!("expected connection from {ip} to be allowed, recorded flaps: {flaps}")
}
}
}
fn assert_rejected(runtime: &FastFlapRuntime, ip: IpAddr, policy: FastFlapPolicy) {
assert!(matches!(
runtime.admit(ip, policy),
FastFlapAdmission::Rejected { .. }
));
}
fn record_short_connection(
runtime: &FastFlapRuntime,
clock: &TestClock,
ip: IpAddr,
policy: FastFlapPolicy,
) {
let connection = allow_connection(runtime, ip, policy);
clock.advance(Duration::from_millis(1));
connection.disconnected();
}
fn tracked_flaps(runtime: &FastFlapRuntime, ip: IpAddr) -> Option<u64> {
runtime
.table
.lock()
.unwrap_or_else(|e| e.into_inner())
.entries
.get(&ip)
.map(|entry| entry.flaps)
}
fn inspection_snapshot(handle: &InterfaceHandle) -> InterfaceInspectionSnapshot {
handle
.inspection
.as_ref()
.expect("backbone listener exposes aggregate inspection")
.snapshot()
}
#[test]
fn test_backbone_server_config() {
@@ -521,6 +933,13 @@ mod tests {
assert_eq!(cfg.listen_port, 4243);
assert!(!cfg.prefer_ipv6);
assert!(cfg.device.is_none());
assert!(cfg.block_fast_flapping);
assert_eq!(cfg.fast_flapping_threshold, Duration::from_secs(20));
assert_eq!(cfg.fast_flapping_grace, 5);
assert_eq!(
cfg.fast_flapping_block_time,
Duration::from_secs(12 * 60 * 60)
);
}
#[test]
@@ -573,6 +992,316 @@ mod tests {
assert!(mtu >= rns_wire::constants::MTU as u32 / 2);
}
#[test]
fn fast_flap_grace_is_strictly_greater_than_five() {
let (runtime, clock) = test_runtime(16);
let policy = default_policy();
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1));
// Upstream's strict `flaps > grace` admits and records six short
// connections for grace=5. The following (seventh) admission blocks.
for _ in 0..=policy.grace {
record_short_connection(&runtime, &clock, ip, policy);
}
assert_eq!(tracked_flaps(&runtime, ip), Some(6));
assert_rejected(&runtime, ip, policy);
}
#[test]
fn threshold_and_expiry_boundaries_are_strict() {
let (runtime, clock) = test_runtime(16);
let mut policy = default_policy();
policy.grace = 0;
let stable_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 2));
let blocked_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 3));
let stable = allow_connection(&runtime, stable_ip, policy);
clock.advance(policy.threshold);
stable.disconnected();
assert_eq!(tracked_flaps(&runtime, stable_ip), None);
record_short_connection(&runtime, &clock, blocked_ip, policy);
clock.advance(policy.block_time);
assert_rejected(&runtime, blocked_ip, policy);
clock.advance(Duration::from_nanos(1));
let readmitted = allow_connection(&runtime, blocked_ip, policy);
assert_eq!(tracked_flaps(&runtime, blocked_ip), None);
readmitted.disconnected();
}
#[test]
fn stable_connection_does_not_reset_existing_flaps() {
let (runtime, clock) = test_runtime(16);
let mut policy = default_policy();
policy.grace = 1;
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 4));
record_short_connection(&runtime, &clock, ip, policy);
let stable = allow_connection(&runtime, ip, policy);
clock.advance(policy.threshold);
stable.disconnected();
assert_eq!(tracked_flaps(&runtime, ip), Some(1));
record_short_connection(&runtime, &clock, ip, policy);
assert_eq!(tracked_flaps(&runtime, ip), Some(2));
assert_rejected(&runtime, ip, policy);
}
#[test]
fn rejected_connection_does_not_refresh_expiry() {
let (runtime, clock) = test_runtime(16);
let mut policy = default_policy();
policy.grace = 0;
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 5));
record_short_connection(&runtime, &clock, ip, policy);
clock.advance(policy.block_time - Duration::from_nanos(1));
assert_rejected(&runtime, ip, policy);
clock.advance(Duration::from_nanos(2));
let readmitted = allow_connection(&runtime, ip, policy);
assert_eq!(tracked_flaps(&runtime, ip), None);
readmitted.disconnected();
}
#[test]
fn disabled_policy_neither_tracks_nor_blocks() {
let (runtime, clock) = test_runtime(16);
let mut policy = default_policy();
policy.enabled = false;
policy.grace = 0;
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 6));
for _ in 0..10 {
record_short_connection(&runtime, &clock, ip, policy);
}
assert_eq!(tracked_flaps(&runtime, ip), None);
let admitted = allow_connection(&runtime, ip, policy);
admitted.disconnected();
let active_clients = AtomicU64::new(0);
assert_eq!(
runtime.inspection_snapshot(policy, &active_clients),
InterfaceInspectionSnapshot {
active_clients: Some(0),
blocked_ips: Some(0),
}
);
}
#[test]
fn inspection_uses_strict_grace_and_expiry_boundaries() {
let (runtime, clock) = test_runtime(16);
let policy = default_policy();
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 12));
let active_clients = AtomicU64::new(3);
for _ in 0..policy.grace {
record_short_connection(&runtime, &clock, ip, policy);
}
assert_eq!(
runtime.inspection_snapshot(policy, &active_clients),
InterfaceInspectionSnapshot {
active_clients: Some(3),
blocked_ips: Some(0),
}
);
record_short_connection(&runtime, &clock, ip, policy);
assert_eq!(
runtime
.inspection_snapshot(policy, &active_clients)
.blocked_ips,
Some(1)
);
clock.advance(policy.block_time);
assert_eq!(
runtime
.inspection_snapshot(policy, &active_clients)
.blocked_ips,
Some(1)
);
clock.advance(Duration::from_nanos(1));
assert_eq!(
runtime
.inspection_snapshot(policy, &active_clients)
.blocked_ips,
Some(0)
);
}
#[test]
fn repeated_inspection_snapshots_are_live_and_non_destructive() {
let (runtime, clock) = test_runtime(16);
let mut policy = default_policy();
policy.grace = 0;
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 13));
let active_clients = AtomicU64::new(1);
record_short_connection(&runtime, &clock, ip, policy);
let first = runtime.inspection_snapshot(policy, &active_clients);
let second = runtime.inspection_snapshot(policy, &active_clients);
assert_eq!(first, second);
assert_eq!(first.active_clients, Some(1));
assert_eq!(first.blocked_ips, Some(1));
active_clients.store(2, Ordering::Relaxed);
assert_eq!(
runtime
.inspection_snapshot(policy, &active_clients)
.active_clients,
Some(2)
);
}
#[test]
fn blocking_is_ip_scoped() {
let (runtime, clock) = test_runtime(16);
let mut policy = default_policy();
policy.grace = 0;
let blocked_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 7));
let other_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 8));
record_short_connection(&runtime, &clock, blocked_ip, policy);
assert_rejected(&runtime, blocked_ip, policy);
let other = allow_connection(&runtime, other_ip, policy);
other.disconnected();
}
#[test]
fn listeners_share_one_process_global_ip_keyspace() {
let clock = TestClock::new();
let table = Arc::new(Mutex::new(FastFlapTable::new(16)));
let first_listener = FastFlapRuntime {
clock: Arc::new(clock.clone()),
table: Arc::clone(&table),
};
let second_listener = FastFlapRuntime {
clock: Arc::new(clock.clone()),
table,
};
let policy = default_policy();
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 9));
for index in 0..=policy.grace {
let listener = if index % 2 == 0 {
&first_listener
} else {
&second_listener
};
record_short_connection(listener, &clock, ip, policy);
}
assert_rejected(&first_listener, ip, policy);
assert_rejected(&second_listener, ip, policy);
}
#[test]
fn full_table_preserves_unexpired_entries_and_reuses_expired_slots() {
let (runtime, clock) = test_runtime(1);
let mut policy = default_policy();
policy.grace = 0;
let tracked_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 10));
let untracked_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 11));
record_short_connection(&runtime, &clock, tracked_ip, policy);
record_short_connection(&runtime, &clock, untracked_ip, policy);
assert_eq!(tracked_flaps(&runtime, tracked_ip), Some(1));
assert_eq!(tracked_flaps(&runtime, untracked_ip), None);
assert_rejected(&runtime, tracked_ip, policy);
let untracked = allow_connection(&runtime, untracked_ip, policy);
untracked.disconnected();
clock.advance(policy.block_time + Duration::from_nanos(1));
record_short_connection(&runtime, &clock, untracked_ip, policy);
assert_eq!(tracked_flaps(&runtime, tracked_ip), None);
assert_eq!(tracked_flaps(&runtime, untracked_ip), Some(1));
}
#[tokio::test]
async fn aborted_child_read_task_records_short_connection() {
let (runtime, clock) = test_runtime(16);
let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
.await
.unwrap();
let listen_addr = listener.local_addr().unwrap();
let config =
BackboneServerConfig::new("abort-accounting-test", "127.0.0.1", listen_addr.port());
let id_gen = Arc::new(AtomicU64::new(100));
let (transport_tx, _transport_rx) = mpsc::channel(8);
let (handle_tx, mut handle_rx) = mpsc::channel(8);
let parent = spawn_backbone_server_on_listener(
config,
1,
id_gen,
transport_tx,
handle_tx,
runtime.clone(),
listener,
)
.unwrap();
assert_eq!(inspection_snapshot(&parent).active_clients, Some(0));
let _stream = TcpStream::connect(listen_addr).await.unwrap();
let child = tokio::time::timeout(Duration::from_secs(1), handle_rx.recv())
.await
.expect("accepted child handle timed out")
.expect("child handle channel closed");
assert_eq!(inspection_snapshot(&parent).active_clients, Some(1));
clock.advance(Duration::from_millis(1));
child.read_task.abort();
let _ = child.read_task.await;
assert_eq!(inspection_snapshot(&parent).active_clients, Some(0));
assert_eq!(
tracked_flaps(&runtime, IpAddr::V4(Ipv4Addr::LOCALHOST)),
Some(1)
);
parent.read_task.abort();
}
#[tokio::test]
async fn rejected_admission_does_not_consume_child_id_or_handle() {
let (runtime, clock) = test_runtime(16);
let mut policy = default_policy();
policy.grace = 0;
let ip = IpAddr::V4(Ipv4Addr::LOCALHOST);
record_short_connection(&runtime, &clock, ip, policy);
let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
.await
.unwrap();
let listen_addr = listener.local_addr().unwrap();
let mut config =
BackboneServerConfig::new("blocked-id-test", "127.0.0.1", listen_addr.port());
config.fast_flapping_grace = 0;
let id_gen = Arc::new(AtomicU64::new(100));
let (transport_tx, _transport_rx) = mpsc::channel(8);
let (handle_tx, mut handle_rx) = mpsc::channel(8);
let parent = spawn_backbone_server_on_listener(
config,
1,
Arc::clone(&id_gen),
transport_tx,
handle_tx,
runtime,
listener,
)
.unwrap();
assert_eq!(inspection_snapshot(&parent).active_clients, Some(0));
let mut stream = TcpStream::connect(listen_addr).await.unwrap();
let mut byte = [0u8; 1];
let closed = tokio::time::timeout(Duration::from_secs(1), stream.read(&mut byte))
.await
.expect("blocked connection was not closed");
assert!(matches!(closed, Ok(0) | Err(_)));
assert_eq!(id_gen.load(Ordering::SeqCst), 100);
assert!(handle_rx.try_recv().is_err());
assert_eq!(inspection_snapshot(&parent).active_clients, Some(0));
assert_eq!(inspection_snapshot(&parent).blocked_ips, Some(1));
parent.read_task.abort();
}
#[tokio::test]
async fn test_backbone_max_reconnect_dereg() {
// Connect attempts to a port nobody is listening on; with
@@ -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
File diff suppressed because it is too large. Load diff
+135 -54
View File
@@ -11,7 +11,9 @@ use tokio::net::TcpStream;
use tokio::sync::mpsc;
use crate::hdlc;
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
use crate::traits::{
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
};
use rns_transport::messages::{InboundPacket, TransportMessage};
pub const DEFAULT_SAM_ADDRESS: &str = "127.0.0.1";
@@ -262,6 +264,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 +354,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 +367,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 +388,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 +421,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 +442,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 +463,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 +488,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 +506,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,20 +551,19 @@ 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;
}
});
@@ -559,6 +583,7 @@ pub async fn spawn_i2p_client(
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: None,
tx,
read_task,
})
@@ -753,11 +778,15 @@ pub async fn spawn_i2p_server(
online: c_online,
rxb: Some(c_rxb),
txb: Some(c_txb),
inspection: None,
tx: c_tx,
read_task: c_read_task,
};
if handle_tx.send(handle).await.is_err() {
if handoff_accepted_interface(&handle_tx, handle)
.await
.is_err()
{
tracing::warn!("I2P server: handle registry channel closed");
online_task.store(false, Ordering::SeqCst);
return;
@@ -790,6 +819,7 @@ pub async fn spawn_i2p_server(
online,
rxb: Some(Arc::new(AtomicU64::new(0))),
txb: Some(Arc::new(AtomicU64::new(0))),
inspection: None,
tx,
read_task,
})
@@ -866,13 +896,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;
}
}
@@ -1000,24 +1068,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;
}
@@ -247,6 +276,7 @@ pub async fn spawn_kiss_interface(
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: None,
tx,
read_task,
})
@@ -262,6 +292,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]
+16 -1
View File
@@ -1,9 +1,12 @@
//! 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;
#[cfg(any(target_os = "android", test))]
mod android_usb_lifecycle;
pub mod auto;
pub mod ax25kiss;
pub mod backbone;
@@ -28,10 +31,22 @@ pub mod local;
pub mod pipe;
pub mod rnode;
pub mod rnode_admin;
pub mod rnode_capabilities;
#[cfg(any(
feature = "serial",
feature = "rnode-tcp",
feature = "ble",
target_os = "android",
test
))]
mod rnode_capability_preflight;
#[cfg(feature = "serial")]
pub mod rnode_multi;
pub mod rnode_protocol;
#[cfg(feature = "serial")]
pub mod serial;
#[cfg(feature = "serial")]
mod serial_io;
pub mod socket_tuning;
pub mod tcp;
pub mod traits;
+366 -183
View File
@@ -9,7 +9,9 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::mpsc;
use crate::hdlc;
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
use crate::traits::{
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
};
use rns_transport::messages::{InboundPacket, TransportMessage};
pub const LOCAL_MTU: u32 = 262_144;
@@ -28,6 +30,18 @@ pub fn socket_path(data_dir: Option<&std::path::Path>) -> std::path::PathBuf {
}
pub const FALLBACK_TCP_PORT: u16 = 37428;
#[cfg(unix)]
const LOCAL_RECONNECT_WAIT_SECS: u64 = 8;
#[cfg(all(unix, not(test)))]
fn local_reconnect_wait() -> std::time::Duration {
std::time::Duration::from_secs(LOCAL_RECONNECT_WAIT_SECS)
}
#[cfg(all(unix, test))]
fn local_reconnect_wait() -> std::time::Duration {
std::time::Duration::from_millis(50)
}
pub fn socket_path_for(instance_name: &str) -> String {
format!("/tmp/rns_{}.sock", instance_name)
@@ -148,6 +162,171 @@ async fn local_write_loop<W: AsyncWriteExt + Unpin>(
online.store(false, Ordering::SeqCst);
}
#[cfg(unix)]
enum LocalClientConnectionEnd {
Disconnected,
Detached,
}
/// Drive both halves of one initiating local-client connection in a single
/// task. Keeping the persistent outbound receiver here lets the Unix client
/// retain one stable `InterfaceHandle` while replacing only the socket after a
/// shared-instance restart.
#[cfg(unix)]
async fn run_local_client_connection<R, W>(
mut reader: R,
mut writer: W,
rx: &mut mpsc::Receiver<Bytes>,
interface_id: InterfaceId,
transport_tx: &mpsc::Sender<TransportMessage>,
rxb: &AtomicU64,
txb: &AtomicU64,
) -> LocalClientConnectionEnd
where
R: AsyncReadExt + Unpin,
W: AsyncWriteExt + Unpin,
{
let mut buf = [0u8; 8192];
let mut deframer = hdlc::HdlcDeframer::new();
loop {
tokio::select! {
read = reader.read(&mut buf) => {
match read {
Ok(0) => {
tracing::info!(interface_id, "local client read: EOF");
return LocalClientConnectionEnd::Disconnected;
}
Ok(n) => {
rxb.fetch_add(n as u64, Ordering::Relaxed);
for frame in deframer.feed(&buf[..n]) {
if frame.is_empty() {
continue;
}
let msg = TransportMessage::Inbound(InboundPacket {
raw: Bytes::from(frame),
interface_id,
rssi: None,
snr: None,
q: None,
});
if transport_tx.send(msg).await.is_err() {
tracing::warn!(interface_id, "transport channel closed");
return LocalClientConnectionEnd::Detached;
}
}
}
Err(error) => {
tracing::warn!(interface_id, %error, "local client read error");
return LocalClientConnectionEnd::Disconnected;
}
}
}
outbound = rx.recv() => {
let Some(data) = outbound else {
return LocalClientConnectionEnd::Detached;
};
let framed = hdlc::frame(&data);
if let Err(error) = writer.write_all(&framed).await {
tracing::warn!(interface_id, %error, "local client write error");
return LocalClientConnectionEnd::Disconnected;
}
txb.fetch_add(framed.len() as u64, Ordering::Relaxed);
}
}
}
}
/// Per-stream wiring shared by both platform variants: write loop, read task,
/// and the connection's `InterfaceHandle`. `dereg_on_disconnect` is set for
/// accepted server-side clients so transport drops them immediately on EOF.
fn wire_local_stream<R, W>(
id: InterfaceId,
name: String,
parent_id: Option<InterfaceId>,
reader: R,
writer: W,
transport_tx: mpsc::Sender<TransportMessage>,
dereg_on_disconnect: bool,
) -> InterfaceHandle
where
R: AsyncReadExt + Unpin + Send + 'static,
W: AsyncWriteExt + Unpin + Send + 'static,
{
let 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),
inspection: None,
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))),
inspection: None,
tx,
read_task,
}
}
#[cfg(unix)]
mod platform {
use super::*;
@@ -238,51 +417,20 @@ mod platform {
let client_name = format!("{}/client_{}", config.name, client_id);
tracing::info!(name = %client_name, "local client connected");
let c_online = Arc::new(AtomicBool::new(true));
let c_rxb = Arc::new(AtomicU64::new(0));
let c_txb = Arc::new(AtomicU64::new(0));
let (c_tx, c_rx) = mpsc::channel::<Bytes>(256);
let (reader, writer) = stream.into_split();
let c_online2 = c_online.clone();
let c_txb2 = c_txb.clone();
tokio::spawn(local_write_loop(writer, c_rx, c_online2, c_txb2));
let c_online3 = c_online.clone();
let c_rxb2 = c_rxb.clone();
let transport_tx2 = transport_tx.clone();
let dereg_tx = transport_tx.clone();
let cname = client_name.clone();
let read_handle = tokio::spawn(async move {
local_read_loop(reader, client_id, transport_tx2, c_online3, c_rxb2)
.await;
tracing::info!(name = %cname, "local client disconnected");
// Proactively notify so transport drops immediately.
let _ = dereg_tx
.send(TransportMessage::DeregisterInterface { id: client_id })
.await;
});
let handle = InterfaceHandle {
id: client_id,
parent_id: Some(0),
name: client_name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online: c_online,
rxb: Some(c_rxb),
txb: Some(c_txb),
tx: c_tx,
read_task: read_handle,
};
if handle_tx.send(handle).await.is_err() {
let handle = wire_local_stream(
client_id,
client_name,
Some(0),
reader,
writer,
transport_tx.clone(),
true,
);
if handoff_accepted_interface(&handle_tx, handle)
.await
.is_err()
{
tracing::warn!("local handle registry closed");
break;
}
@@ -296,28 +444,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,
parent_id: None,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
outbound: false,
forward: false,
repeat: false,
},
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online,
rxb: Some(server_rxb),
txb: Some(server_txb),
tx,
read_task,
})
Ok(server_listener_handle(name, online, tx, read_task))
}
pub async fn spawn_local_client_impl(
@@ -325,30 +452,81 @@ mod platform {
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let stream = connect_unix_stream(&config.socket_path).await?;
let initial_stream = connect_unix_stream(&config.socket_path).await?;
tracing::info!(name = %config.name, path = %display_socket_path(&config.socket_path), "local client connected");
let online = Arc::new(AtomicBool::new(true));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let (tx, rx) = mpsc::channel::<Bytes>(256);
let (reader, writer) = stream.into_split();
let rxb = Arc::new(AtomicU64::new(0));
let txb = Arc::new(AtomicU64::new(0));
let (tx, mut rx) = mpsc::channel::<Bytes>(256);
let online_w = online.clone();
let task_txb = shared_txb.clone();
tokio::spawn(local_write_loop(writer, rx, online_w, task_txb));
let online_r = online.clone();
let task_rxb = shared_rxb.clone();
let name = config.name.clone();
let task_online = online.clone();
let task_rxb = rxb.clone();
let task_txb = txb.clone();
let task_name = config.name.clone();
let task_socket_path = config.socket_path.clone();
let read_task = tokio::spawn(async move {
local_read_loop(reader, id, transport_tx, online_r, task_rxb).await;
let mut stream = initial_stream;
loop {
let (reader, writer) = stream.into_split();
let end = run_local_client_connection(
reader,
writer,
&mut rx,
id,
&transport_tx,
&task_rxb,
&task_txb,
)
.await;
task_online.store(false, Ordering::SeqCst);
if matches!(end, LocalClientConnectionEnd::Detached)
|| transport_tx.is_closed()
|| rx.is_closed()
{
return;
}
tracing::warn!(
name = %task_name,
path = %display_socket_path(&task_socket_path),
wait_seconds = LOCAL_RECONNECT_WAIT_SECS,
"local shared-instance connection lost; reconnecting"
);
loop {
tokio::time::sleep(local_reconnect_wait()).await;
if transport_tx.is_closed() || rx.is_closed() {
return;
}
match connect_unix_stream(&task_socket_path).await {
Ok(connected) => {
stream = connected;
task_online.store(true, Ordering::SeqCst);
tracing::info!(
name = %task_name,
path = %display_socket_path(&task_socket_path),
"local shared-instance client reconnected"
);
break;
}
Err(error) => {
tracing::debug!(
name = %task_name,
path = %display_socket_path(&task_socket_path),
%error,
"local shared-instance reconnect failed"
);
}
}
}
}
});
Ok(InterfaceHandle {
id,
parent_id: None,
name,
name: config.name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
@@ -359,8 +537,9 @@ mod platform {
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
rxb: Some(rxb),
txb: Some(txb),
inspection: None,
tx,
read_task,
})
@@ -407,51 +586,20 @@ mod platform {
let client_name = format!("{}/client_{}", config.name, client_id);
tracing::info!(name = %client_name, peer = %peer, "local client connected (TCP)");
let c_online = Arc::new(AtomicBool::new(true));
let c_rxb = Arc::new(AtomicU64::new(0));
let c_txb = Arc::new(AtomicU64::new(0));
let (c_tx, c_rx) = mpsc::channel::<Bytes>(256);
let (reader, writer) = stream.into_split();
let c_online2 = c_online.clone();
let c_txb2 = c_txb.clone();
tokio::spawn(local_write_loop(writer, c_rx, c_online2, c_txb2));
let c_online3 = c_online.clone();
let c_rxb2 = c_rxb.clone();
let transport_tx2 = transport_tx.clone();
let dereg_tx = transport_tx.clone();
let cname = client_name.clone();
let read_handle = tokio::spawn(async move {
local_read_loop(reader, client_id, transport_tx2, c_online3, c_rxb2)
.await;
tracing::info!(name = %cname, "local client disconnected");
// See unix variant — notify proactively to avoid zombies.
let _ = dereg_tx
.send(TransportMessage::DeregisterInterface { id: client_id })
.await;
});
let handle = InterfaceHandle {
id: client_id,
parent_id: Some(0),
name: client_name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online: c_online,
rxb: Some(c_rxb),
txb: Some(c_txb),
tx: c_tx,
read_task: read_handle,
};
if handle_tx.send(handle).await.is_err() {
let handle = wire_local_stream(
client_id,
client_name,
Some(0),
reader,
writer,
transport_tx.clone(),
true,
);
if handoff_accepted_interface(&handle_tx, handle)
.await
.is_err()
{
tracing::warn!("local handle registry closed");
break;
}
@@ -465,28 +613,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,
parent_id: None,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
outbound: false,
forward: false,
repeat: false,
},
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online,
rxb: Some(server_rxb),
txb: Some(server_txb),
tx,
read_task,
})
Ok(server_listener_handle(name, online, tx, read_task))
}
pub async fn spawn_local_client_impl(
@@ -498,42 +625,16 @@ mod platform {
let stream = TcpStream::connect(&addr).await?;
tracing::info!(name = %config.name, addr = %addr, "local client connected (TCP fallback)");
let online = Arc::new(AtomicBool::new(true));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
let (tx, rx) = mpsc::channel::<Bytes>(256);
let (reader, writer) = stream.into_split();
let online_w = online.clone();
let task_txb = shared_txb.clone();
tokio::spawn(local_write_loop(writer, rx, online_w, task_txb));
let online_r = online.clone();
let task_rxb = shared_rxb.clone();
let name = config.name.clone();
let read_task = tokio::spawn(async move {
local_read_loop(reader, id, transport_tx, online_r, task_rxb).await;
});
Ok(InterfaceHandle {
Ok(wire_local_stream(
id,
parent_id: None,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
inbound: true,
outbound: true,
forward: false,
repeat: false,
},
bitrate: 1_000_000_000,
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
tx,
read_task,
})
config.name.clone(),
None,
reader,
writer,
transport_tx,
false,
))
}
}
@@ -752,4 +853,86 @@ mod tests {
server_handle.read_task.abort();
let _ = std::fs::remove_file(&socket_path);
}
#[cfg(unix)]
#[tokio::test]
async fn test_local_client_reconnects_after_server_restart() {
let (transport_tx, mut transport_rx) = mpsc::channel::<TransportMessage>(64);
let (handle_tx, mut handle_rx) = mpsc::channel::<InterfaceHandle>(8);
let id_gen = Arc::new(AtomicU64::new(900));
let socket_path = unique_test_socket_path("reticulum_reconnect_test");
let server_config = || LocalServerConfig {
socket_path: socket_path.clone(),
name: "restartable-local-server".to_string(),
};
let server_handle = spawn_local_server(
server_config(),
id_gen.clone(),
transport_tx.clone(),
handle_tx.clone(),
)
.await
.unwrap();
let client_handle = spawn_local_client(
LocalClientConfig {
socket_path: socket_path.clone(),
name: "persistent-local-client".to_string(),
},
88,
transport_tx.clone(),
)
.await
.unwrap();
let first_accepted =
tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for first accepted client")
.expect("handle channel closed");
server_handle.read_task.abort();
first_accepted.read_task.abort();
drop(first_accepted.tx);
tokio::time::timeout(std::time::Duration::from_secs(3), async {
while client_handle.online.load(Ordering::SeqCst) {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.expect("client did not observe server shutdown");
let restarted_server =
spawn_local_server(server_config(), id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
let second_accepted =
tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("client did not reconnect to restarted server")
.expect("handle channel closed");
assert!(
client_handle.online.load(Ordering::SeqCst),
"stable client handle must return online after reconnect"
);
let payload = Bytes::from_static(b"after shared restart");
second_accepted.tx.send(payload.clone()).await.unwrap();
let inbound = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv())
.await
.expect("timeout waiting for post-restart frame")
.expect("transport channel closed");
match inbound {
TransportMessage::Inbound(packet) => {
assert_eq!(packet.interface_id, 88);
assert_eq!(packet.raw, payload);
}
other => panic!("unexpected post-restart message: {other:?}"),
}
restarted_server.read_task.abort();
second_accepted.read_task.abort();
drop(second_accepted.tx);
client_handle.read_task.abort();
let _ = std::fs::remove_file(&socket_path);
}
}
+1
View File
@@ -203,6 +203,7 @@ pub async fn spawn_pipe_interface(
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: None,
tx,
read_task,
})
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,978 @@
//! Privacy-bounded, read-only RNode capability parsing.
//!
//! RNode EEPROM identity information contains serial, manufacturing, checksum,
//! signature, and other device-specific bytes. This module validates the
//! immutable identity prefix in place, then returns only copyable product/model
//! codes and reviewed radio limits. It never retains the source image or
//! exposes identity, signature, configuration, or raw EEPROM fields.
use md5::{Digest, Md5};
use crate::rnode::{RNodeConfigValidationError, RNodeRadioSettings};
const PRODUCT_ADDRESS: usize = 0x00;
const MODEL_ADDRESS: usize = 0x01;
const IDENTITY_CHECKSUM_INPUT_END: usize = 0x0B;
const CHECKSUM_ADDRESS: usize = 0x0B;
const CHECKSUM_END: usize = 0x1B;
const INFO_LOCK_ADDRESS: usize = 0x9B;
const REQUIRED_EEPROM_LEN: usize = INFO_LOCK_ADDRESS + 1;
const INFO_LOCK_BYTE: u8 = 0x73;
/// A validated, privacy-bounded RNode capability description.
///
/// The value owns no EEPROM bytes and contains no stable device identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct RNodeCapabilities {
product_code: u8,
model_code: u8,
radio: RNodeRadioCapabilities,
}
impl RNodeCapabilities {
/// The RNode product code stored in the validated identity prefix.
pub const fn product_code(self) -> u8 {
self.product_code
}
/// A reviewed display name for the product code, when one is known.
///
/// This is a static code-table lookup; no label is read from or retained
/// from the EEPROM image.
pub const fn product_name(self) -> Option<&'static str> {
rnode_product_name(self.product_code)
}
/// The exact, unnormalised RNode model code stored in the identity prefix.
pub const fn model_code(self) -> u8 {
self.model_code
}
/// Reviewed radio limits for the model, or [`RNodeRadioCapabilities::Unknown`].
pub const fn radio(self) -> RNodeRadioCapabilities {
self.radio
}
}
/// Whether a validated model has a reviewed radio capability profile.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RNodeRadioCapabilities {
/// The model maps to a reviewed, internally consistent numeric profile.
Known(RNodeKnownRadioCapabilities),
/// The model is unknown, ambiguous, or deliberately quarantined.
Unknown,
}
/// Reviewed numeric limits for a known RNode radio model.
///
/// For a dual-radio product, these limits describe the reviewed generic/main
/// RNode radio profile. They do not claim to span every band supported by each
/// physically present secondary radio.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct RNodeKnownRadioCapabilities {
family: RNodeRadioFamily,
min_frequency_hz: u32,
max_frequency_hz: u32,
max_tx_power_dbm: u8,
}
impl RNodeKnownRadioCapabilities {
/// The radio family associated with the model.
pub const fn family(self) -> RNodeRadioFamily {
self.family
}
/// The inclusive lower frequency bound in hertz.
pub const fn min_frequency_hz(self) -> u32 {
self.min_frequency_hz
}
/// The inclusive upper frequency bound in hertz.
pub const fn max_frequency_hz(self) -> u32 {
self.max_frequency_hz
}
/// The inclusive maximum transmit power in dBm.
pub const fn max_tx_power_dbm(self) -> u8 {
self.max_tx_power_dbm
}
/// Whether `frequency_hz` lies within the inclusive reviewed bounds.
pub const fn supports_frequency(self, frequency_hz: u32) -> bool {
frequency_hz >= self.min_frequency_hz && frequency_hz <= self.max_frequency_hz
}
/// Whether `tx_power_dbm` is at or below the inclusive reviewed maximum.
pub const fn supports_tx_power(self, tx_power_dbm: u8) -> bool {
tx_power_dbm <= self.max_tx_power_dbm
}
}
/// Radio families represented by reviewed RNode model profiles.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RNodeRadioFamily {
Sx1262,
Sx1268,
Sx1276,
Sx1278,
Sx1280,
/// A dual-radio product.
///
/// Its numeric capability bounds describe the reviewed generic/main radio
/// profile, not every band of the physically present secondary radio.
Sx1262AndSx1280,
}
/// Why a capability image could not be accepted.
///
/// Errors intentionally contain no EEPROM contents, hashes, or identity
/// values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum RNodeCapabilityParseError {
#[error("RNode EEPROM image is too short (need {required} bytes, got {actual})")]
TooShort { required: usize, actual: usize },
#[error("RNode identity information is not locked")]
InfoNotLocked,
#[error("RNode identity checksum is invalid")]
ChecksumMismatch,
}
/// Model-specific classification for a validated RNode capability image.
///
/// `Verified` means the exact model has a reviewed capability profile.
/// `Unverified` means the exact stored model is unknown or quarantined, so no
/// model profile was inferred. `Unprovisioned` means the device presented no
/// locked EEPROM identity at all, so no product or model claim exists and only
/// generic validation was applied. A `Verified` classification alone does not
/// admit radio settings; use [`admit_rnode_radio_settings`] for that.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RNodeRadioAdmission {
Verified { product_code: u8, model_code: u8 },
Unverified { product_code: u8, model_code: u8 },
Unprovisioned,
}
impl RNodeRadioAdmission {
/// Validated EEPROM product code, when a locked identity supplied one.
pub const fn product_code(self) -> Option<u8> {
match self {
Self::Verified { product_code, .. } | Self::Unverified { product_code, .. } => {
Some(product_code)
}
Self::Unprovisioned => None,
}
}
/// Exact, unnormalised EEPROM model code, when a locked identity supplied one.
pub const fn model_code(self) -> Option<u8> {
match self {
Self::Verified { model_code, .. } | Self::Unverified { model_code, .. } => {
Some(model_code)
}
Self::Unprovisioned => None,
}
}
/// Whether a reviewed model-specific profile was available.
pub const fn is_verified(self) -> bool {
matches!(self, Self::Verified { .. })
}
}
/// Typed failure from model-specific RNode radio admission.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum RNodeRadioAdmissionError {
#[error("generic RNode radio settings are invalid: {0}")]
GenericValidation(#[source] RNodeConfigValidationError),
#[error("frequency {requested_hz} Hz is outside verified model range {min_hz}..={max_hz} Hz")]
FrequencyOutOfRange {
requested_hz: u32,
min_hz: u32,
max_hz: u32,
},
#[error("TX power {requested_dbm} dBm exceeds verified model maximum {max_dbm} dBm")]
TxPowerExceedsMaximum { requested_dbm: u8, max_dbm: u8 },
}
/// Bounded classification of a full-length RNode EEPROM image.
///
/// `Provisioned` carries validated capabilities from a locked, checksummed
/// identity. `Unprovisioned` means the info lock at `0x9b` is absent: the
/// device carries no attested identity, so product, model, and checksum bytes
/// are deliberately never read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RNodeEepromImage {
Provisioned(RNodeCapabilities),
Unprovisioned,
}
/// Classify an EEPROM image, admitting unprovisioned devices as a typed state.
///
/// The image must still span the identity-information lock at `0x9b`. An
/// unlocked image classifies as [`RNodeEepromImage::Unprovisioned`] without
/// consulting the checksum or identity bytes — an unattested model byte must
/// never impose or relax model-specific limits. A locked image validates the
/// MD5 checksum over the exact stored bytes `0x00..0x0b` (model aliases are
/// deliberately not normalised first); bytes after the identity prefix,
/// including the signature region, are ignored.
pub fn classify_rnode_eeprom_image(
eeprom: &[u8],
) -> Result<RNodeEepromImage, RNodeCapabilityParseError> {
if eeprom.len() < REQUIRED_EEPROM_LEN {
return Err(RNodeCapabilityParseError::TooShort {
required: REQUIRED_EEPROM_LEN,
actual: eeprom.len(),
});
}
if eeprom[INFO_LOCK_ADDRESS] != INFO_LOCK_BYTE {
return Ok(RNodeEepromImage::Unprovisioned);
}
let calculated: [u8; 16] = Md5::digest(&eeprom[..IDENTITY_CHECKSUM_INPUT_END]).into();
if calculated != eeprom[CHECKSUM_ADDRESS..CHECKSUM_END] {
return Err(RNodeCapabilityParseError::ChecksumMismatch);
}
let product_code = eeprom[PRODUCT_ADDRESS];
let model_code = eeprom[MODEL_ADDRESS];
let radio = rnode_model_capabilities(model_code);
Ok(RNodeEepromImage::Provisioned(RNodeCapabilities {
product_code,
model_code,
radio,
}))
}
/// Validate an EEPROM image and retain only non-identifying capability data.
///
/// Strict form of [`classify_rnode_eeprom_image`] for callers that require a
/// provisioned identity (for example rnodeconf mutation preflights): an
/// unlocked image is an [`RNodeCapabilityParseError::InfoNotLocked`] error
/// here rather than a typed classification.
pub fn parse_rnode_capabilities(
eeprom: &[u8],
) -> Result<RNodeCapabilities, RNodeCapabilityParseError> {
match classify_rnode_eeprom_image(eeprom)? {
RNodeEepromImage::Provisioned(capabilities) => Ok(capabilities),
RNodeEepromImage::Unprovisioned => Err(RNodeCapabilityParseError::InfoNotLocked),
}
}
/// Classify a validated model without admitting radio settings.
///
/// `capabilities` can only be obtained from a successfully validated EEPROM
/// image. Unknown, aliased, ambiguous, and quarantined model codes return
/// [`RNodeRadioAdmission::Unverified`] without normalisation or an inferred
/// profile.
pub fn classify_rnode_radio_capabilities(capabilities: RNodeCapabilities) -> RNodeRadioAdmission {
let product_code = capabilities.product_code();
let model_code = capabilities.model_code();
match capabilities.radio() {
RNodeRadioCapabilities::Known(_) => RNodeRadioAdmission::Verified {
product_code,
model_code,
},
RNodeRadioCapabilities::Unknown => RNodeRadioAdmission::Unverified {
product_code,
model_code,
},
}
}
/// Apply the sole lower-layer RF admission policy to validated capabilities.
///
/// Generic RNode validation runs first. Known exact model codes then enforce
/// their inclusive frequency range and maximum TX power. Unknown, aliased,
/// ambiguous, and quarantined model codes continue as an explicit
/// [`RNodeRadioAdmission::Unverified`] result without normalisation or an
/// inferred profile.
pub fn admit_rnode_radio_settings(
capabilities: RNodeCapabilities,
settings: RNodeRadioSettings,
) -> Result<RNodeRadioAdmission, RNodeRadioAdmissionError> {
settings
.validate()
.map_err(RNodeRadioAdmissionError::GenericValidation)?;
if let RNodeRadioCapabilities::Known(radio) = capabilities.radio() {
if !radio.supports_frequency(settings.frequency) {
return Err(RNodeRadioAdmissionError::FrequencyOutOfRange {
requested_hz: settings.frequency,
min_hz: radio.min_frequency_hz(),
max_hz: radio.max_frequency_hz(),
});
}
if !radio.supports_tx_power(settings.tx_power) {
return Err(RNodeRadioAdmissionError::TxPowerExceedsMaximum {
requested_dbm: settings.tx_power,
max_dbm: radio.max_tx_power_dbm(),
});
}
}
Ok(classify_rnode_radio_capabilities(capabilities))
}
/// Admit radio settings for a device that presented no locked EEPROM identity.
///
/// Only generic RNode validation applies: with no attested model there are no
/// model-specific limits to consult, matching the treatment of unknown and
/// quarantined model codes.
pub fn admit_unprovisioned_rnode_radio_settings(
settings: RNodeRadioSettings,
) -> Result<RNodeRadioAdmission, RNodeRadioAdmissionError> {
settings
.validate()
.map_err(RNodeRadioAdmissionError::GenericValidation)?;
Ok(RNodeRadioAdmission::Unprovisioned)
}
/// Return the reviewed display name for an RNode product code.
///
/// Unknown product codes return `None`. Names are static code-table values and
/// are never read from device-controlled EEPROM data.
pub const fn rnode_product_name(product_code: u8) -> Option<&'static str> {
Some(match product_code {
0x03 => "RNode",
0x10 => "RAK4631",
0x15 => "LilyGO T-Echo",
0x20 => "openCom XL",
0xB0 => "LilyGO LoRa32 v2.0",
0xB1 => "LilyGO LoRa32 v2.1",
0xB2 => "LilyGO LoRa32 v1.0",
0xC0 => "Heltec LoRa32 v2",
0xC1 => "Heltec LoRa32 v3",
0xC2 => "Heltec Mesh Node T114",
0xC3 => "Heltec LoRa32 v4",
0xD0 => "LilyGO T-Deck",
0xE0 => "LilyGO T-Beam",
0xEA => "LilyGO T-Beam Supreme",
0xEB => "Seeed XIAO ESP32S3 Wio-SX1262",
0xF0 => "Hombrew RNode",
_ => return None,
})
}
/// Return the reviewed radio capabilities for an exact RNode model code.
///
/// Unknown, ambiguous, and quarantined model codes return
/// [`RNodeRadioCapabilities::Unknown`]. In particular, EEPROM aliases are not
/// normalised by this lookup. Model codes `0xA6`, `0xAA`, and `0xC8` remain
/// quarantined because the trusted Rust sources do not establish a single,
/// internally consistent numeric capability profile for them.
pub fn rnode_model_capabilities(model_code: u8) -> RNodeRadioCapabilities {
KNOWN_RADIOS
.iter()
.find_map(|(candidate, profile)| (*candidate == model_code).then_some(*profile))
.map(RNodeRadioCapabilities::Known)
.unwrap_or(RNodeRadioCapabilities::Unknown)
}
const fn known(
family: RNodeRadioFamily,
min_frequency_hz: u32,
max_frequency_hz: u32,
max_tx_power_dbm: u8,
) -> RNodeKnownRadioCapabilities {
RNodeKnownRadioCapabilities {
family,
min_frequency_hz,
max_frequency_hz,
max_tx_power_dbm,
}
}
// Reviewed numeric profiles owned by this lower-core module. Firmware
// filenames and human labels intentionally do not cross this boundary.
// Models with aliases, contradictory ranges, ambiguous evidence, or explicitly
// unknown limits are absent and therefore resolve to Unknown.
const KNOWN_RADIOS: &[(u8, RNodeKnownRadioCapabilities)] = &[
(
0xA4,
known(RNodeRadioFamily::Sx1278, 410_000_000, 525_000_000, 14),
),
(
0xA9,
known(RNodeRadioFamily::Sx1276, 820_000_000, 1_020_000_000, 17),
),
(
0xA1,
known(RNodeRadioFamily::Sx1268, 410_000_000, 525_000_000, 22),
),
(
0xA5,
known(RNodeRadioFamily::Sx1278, 410_000_000, 525_000_000, 17),
),
(
0xAC,
known(RNodeRadioFamily::Sx1280, 2_400_000_000, 2_500_000_000, 20),
),
(
0xA2,
known(RNodeRadioFamily::Sx1278, 410_000_000, 525_000_000, 17),
),
(
0xA7,
known(RNodeRadioFamily::Sx1276, 820_000_000, 1_020_000_000, 17),
),
(
0xA3,
known(RNodeRadioFamily::Sx1278, 410_000_000, 525_000_000, 17),
),
(
0xA8,
known(RNodeRadioFamily::Sx1276, 820_000_000, 1_020_000_000, 17),
),
(
0xB3,
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
),
(
0xB8,
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
),
(
0xB4,
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
),
(
0xB9,
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
),
(
0xBA,
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
),
(
0xBB,
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
),
(
0xC4,
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
),
(
0xC9,
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
),
(
0xC5,
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
),
(
0xCA,
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
),
(
0xC6,
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
),
(
0xC7,
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
),
(
0xE4,
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
),
(
0xE9,
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
),
(
0xD4,
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
),
(
0xD9,
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
),
(
0xDB,
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
),
(
0xDC,
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
),
(
0xE3,
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
),
(
0xE8,
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
),
(
0x11,
known(RNodeRadioFamily::Sx1262, 430_000_000, 510_000_000, 22),
),
(
0x12,
known(RNodeRadioFamily::Sx1262, 779_000_000, 928_000_000, 22),
),
(
0x13,
known(
RNodeRadioFamily::Sx1262AndSx1280,
430_000_000,
510_000_000,
22,
),
),
(
0x14,
known(
RNodeRadioFamily::Sx1262AndSx1280,
779_000_000,
928_000_000,
22,
),
),
(
0x17,
known(RNodeRadioFamily::Sx1262, 779_000_000, 928_000_000, 22),
),
(
0x21,
known(
RNodeRadioFamily::Sx1262AndSx1280,
820_000_000,
960_000_000,
22,
),
),
(
0xDE,
known(RNodeRadioFamily::Sx1262, 420_000_000, 520_000_000, 22),
),
(
0xDD,
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
),
];
#[cfg(test)]
mod tests {
use super::*;
const PRODUCT: u8 = 0x03;
const QUARANTINED_MODELS: &[u8] = &[0x04, 0x09, 0x16, 0xA6, 0xAA, 0xC8, 0xFE, 0xFF];
fn image(model: u8) -> [u8; REQUIRED_EEPROM_LEN] {
let mut bytes = [0xA5; REQUIRED_EEPROM_LEN];
bytes[PRODUCT_ADDRESS] = PRODUCT;
bytes[MODEL_ADDRESS] = model;
bytes[0x02] = 0x07;
bytes[0x03..0x07].copy_from_slice(&0x1122_3344_u32.to_be_bytes());
bytes[0x07..0x0B].copy_from_slice(&0x5566_7788_u32.to_be_bytes());
let checksum: [u8; 16] = Md5::digest(&bytes[..IDENTITY_CHECKSUM_INPUT_END]).into();
bytes[CHECKSUM_ADDRESS..CHECKSUM_END].copy_from_slice(&checksum);
bytes[INFO_LOCK_ADDRESS] = INFO_LOCK_BYTE;
bytes
}
fn settings(frequency: u32, tx_power: u8) -> RNodeRadioSettings {
RNodeRadioSettings::new(frequency, 125_000, 7, 5, tx_power)
}
#[test]
fn requires_every_byte_through_info_lock() {
let short = &image(0xA4)[..REQUIRED_EEPROM_LEN - 1];
assert_eq!(
parse_rnode_capabilities(short),
Err(RNodeCapabilityParseError::TooShort {
required: 156,
actual: 155,
})
);
let exact = image(0xA4);
assert!(parse_rnode_capabilities(&exact).is_ok());
}
#[test]
fn rejects_unlocked_identity_information_before_checksum_validation() {
let mut bytes = image(0xA4);
bytes[INFO_LOCK_ADDRESS] = 0x00;
bytes[CHECKSUM_ADDRESS] ^= 0xFF;
assert_eq!(
parse_rnode_capabilities(&bytes),
Err(RNodeCapabilityParseError::InfoNotLocked)
);
}
#[test]
fn unlocked_images_classify_unprovisioned_without_reading_identity() {
// Both fresh-erase (0xFF) and zeroed lock bytes count as unlocked, and
// neither the checksum nor the identity bytes may be consulted.
for lock in [0x00, 0xFF] {
let mut bytes = image(0x11);
bytes[INFO_LOCK_ADDRESS] = lock;
for byte in &mut bytes[CHECKSUM_ADDRESS..CHECKSUM_END] {
*byte = 0xA5;
}
assert_eq!(
classify_rnode_eeprom_image(&bytes),
Ok(RNodeEepromImage::Unprovisioned),
"lock byte {lock:#04x} must classify unprovisioned"
);
}
}
#[test]
fn classification_preserves_strict_short_and_checksum_failures() {
let short = &image(0xA4)[..REQUIRED_EEPROM_LEN - 1];
assert_eq!(
classify_rnode_eeprom_image(short),
Err(RNodeCapabilityParseError::TooShort {
required: 156,
actual: 155,
})
);
let mut corrupt = image(0xA4);
corrupt[CHECKSUM_ADDRESS] ^= 0x01;
assert_eq!(
classify_rnode_eeprom_image(&corrupt),
Err(RNodeCapabilityParseError::ChecksumMismatch)
);
assert_eq!(
classify_rnode_eeprom_image(&image(0x11)),
Ok(RNodeEepromImage::Provisioned(
parse_rnode_capabilities(&image(0x11)).expect("valid image")
))
);
}
#[test]
fn unprovisioned_admission_applies_generic_validation_only() {
assert_eq!(
admit_unprovisioned_rnode_radio_settings(settings(868_000_000, 37)),
Ok(RNodeRadioAdmission::Unprovisioned)
);
assert!(matches!(
admit_unprovisioned_rnode_radio_settings(settings(1, 14)),
Err(RNodeRadioAdmissionError::GenericValidation(_))
));
}
#[test]
fn admission_codes_are_present_only_for_locked_identities() {
let verified = RNodeRadioAdmission::Verified {
product_code: PRODUCT,
model_code: 0x11,
};
assert_eq!(verified.product_code(), Some(PRODUCT));
assert_eq!(verified.model_code(), Some(0x11));
assert!(verified.is_verified());
assert_eq!(RNodeRadioAdmission::Unprovisioned.product_code(), None);
assert_eq!(RNodeRadioAdmission::Unprovisioned.model_code(), None);
assert!(!RNodeRadioAdmission::Unprovisioned.is_verified());
}
#[test]
fn checksum_covers_exact_identity_prefix_without_model_normalisation() {
let mut bytes = image(0x04);
let parsed = parse_rnode_capabilities(&bytes).expect("raw model checksum should validate");
assert_eq!(parsed.model_code(), 0x04);
assert_eq!(parsed.radio(), RNodeRadioCapabilities::Unknown);
// Replacing the raw alias with its nominal model invalidates the exact
// stored checksum; the parser must not normalise it first.
bytes[MODEL_ADDRESS] = 0xB4;
assert_eq!(
parse_rnode_capabilities(&bytes),
Err(RNodeCapabilityParseError::ChecksumMismatch)
);
}
#[test]
fn rejects_any_identity_prefix_checksum_mismatch() {
for address in 0..IDENTITY_CHECKSUM_INPUT_END {
let mut bytes = image(0xA4);
bytes[address] ^= 0x01;
assert_eq!(
parse_rnode_capabilities(&bytes),
Err(RNodeCapabilityParseError::ChecksumMismatch),
"identity byte {address:#04x} was not covered"
);
}
}
#[test]
fn returns_only_reviewed_codes_and_known_numeric_bounds() {
let parsed = parse_rnode_capabilities(&image(0xAC)).expect("valid known model");
assert_eq!(parsed.product_code(), PRODUCT);
assert_eq!(parsed.product_name(), Some("RNode"));
assert_eq!(parsed.model_code(), 0xAC);
assert_eq!(
parsed.radio(),
RNodeRadioCapabilities::Known(known(
RNodeRadioFamily::Sx1280,
2_400_000_000,
2_500_000_000,
20,
))
);
let low_band = parse_rnode_capabilities(&image(0x11)).expect("valid known model");
assert_eq!(
low_band.radio(),
RNodeRadioCapabilities::Known(known(
RNodeRadioFamily::Sx1262,
430_000_000,
510_000_000,
22,
))
);
}
#[test]
fn capability_support_helpers_include_both_boundaries() {
let parsed = parse_rnode_capabilities(&image(0x11)).expect("valid known model");
let RNodeRadioCapabilities::Known(radio) = parsed.radio() else {
panic!("model 0x11 must have a reviewed profile");
};
assert!(radio.supports_frequency(430_000_000));
assert!(radio.supports_frequency(510_000_000));
assert!(!radio.supports_frequency(429_999_999));
assert!(!radio.supports_frequency(510_000_001));
assert!(radio.supports_tx_power(0));
assert!(radio.supports_tx_power(22));
assert!(!radio.supports_tx_power(23));
}
#[test]
fn known_model_admission_includes_frequency_and_power_boundaries() {
let capabilities = parse_rnode_capabilities(&image(0x11)).expect("valid known model");
assert_eq!(
admit_rnode_radio_settings(capabilities, settings(430_000_000, 0)),
Ok(RNodeRadioAdmission::Verified {
product_code: PRODUCT,
model_code: 0x11,
})
);
assert_eq!(
admit_rnode_radio_settings(capabilities, settings(510_000_000, 22)),
Ok(RNodeRadioAdmission::Verified {
product_code: PRODUCT,
model_code: 0x11,
})
);
assert_eq!(
classify_rnode_radio_capabilities(capabilities),
RNodeRadioAdmission::Verified {
product_code: PRODUCT,
model_code: 0x11,
}
);
}
#[test]
fn known_model_admission_returns_typed_frequency_and_power_mismatches() {
let capabilities = parse_rnode_capabilities(&image(0x11)).expect("valid known model");
for (frequency, expected) in [
(
429_999_999,
RNodeRadioAdmissionError::FrequencyOutOfRange {
requested_hz: 429_999_999,
min_hz: 430_000_000,
max_hz: 510_000_000,
},
),
(
510_000_001,
RNodeRadioAdmissionError::FrequencyOutOfRange {
requested_hz: 510_000_001,
min_hz: 430_000_000,
max_hz: 510_000_000,
},
),
] {
assert_eq!(
admit_rnode_radio_settings(capabilities, settings(frequency, 22)),
Err(expected)
);
}
let error = admit_rnode_radio_settings(capabilities, settings(430_000_000, 23));
assert_eq!(
error,
Err(RNodeRadioAdmissionError::TxPowerExceedsMaximum {
requested_dbm: 23,
max_dbm: 22,
})
);
}
#[test]
fn unknown_and_quarantined_admission_is_explicitly_unverified() {
for model in std::iter::once(0x00).chain(QUARANTINED_MODELS.iter().copied()) {
let capabilities =
parse_rnode_capabilities(&image(model)).expect("valid identity image");
assert_eq!(
classify_rnode_radio_capabilities(capabilities),
RNodeRadioAdmission::Unverified {
product_code: PRODUCT,
model_code: model,
},
"model {model:#04x} classification must remain unverified"
);
assert_eq!(
admit_rnode_radio_settings(capabilities, settings(868_000_000, 37)),
Ok(RNodeRadioAdmission::Unverified {
product_code: PRODUCT,
model_code: model,
}),
"model {model:#04x} must remain unverified"
);
}
}
#[test]
fn generic_validation_precedes_known_and_unverified_model_policy() {
for model in [0x11, 0xA6] {
let capabilities = parse_rnode_capabilities(&image(model)).expect("valid identity");
let error = admit_rnode_radio_settings(capabilities, settings(1, 23))
.expect_err("model policy must not bypass generic validation");
assert!(
matches!(error, RNodeRadioAdmissionError::GenericValidation(_)),
"model {model:#04x} did not fail generic validation first: {error:?}"
);
}
}
#[test]
fn product_names_are_closed_static_lookups() {
const PRODUCTS: &[(u8, &str)] = &[
(0x03, "RNode"),
(0x10, "RAK4631"),
(0x15, "LilyGO T-Echo"),
(0x20, "openCom XL"),
(0xB0, "LilyGO LoRa32 v2.0"),
(0xB1, "LilyGO LoRa32 v2.1"),
(0xB2, "LilyGO LoRa32 v1.0"),
(0xC0, "Heltec LoRa32 v2"),
(0xC1, "Heltec LoRa32 v3"),
(0xC2, "Heltec Mesh Node T114"),
(0xC3, "Heltec LoRa32 v4"),
(0xD0, "LilyGO T-Deck"),
(0xE0, "LilyGO T-Beam"),
(0xEA, "LilyGO T-Beam Supreme"),
(0xEB, "Seeed XIAO ESP32S3 Wio-SX1262"),
(0xF0, "Hombrew RNode"),
];
for (index, (code, name)) in PRODUCTS.iter().enumerate() {
assert_eq!(rnode_product_name(*code), Some(*name));
assert!(
!PRODUCTS[..index].iter().any(|(earlier, _)| earlier == code),
"duplicate product code {code:#04x}"
);
}
assert_eq!(rnode_product_name(0x00), None);
assert_eq!(rnode_product_name(0xFF), None);
}
#[test]
fn unknown_and_quarantined_models_never_invent_limits() {
for model in std::iter::once(0x00).chain(QUARANTINED_MODELS.iter().copied()) {
let parsed = parse_rnode_capabilities(&image(model)).expect("valid identity image");
assert_eq!(parsed.model_code(), model);
assert_eq!(
parsed.radio(),
RNodeRadioCapabilities::Unknown,
"model {model:#04x} must remain unknown"
);
}
}
#[test]
fn direct_model_lookup_is_closed_and_does_not_normalise_quarantine() {
assert_eq!(
rnode_model_capabilities(0xA4),
RNodeRadioCapabilities::Known(known(
RNodeRadioFamily::Sx1278,
410_000_000,
525_000_000,
14,
))
);
for model in std::iter::once(0x00).chain(QUARANTINED_MODELS.iter().copied()) {
assert_eq!(
rnode_model_capabilities(model),
RNodeRadioCapabilities::Unknown,
"model {model:#04x} must remain unknown"
);
}
}
#[test]
fn signature_and_other_ignored_bytes_do_not_affect_result() {
let baseline_image = image(0xA4);
let baseline = parse_rnode_capabilities(&baseline_image).expect("valid image");
let mut mutated = baseline_image;
for (index, byte) in mutated[CHECKSUM_END..INFO_LOCK_ADDRESS]
.iter_mut()
.enumerate()
{
*byte = index as u8;
}
assert_eq!(
parse_rnode_capabilities(&mutated),
Ok(baseline),
"signature and non-capability bytes must be ignored"
);
}
#[test]
fn known_model_table_is_unique_valid_and_excludes_quarantine() {
assert_eq!(KNOWN_RADIOS.len(), 37);
for (index, (model, profile)) in KNOWN_RADIOS.iter().enumerate() {
assert!(
!QUARANTINED_MODELS.contains(model),
"quarantined model {model:#04x} entered the known table"
);
assert!(
profile.min_frequency_hz() < profile.max_frequency_hz(),
"model {model:#04x} has inverted frequency limits"
);
assert!(
profile.max_tx_power_dbm() > 0,
"model {model:#04x} has a non-positive maximum TX power"
);
assert!(
!KNOWN_RADIOS[..index]
.iter()
.any(|(earlier, _)| earlier == model),
"duplicate model {model:#04x}"
);
assert_eq!(
rnode_model_capabilities(*model),
RNodeRadioCapabilities::Known(*profile),
"model {model:#04x} did not round-trip through lookup"
);
}
}
}
@@ -0,0 +1,497 @@
//! Bounded, transport-independent RNode capability preflight state.
//!
//! Transport owners retain their stream, writer, clock, and cancellation
//! policy. This module owns only strict framing, bounded admission state, and
//! privacy-safe errors so serial/TCP, BLE, and USB can share one policy without
//! sharing transport lifecycle machinery.
use crate::kiss;
use crate::rnode::{CMD_ERROR, CMD_ROM_READ, RNodeCapabilityAdmissionError, RNodeRadioSettings};
use crate::rnode_capabilities::{
RNodeEepromImage, RNodeRadioAdmission, admit_rnode_radio_settings,
admit_unprovisioned_rnode_radio_settings, classify_rnode_eeprom_image,
};
use crate::rnode_protocol::{
RNodeFrameRejection, RNodeProtocolEffect, RNodeProtocolState, RNodeProtocolTarget,
};
#[cfg(all(not(test), any(feature = "serial", feature = "rnode-tcp")))]
pub(crate) const RNODE_CAPABILITY_PREFLIGHT_DEADLINE: std::time::Duration =
std::time::Duration::from_secs(5);
#[cfg(all(test, any(feature = "serial", feature = "rnode-tcp")))]
pub(crate) const RNODE_CAPABILITY_PREFLIGHT_DEADLINE: std::time::Duration =
std::time::Duration::from_secs(1);
pub(crate) const RNODE_CAPABILITY_READ_BUFFER_BYTES: usize = 1024;
const RNODE_CAPABILITY_MAX_READS: usize = 128;
const RNODE_CAPABILITY_MAX_INPUT_BYTES: usize = 4 * 1024;
const RNODE_CAPABILITY_MAX_FRAMES: usize = 128;
pub(crate) fn build_rnode_capability_request() -> Vec<u8> {
kiss::frame_with_command(CMD_ROM_READ, &[0])
}
pub(crate) struct RNodeCapabilityPreflight {
deframer: kiss::RawKissDeframer,
protocol_state: RNodeProtocolState,
settings: RNodeRadioSettings,
admission: Option<RNodeRadioAdmission>,
read_count: usize,
input_bytes: usize,
frame_count: usize,
}
impl RNodeCapabilityPreflight {
pub(crate) fn new(settings: RNodeRadioSettings) -> Self {
Self {
deframer: kiss::RawKissDeframer::new(),
protocol_state: RNodeProtocolState::new(RNodeProtocolTarget::new(
settings.frequency,
settings.bandwidth,
settings.spreading_factor,
settings.coding_rate,
settings.tx_power,
)),
settings,
admission: None,
read_count: 0,
input_bytes: 0,
frame_count: 0,
}
}
/// Consume one bounded transport read.
///
/// `CMD_DATA` and EEPROM payloads never leave this state machine. Unknown
/// non-data controls are ignored after strict deframing; supported generic
/// controls are reduced into the generation-private protocol state.
pub(crate) fn observe_read(
&mut self,
bytes: &[u8],
) -> Result<Option<RNodeRadioAdmission>, RNodeCapabilityAdmissionError> {
self.read_count = self.read_count.saturating_add(1);
if self.read_count > RNODE_CAPABILITY_MAX_READS {
return Err(RNodeCapabilityAdmissionError::ReadLimitExceeded {
limit: RNODE_CAPABILITY_MAX_READS,
});
}
if bytes.len() > RNODE_CAPABILITY_READ_BUFFER_BYTES {
return Err(RNodeCapabilityAdmissionError::InputLimitExceeded {
limit: RNODE_CAPABILITY_READ_BUFFER_BYTES,
});
}
self.input_bytes = self.input_bytes.saturating_add(bytes.len());
if self.input_bytes > RNODE_CAPABILITY_MAX_INPUT_BYTES {
return Err(RNodeCapabilityAdmissionError::InputLimitExceeded {
limit: RNODE_CAPABILITY_MAX_INPUT_BYTES,
});
}
for (command, payload) in self.deframer.feed(bytes) {
self.frame_count = self.frame_count.saturating_add(1);
if self.frame_count > RNODE_CAPABILITY_MAX_FRAMES {
return Err(RNodeCapabilityAdmissionError::FrameLimitExceeded {
limit: RNODE_CAPABILITY_MAX_FRAMES,
});
}
if command == kiss::CMD_DATA {
continue;
}
if command == CMD_ROM_READ {
if self.admission.is_some() {
return Err(RNodeCapabilityAdmissionError::DuplicateEepromResponse);
}
let admission = match classify_rnode_eeprom_image(&payload)
.map_err(RNodeCapabilityAdmissionError::CapabilityImage)?
{
RNodeEepromImage::Provisioned(capabilities) => {
admit_rnode_radio_settings(capabilities, self.settings)
.map_err(RNodeCapabilityAdmissionError::RadioSettings)?
}
RNodeEepromImage::Unprovisioned => {
admit_unprovisioned_rnode_radio_settings(self.settings)
.map_err(RNodeCapabilityAdmissionError::RadioSettings)?
}
};
self.admission = Some(admission);
continue;
}
if command == CMD_ERROR {
return Err(RNodeCapabilityAdmissionError::DeviceError);
}
match self.protocol_state.apply_frame(command, &payload) {
RNodeProtocolEffect::Rejected(RNodeFrameRejection::UnknownCommand) => {}
RNodeProtocolEffect::Rejected(rejection) => {
return Err(RNodeCapabilityAdmissionError::MalformedProtocolFrame {
rejection,
});
}
RNodeProtocolEffect::RadioInitialisationFault => {
unreachable!("CMD_ERROR is rejected before protocol reduction")
}
RNodeProtocolEffect::EvidenceChanged(_)
| RNodeProtocolEffect::FlowPermissionChanged(_)
| RNodeProtocolEffect::Reset
| RNodeProtocolEffect::NoChange => {}
}
}
let evidence = self.protocol_state.evidence();
if self.protocol_state.detection_observed() && !evidence.detected {
return Err(RNodeCapabilityAdmissionError::DetectionRejected);
}
if evidence
.firmware
.is_some_and(|firmware| !firmware.is_supported())
{
return Err(RNodeCapabilityAdmissionError::UnsupportedFirmware);
}
Ok((evidence.detected && evidence.firmware.is_some())
.then_some(self.admission)
.flatten())
}
/// Return the only preflight evidence that may seed active readiness.
///
/// Configuration, radio, and flow frames observed before the runtime sends
/// its admitted init sequence may be stale. They remain reduced privately
/// during preflight but never cross the admission boundary.
pub(crate) fn into_protocol_state(self) -> RNodeProtocolState {
let target = self.protocol_state.target();
let evidence = self.protocol_state.evidence();
let mut admitted = RNodeProtocolState::new(target);
if evidence.detected {
admitted.apply_frame(crate::rnode::CMD_DETECT, &[crate::rnode::DETECT_RESP]);
}
if let Some(firmware) = evidence.firmware {
admitted.apply_frame(
crate::rnode::CMD_FW_VERSION,
&[firmware.major, firmware.minor],
);
}
admitted
}
}
#[cfg(test)]
mod tests {
use md5::{Digest, Md5};
use super::*;
use crate::rnode::{
CMD_DETECT, CMD_FW_VERSION, DETECT_RESP, REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN,
};
fn settings(frequency: u32, tx_power: u8) -> RNodeRadioSettings {
RNodeRadioSettings::new(frequency, 125_000, 7, 5, tx_power)
}
fn eeprom(model: u8) -> Vec<u8> {
let mut bytes = vec![0xFF; 1024];
bytes[0] = 0x03;
bytes[1] = model;
bytes[2..11].copy_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8, 9]);
let checksum: [u8; 16] = Md5::digest(&bytes[..11]).into();
bytes[11..27].copy_from_slice(&checksum);
// Exercise both extended-KISS escape forms outside the validated
// identity prefix.
bytes[100] = kiss::FEND;
bytes[101] = kiss::FESC;
bytes[0x9B] = 0x73;
bytes
}
fn observe_chunked(
preflight: &mut RNodeCapabilityPreflight,
bytes: &[u8],
) -> Result<Option<RNodeRadioAdmission>, RNodeCapabilityAdmissionError> {
let mut admission = None;
for chunk in bytes.chunks(257) {
admission = preflight.observe_read(chunk)?.or(admission);
}
Ok(admission)
}
fn admitted_frames(model: u8) -> Vec<u8> {
let mut frames = Vec::new();
kiss::frame_with_command_into(CMD_DETECT, &[DETECT_RESP], &mut frames);
kiss::frame_with_command_into(
CMD_FW_VERSION,
&[REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN],
&mut frames,
);
kiss::frame_with_command_into(CMD_ROM_READ, &eeprom(model), &mut frames);
frames
}
fn unlocked_eeprom(model: u8) -> Vec<u8> {
let mut bytes = eeprom(model);
bytes[0x9B] = 0xFF;
// Corrupt the checksum region too: unlocked images must admit without
// consulting it.
for byte in &mut bytes[11..27] {
*byte = 0x5A;
}
bytes
}
fn unprovisioned_frames(model: u8) -> Vec<u8> {
let mut frames = Vec::new();
kiss::frame_with_command_into(CMD_DETECT, &[DETECT_RESP], &mut frames);
kiss::frame_with_command_into(
CMD_FW_VERSION,
&[REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN],
&mut frames,
);
kiss::frame_with_command_into(CMD_ROM_READ, &unlocked_eeprom(model), &mut frames);
frames
}
#[test]
fn unlocked_eeprom_admits_unprovisioned_and_never_consults_model_bounds() {
// Model 0xB4 at 868 MHz is a typed FrequencyOutOfRange when locked
// (see known_model_mismatch_and_bounds_are_typed); unlocked, the model
// byte is unattested and must impose nothing.
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
let result = observe_chunked(&mut preflight, &unprovisioned_frames(0xB4)).unwrap();
assert_eq!(result, Some(RNodeRadioAdmission::Unprovisioned));
let seed = preflight.into_protocol_state();
assert!(seed.evidence().detected);
assert!(seed.evidence().firmware.is_some());
}
#[test]
fn unlocked_eeprom_still_fails_generic_radio_validation() {
let mut preflight = RNodeCapabilityPreflight::new(settings(1, 14));
assert!(matches!(
observe_chunked(&mut preflight, &unprovisioned_frames(0xB8)),
Err(RNodeCapabilityAdmissionError::RadioSettings(
crate::rnode_capabilities::RNodeRadioAdmissionError::GenericValidation(_)
))
));
}
#[test]
fn unlocked_then_duplicate_rom_response_remains_fatal() {
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert_eq!(
observe_chunked(&mut preflight, &unprovisioned_frames(0xB8)).unwrap(),
Some(RNodeRadioAdmission::Unprovisioned)
);
assert_eq!(
observe_chunked(
&mut preflight,
&kiss::frame_with_command(CMD_ROM_READ, &unlocked_eeprom(0xB8)),
),
Err(RNodeCapabilityAdmissionError::DuplicateEepromResponse)
);
}
#[test]
fn capability_request_is_one_standalone_rom_read_zero_frame() {
assert_eq!(
build_rnode_capability_request(),
kiss::frame_with_command(CMD_ROM_READ, &[0])
);
}
#[test]
fn fragmented_and_escaped_eeprom_admits_verified_model() {
let bytes = admitted_frames(0xB8);
assert!(bytes.contains(&kiss::FESC));
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
let result = observe_chunked(&mut preflight, &bytes).unwrap();
assert!(matches!(result, Some(RNodeRadioAdmission::Verified { .. })));
assert!(preflight.into_protocol_state().evidence().detected);
}
#[test]
fn validated_unknown_model_is_explicitly_unverified() {
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert!(matches!(
observe_chunked(&mut preflight, &admitted_frames(0xFE)).unwrap(),
Some(RNodeRadioAdmission::Unverified {
model_code: 0xFE,
..
})
));
}
#[test]
fn data_and_wrong_commands_do_not_satisfy_or_escape_preflight() {
let mut bytes = Vec::new();
kiss::frame_with_command_into(kiss::CMD_DATA, b"private packet", &mut bytes);
kiss::frame_with_command_into(crate::rnode::CMD_PLATFORM, &[0x80], &mut bytes);
kiss::frame_with_command_into(CMD_ROM_READ.wrapping_add(1), &eeprom(0xB8), &mut bytes);
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert_eq!(observe_chunked(&mut preflight, &bytes).unwrap(), None);
}
#[test]
fn malformed_control_device_error_and_invalid_image_fail_closed() {
let mut malformed = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
let malformed_frame = kiss::frame_with_command(CMD_FW_VERSION, &[1]);
assert!(matches!(
malformed.observe_read(&malformed_frame),
Err(RNodeCapabilityAdmissionError::MalformedProtocolFrame { .. })
));
let mut device_error = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert_eq!(
device_error.observe_read(&kiss::frame_with_command(CMD_ERROR, &[0x7F])),
Err(RNodeCapabilityAdmissionError::DeviceError)
);
let mut invalid = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert!(matches!(
invalid.observe_read(&kiss::frame_with_command(CMD_ROM_READ, &[0; 8])),
Err(RNodeCapabilityAdmissionError::CapabilityImage(_))
));
}
#[test]
fn known_model_mismatch_and_bounds_are_typed() {
let mut mismatch = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
let result = observe_chunked(&mut mismatch, &admitted_frames(0xB4));
assert!(matches!(
result,
Err(RNodeCapabilityAdmissionError::RadioSettings(
crate::rnode_capabilities::RNodeRadioAdmissionError::FrequencyOutOfRange { .. }
))
));
let mut bounded = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
for _ in 0..RNODE_CAPABILITY_MAX_READS {
assert_eq!(bounded.observe_read(&[]).unwrap(), None);
}
assert_eq!(
bounded.observe_read(&[]),
Err(RNodeCapabilityAdmissionError::ReadLimitExceeded {
limit: RNODE_CAPABILITY_MAX_READS
})
);
}
#[test]
fn negative_detection_unsupported_firmware_and_duplicate_rom_are_typed() {
let mut detection = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert_eq!(
detection.observe_read(&kiss::frame_with_command(CMD_DETECT, &[0])),
Err(RNodeCapabilityAdmissionError::DetectionRejected)
);
let mut firmware = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert_eq!(
firmware.observe_read(&kiss::frame_with_command(
CMD_FW_VERSION,
&[REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN - 1],
)),
Err(RNodeCapabilityAdmissionError::UnsupportedFirmware)
);
let mut duplicate = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert_eq!(
observe_chunked(
&mut duplicate,
&kiss::frame_with_command(CMD_ROM_READ, &eeprom(0xB8)),
)
.unwrap(),
None
);
assert_eq!(
observe_chunked(
&mut duplicate,
&kiss::frame_with_command(CMD_ROM_READ, &eeprom(0xB8)),
),
Err(RNodeCapabilityAdmissionError::DuplicateEepromResponse)
);
}
#[test]
fn cumulative_input_and_frame_limits_fail_closed() {
let mut input = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
let chunk = vec![0; RNODE_CAPABILITY_READ_BUFFER_BYTES];
for _ in 0..(RNODE_CAPABILITY_MAX_INPUT_BYTES / chunk.len()) {
assert_eq!(input.observe_read(&chunk).unwrap(), None);
}
assert_eq!(
input.observe_read(&[0]),
Err(RNodeCapabilityAdmissionError::InputLimitExceeded {
limit: RNODE_CAPABILITY_MAX_INPUT_BYTES
})
);
let mut frame_bytes = Vec::new();
for _ in 0..=RNODE_CAPABILITY_MAX_FRAMES {
kiss::frame_with_command_into(crate::rnode::CMD_PLATFORM, &[0], &mut frame_bytes);
}
let mut frames = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert_eq!(
frames.observe_read(&frame_bytes),
Err(RNodeCapabilityAdmissionError::FrameLimitExceeded {
limit: RNODE_CAPABILITY_MAX_FRAMES
})
);
}
#[test]
fn partial_frame_never_admits_and_is_not_replayed() {
let bytes = admitted_frames(0xB8);
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
assert_eq!(
observe_chunked(&mut preflight, &bytes[..bytes.len() - 1]).unwrap(),
None
);
drop(preflight);
let mut fresh = kiss::RawKissDeframer::new();
assert!(fresh.feed(&bytes[bytes.len() - 1..]).is_empty());
}
#[test]
fn stale_pre_init_radio_evidence_cannot_make_admitted_seed_ready() {
let settings = settings(868_000_000, 14);
let mut bytes = Vec::new();
kiss::frame_with_command_into(
crate::rnode::CMD_FREQUENCY,
&settings.frequency.to_be_bytes(),
&mut bytes,
);
kiss::frame_with_command_into(
crate::rnode::CMD_BANDWIDTH,
&settings.bandwidth.to_be_bytes(),
&mut bytes,
);
kiss::frame_with_command_into(
crate::rnode::CMD_SF,
&[settings.spreading_factor],
&mut bytes,
);
kiss::frame_with_command_into(crate::rnode::CMD_CR, &[settings.coding_rate], &mut bytes);
kiss::frame_with_command_into(crate::rnode::CMD_TXPOWER, &[settings.tx_power], &mut bytes);
kiss::frame_with_command_into(
crate::rnode::CMD_RADIO_STATE,
&[crate::rnode::RADIO_STATE_ON],
&mut bytes,
);
bytes.extend_from_slice(&admitted_frames(0xB8));
let mut preflight = RNodeCapabilityPreflight::new(settings);
assert!(observe_chunked(&mut preflight, &bytes).unwrap().is_some());
let seed = preflight.into_protocol_state();
assert!(seed.evidence().detected);
assert!(seed.evidence().firmware.is_some());
assert_eq!(seed.evidence().frequency, None);
assert_eq!(seed.evidence().radio_state, None);
assert!(matches!(
seed.readiness(),
crate::rnode_protocol::RNodeReadiness::Blocked(
crate::rnode_protocol::RNodeReadinessBlocker::Missing(
crate::rnode_protocol::RNodeReadinessEvidence::Frequency
)
)
));
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+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;
}
@@ -185,6 +188,7 @@ pub async fn spawn_serial_interface(
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: None,
tx,
read_task,
})
+43
View File
@@ -0,0 +1,43 @@
//! Blocking-I/O shuttles shared by the serial-family interfaces (Serial,
//! KISS, AX.25 KISS, RNodeMulti). No mature async serial driver exists, so
//! each read/write moves the port through `spawn_blocking` and back.
/// One bounded blocking read. Serial idle timeouts surface as `n == 0` so
/// the caller's loop can re-check its exit flag. A panicked blocking task
/// folds into an `io::Error`.
#[cfg(feature = "serial")]
pub(crate) async fn poll_read<P>(
mut port: P,
mut buf: [u8; 1024],
) -> Result<(P, [u8; 1024], usize), std::io::Error>
where
P: std::io::Read + Send + 'static,
{
let result = tokio::task::spawn_blocking(move || match port.read(&mut buf) {
Ok(n) => Ok((port, buf, n)),
Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok((port, buf, 0)),
Err(e) => Err(e),
})
.await;
match result {
Ok(read_result) => read_result,
Err(join_err) => Err(std::io::Error::other(join_err)),
}
}
/// One blocking `write_all` + `flush`, returning the port for the next call.
pub(crate) async fn blocking_write_all<P>(mut port: P, data: Vec<u8>) -> Result<P, std::io::Error>
where
P: std::io::Write + Send + 'static,
{
let result = tokio::task::spawn_blocking(move || {
port.write_all(&data)?;
port.flush()?;
Ok::<_, std::io::Error>(port)
})
.await;
match result {
Ok(write_result) => write_result,
Err(join_err) => Err(std::io::Error::other(join_err)),
}
}
+73 -122
View File
@@ -1,109 +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)
}
/// Enable portable `SO_KEEPALIVE` on a blocking std TCP stream.
/// Platform bound for streams the tuning helpers accept: anything exposing
/// the raw socket handle (tokio `TcpStream`, std `TcpStream`, …).
#[cfg(unix)]
pub fn set_keepalive_std(stream: &std::net::TcpStream) -> std::io::Result<()> {
use std::os::fd::{AsRawFd, FromRawFd};
let raw_fd = stream.as_raw_fd();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
sock.set_keepalive(true)?;
Ok(())
}
pub trait RawStream: std::os::fd::AsRawFd {}
#[cfg(unix)]
impl<T: std::os::fd::AsRawFd> RawStream for T {}
#[cfg(windows)]
pub fn set_keepalive_std(stream: &std::net::TcpStream) -> std::io::Result<()> {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
sock.set_keepalive(true)?;
Ok(())
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);
}
/// Tuned keepalive for blocking std TCP streams. Best-effort.
#[cfg(unix)]
pub fn set_keepalive_tuned_std(
stream: &std::net::TcpStream,
idle: Duration,
intvl: Duration,
retries: u32,
user_timeout: Duration,
) {
use std::os::fd::{AsRawFd, FromRawFd};
let raw_fd = stream.as_raw_fd();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
}
#[cfg(windows)]
pub fn set_keepalive_tuned_std(
stream: &std::net::TcpStream,
idle: Duration,
intvl: Duration,
retries: u32,
user_timeout: Duration,
) {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
/// 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(
@@ -136,42 +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);
}
/// Raise TCP send/recv buffers on a blocking std TCP stream; best-effort.
#[cfg(unix)]
pub fn set_socket_buffers_std(stream: &std::net::TcpStream, size: usize) {
use std::os::fd::{AsRawFd, FromRawFd};
let raw_fd = stream.as_raw_fd();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
let _ = sock.set_recv_buffer_size(size);
let _ = sock.set_send_buffer_size(size);
}
#[cfg(windows)]
pub fn set_socket_buffers_std(stream: &std::net::TcpStream, size: usize) {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
let _ = sock.set_recv_buffer_size(size);
let _ = sock.set_send_buffer_size(size);
/// Resolve interface name to 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
@@ -210,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() {
@@ -244,6 +194,7 @@ mod tests {
set_socket_buffers(&client, 131_072);
}
/// The same generic helpers must accept blocking std streams.
#[test]
fn std_keepalive_and_buffers_apply_without_panic() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
@@ -252,17 +203,17 @@ mod tests {
let client = std::net::TcpStream::connect(addr).unwrap();
let server = accept.join().unwrap();
set_keepalive_std(&server).expect("server set_keepalive_std");
set_keepalive_std(&client).expect("client set_keepalive_std");
set_keepalive(&server).expect("server set_keepalive");
set_keepalive(&client).expect("client set_keepalive");
set_keepalive_tuned_std(
set_keepalive_tuned(
&server,
Duration::from_secs(5),
Duration::from_secs(2),
12,
Duration::from_secs(24),
);
set_keepalive_tuned_std(
set_keepalive_tuned(
&client,
Duration::from_secs(5),
Duration::from_secs(2),
@@ -270,8 +221,8 @@ mod tests {
Duration::from_secs(24),
);
set_socket_buffers_std(&server, 131_072);
set_socket_buffers_std(&client, 131_072);
set_socket_buffers(&server, 131_072);
set_socket_buffers(&client, 131_072);
}
#[test]
+176 -36
View File
@@ -8,22 +8,36 @@ use tokio::sync::mpsc;
use crate::hdlc;
use crate::kiss;
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
use crate::traits::{
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
};
use rns_transport::messages::{InboundPacket, TransportMessage};
pub const 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 +47,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 +61,7 @@ impl TcpClientConfig {
connect_timeout_secs: DEFAULT_CONNECT_TIMEOUT,
max_reconnect_tries: None,
mode: InterfaceMode::Full,
fixed_mtu: None,
}
}
}
@@ -57,6 +74,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 +88,32 @@ 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 {
if 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 +128,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 +179,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 +289,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 +302,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 +332,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 +350,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 +362,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);
@@ -401,10 +436,12 @@ pub async fn spawn_tcp_client(
repeat: false,
},
bitrate,
mtu: crate::traits::optimise_mtu(bitrate).unwrap_or(TCP_HW_MTU),
mtu: fixed_mtu
.unwrap_or_else(|| crate::traits::optimise_mtu(bitrate).unwrap_or(TCP_HW_MTU)),
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: None,
tx,
read_task,
})
@@ -435,9 +472,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);
@@ -475,6 +510,7 @@ async fn spawn_tcp_accepted(
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: None,
tx,
read_task,
}
@@ -489,7 +525,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");
@@ -520,7 +566,10 @@ pub async fn spawn_tcp_server(
mode,
)
.await;
if handle_tx.send(handle).await.is_err() {
if handoff_accepted_interface(&handle_tx, handle)
.await
.is_err()
{
tracing::warn!("handle registry channel closed, stopping accept loop");
break;
}
@@ -551,6 +600,7 @@ pub async fn spawn_tcp_server(
online,
rxb: Some(Arc::new(AtomicU64::new(0))),
txb: Some(Arc::new(AtomicU64::new(0))),
inspection: None,
tx,
read_task,
})
@@ -575,6 +625,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";
@@ -634,8 +773,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();
@@ -718,11 +858,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 =
@@ -761,8 +900,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();
+131 -48
View File
@@ -20,14 +20,34 @@ pub struct InterfaceHandle {
pub online: Arc<AtomicBool>,
pub rxb: Option<Arc<AtomicU64>>,
pub txb: Option<Arc<AtomicU64>>,
/// Optional live aggregate inspection source carried into the transport
/// actor. This field intentionally makes pre-freeze struct literals update
/// explicitly so new interface drivers choose whether they expose stats.
pub inspection: Option<rns_transport::messages::InterfaceInspectionSource>,
pub tx: mpsc::Sender<Bytes>,
pub read_task: tokio::task::JoinHandle<()>,
}
/// Optional per-interface IFAC (Interface Authentication Code) configuration.
pub struct IfacConfig {
pub ifac_key: [u8; 64],
pub ifac_size: usize,
/// Deliver a dynamically accepted interface to its owner.
///
/// A failed handoff returns the handle to this producer. The producer must
/// finish disposing of the exact child it created rather than detaching its
/// read task when the receiving runtime has gone away.
pub(crate) async fn handoff_accepted_interface(
handle_tx: &mpsc::Sender<InterfaceHandle>,
handle: InterfaceHandle,
) -> Result<(), ()> {
match handle_tx.send(handle).await {
Ok(()) => Ok(()),
Err(mpsc::error::SendError(handle)) => {
handle
.online
.store(false, std::sync::atomic::Ordering::SeqCst);
handle.read_task.abort();
let _ = handle.read_task.await;
Err(())
}
}
}
/// Interface operating mode. Byte values are on-wire constants.
@@ -42,6 +62,8 @@ pub enum InterfaceMode {
Roaming = 0x04,
Boundary = 0x05,
Gateway = 0x06,
/// Python 1.3.8 `MODE_INTERNAL` (Interface.py:51) — local/shared-instance interfaces.
Internal = 0x07,
}
pub const MODE_FULL: InterfaceMode = InterfaceMode::Full;
@@ -57,6 +79,7 @@ pub const DISCOVER_PATHS_FOR: &[InterfaceMode] = &[
InterfaceMode::AccessPoint,
InterfaceMode::Gateway,
InterfaceMode::Roaming,
InterfaceMode::Internal,
];
impl InterfaceMode {
@@ -68,6 +91,7 @@ impl InterfaceMode {
0x04 => Some(Self::Roaming),
0x05 => Some(Self::Boundary),
0x06 => Some(Self::Gateway),
0x07 => Some(Self::Internal),
_ => None,
}
}
@@ -82,50 +106,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 {
@@ -206,6 +186,19 @@ pub enum InterfaceError {
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::Ordering;
struct TaskExitGuard {
exited: Option<tokio::sync::oneshot::Sender<()>>,
}
impl Drop for TaskExitGuard {
fn drop(&mut self) {
if let Some(exited) = self.exited.take() {
let _ = exited.send(());
}
}
}
#[test]
fn test_optimise_mtu() {
@@ -224,6 +217,7 @@ mod tests {
assert_eq!(InterfaceMode::Roaming as u8, 0x04);
assert_eq!(InterfaceMode::Boundary as u8, 0x05);
assert_eq!(InterfaceMode::Gateway as u8, 0x06);
assert_eq!(InterfaceMode::Internal as u8, 0x07);
}
#[test]
@@ -234,7 +228,9 @@ mod tests {
Some(InterfaceMode::PointToPoint)
);
assert_eq!(InterfaceMode::from_u8(0x06), Some(InterfaceMode::Gateway));
assert_eq!(InterfaceMode::from_u8(0x07), Some(InterfaceMode::Internal));
assert_eq!(InterfaceMode::from_u8(0x00), None);
assert_eq!(InterfaceMode::from_u8(0x08), None);
assert_eq!(InterfaceMode::from_u8(0xFF), None);
}
@@ -249,6 +245,7 @@ mod tests {
assert!(DISCOVER_PATHS_FOR.contains(&InterfaceMode::AccessPoint));
assert!(DISCOVER_PATHS_FOR.contains(&InterfaceMode::Gateway));
assert!(DISCOVER_PATHS_FOR.contains(&InterfaceMode::Roaming));
assert!(DISCOVER_PATHS_FOR.contains(&InterfaceMode::Internal));
assert!(!DISCOVER_PATHS_FOR.contains(&InterfaceMode::Full));
}
@@ -281,4 +278,90 @@ mod tests {
assert_eq!(EC_PR_FREQ, 5.0);
const { assert!(!EGRESS_CONTROL) };
}
#[tokio::test]
async fn rejected_accepted_interface_is_stopped_and_disposed() {
let (handle_tx, handle_rx) = mpsc::channel(1);
drop(handle_rx);
let online = Arc::new(AtomicBool::new(true));
let (interface_tx, mut interface_rx) = mpsc::channel(1);
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
let (exited_tx, exited_rx) = tokio::sync::oneshot::channel();
let read_task = tokio::spawn(async move {
let _exit_guard = TaskExitGuard {
exited: Some(exited_tx),
};
let _ = started_tx.send(());
std::future::pending::<()>().await;
});
started_rx.await.expect("read task should start");
let handle = InterfaceHandle {
id: 1,
parent_id: Some(0),
name: "rejected-child".to_string(),
mode: InterfaceMode::Full,
direction: InterfaceDirection::default(),
bitrate: 1,
mtu: 1,
online: Arc::clone(&online),
rxb: None,
txb: None,
inspection: None,
tx: interface_tx,
read_task,
};
assert_eq!(
handoff_accepted_interface(&handle_tx, handle).await,
Err(())
);
assert!(!online.load(Ordering::SeqCst));
exited_rx
.await
.expect("helper should await exact read-task termination");
assert_eq!(
interface_rx.recv().await,
None,
"rejected handle resources should be dropped"
);
}
#[tokio::test]
async fn accepted_interface_handoff_preserves_live_handle() {
let (handle_tx, mut handle_rx) = mpsc::channel(1);
let online = Arc::new(AtomicBool::new(true));
let (interface_tx, _interface_rx) = mpsc::channel(1);
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
let read_task = tokio::spawn(async move {
let _ = started_tx.send(());
std::future::pending::<()>().await;
});
started_rx.await.expect("read task should start");
let handle = InterfaceHandle {
id: 2,
parent_id: Some(0),
name: "accepted-child".to_string(),
mode: InterfaceMode::Full,
direction: InterfaceDirection::default(),
bitrate: 1,
mtu: 1,
online: Arc::clone(&online),
rxb: None,
txb: None,
inspection: None,
tx: interface_tx,
read_task,
};
assert_eq!(handoff_accepted_interface(&handle_tx, handle).await, Ok(()));
let delivered = handle_rx.recv().await.expect("handle should be delivered");
assert!(online.load(Ordering::SeqCst));
assert!(!delivered.read_task.is_finished());
delivered.read_task.abort();
let _ = delivered.read_task.await;
}
}
+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() {
@@ -159,6 +180,7 @@ pub async fn spawn_udp_interface(
online,
rxb: Some(shared_rxb),
txb: Some(shared_txb),
inspection: None,
tx,
read_task,
})
@@ -185,6 +207,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 -1
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;
@@ -333,7 +336,6 @@ mod tests {
#[test]
fn test_weave_constants() {
assert_eq!(HW_MTU, 1024);
const { assert!(FIXED_MTU) };
assert_eq!(PEERING_TIMEOUT, 20.0);
assert_eq!(BITRATE_GUESS, 250_000);
assert_eq!(DEFAULT_IFAC_SIZE, 16);
@@ -442,6 +444,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());
+1
View File
@@ -3,6 +3,7 @@ name = "rns-link"
description = "Link layer and encrypted channel for Reticulum"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[features]
+95 -11
View File
@@ -89,6 +89,10 @@ impl KeepaliveState {
/// Whether the initiator should emit a keepalive now (jitter applied).
pub fn should_send_keepalive(&self) -> bool {
self.should_send_keepalive_at(Instant::now())
}
pub(crate) fn should_send_keepalive_at(&self, now: Instant) -> bool {
let jittered = if self.jitter_negative {
self.keepalive_interval
.saturating_sub(self.jitter_offset)
@@ -97,37 +101,53 @@ impl KeepaliveState {
self.keepalive_interval + self.jitter_offset
};
let inbound_elapsed = self.last_inbound.elapsed();
let inbound_elapsed = now.saturating_duration_since(self.last_inbound);
let outbound_elapsed = self
.last_outbound
.or(self.activated_at)
.map(|baseline| now.saturating_duration_since(baseline))
.unwrap_or(inbound_elapsed);
let keepalive_elapsed = self
.last_keepalive_sent
.map(|t| t.elapsed())
.map(|last_keepalive| now.saturating_duration_since(last_keepalive))
.unwrap_or(Duration::MAX);
self.is_initiator && inbound_elapsed >= jittered && keepalive_elapsed >= jittered
self.is_initiator
&& (inbound_elapsed >= jittered || outbound_elapsed >= jittered)
&& keepalive_elapsed >= jittered
}
pub(crate) fn should_respond_to_keepalive_at(&self, now: Instant) -> bool {
!self.is_initiator
&& self
.last_outbound
.map(|last_outbound| {
now.saturating_duration_since(last_outbound) >= self.keepalive_interval
})
.unwrap_or(true)
}
/// Whether the link should transition to STALE.
///
/// Uses the most recent of inbound, proof, or activation as the baseline so a
/// link that just came up isn't immediately flagged stale on a quiet channel.
/// Uses only peer evidence — inbound traffic, proof, or activation — as the
/// baseline. Local outbound traffic cannot prove that the peer remains alive.
pub fn is_stale(&self) -> bool {
self.is_stale_at(Instant::now())
}
pub(crate) fn is_stale_at(&self, now: Instant) -> bool {
let mut latest = self.last_inbound;
if let Some(proof) = self.last_proof {
if proof > latest {
latest = proof;
}
}
if let Some(outbound) = self.last_outbound {
if outbound > latest {
latest = outbound;
}
}
if let Some(activated) = self.activated_at {
if activated > latest {
latest = activated;
}
}
latest.elapsed() >= self.stale_time
now.saturating_duration_since(latest) >= self.stale_time
}
/// How long to wait in STALE before tearing the link down.
@@ -139,6 +159,16 @@ impl KeepaliveState {
self.last_keepalive_sent = Some(Instant::now());
}
pub(crate) fn mark_keepalive_sent_at(&mut self, now: Instant) {
self.last_keepalive_sent = Some(now);
}
pub(crate) fn record_keepalive_outbound(&mut self) {
let now = Instant::now();
self.last_outbound = Some(now);
self.last_keepalive_sent = Some(now);
}
pub fn since_inbound(&self) -> Duration {
self.last_inbound.elapsed()
}
@@ -220,6 +250,60 @@ mod tests {
assert!(!ks2.should_send_keepalive());
}
#[test]
fn continuous_inbound_still_schedules_keepalive_when_outbound_is_quiet() {
let now = Instant::now();
let mut state = KeepaliveState::new(true);
state.keepalive_interval = Duration::from_secs(5);
state.jitter_offset = Duration::ZERO;
state.jitter_negative = false;
state.last_inbound = now;
state.last_outbound = None;
state.activated_at = Some(now - Duration::from_secs(6));
state.last_keepalive_sent = Some(now - Duration::from_secs(6));
assert!(state.should_send_keepalive_at(now));
}
#[test]
fn recent_keepalive_suppresses_duplicate_at_exact_tick_time() {
let now = Instant::now();
let mut state = KeepaliveState::new(true);
state.keepalive_interval = Duration::from_secs(5);
state.jitter_offset = Duration::ZERO;
state.jitter_negative = false;
state.last_inbound = now - Duration::from_secs(6);
state.last_outbound = Some(now - Duration::from_secs(6));
state.last_keepalive_sent = Some(now - Duration::from_secs(4));
assert!(!state.should_send_keepalive_at(now));
assert!(state.should_send_keepalive_at(now + Duration::from_secs(1)));
}
#[test]
fn local_outbound_traffic_does_not_mask_a_stale_peer() {
let now = Instant::now();
let mut state = KeepaliveState::new(true);
state.stale_time = Duration::from_secs(5);
state.last_inbound = now - Duration::from_secs(6);
state.last_outbound = Some(now);
state.last_proof = None;
state.activated_at = None;
assert!(state.is_stale_at(now));
}
#[test]
fn responder_suppresses_keepalive_reply_after_recent_outbound() {
let now = Instant::now();
let mut state = KeepaliveState::new(false);
state.keepalive_interval = Duration::from_secs(5);
state.last_outbound = Some(now);
assert!(!state.should_respond_to_keepalive_at(now));
assert!(state.should_respond_to_keepalive_at(now + Duration::from_secs(5)));
}
#[test]
fn test_stale_detection() {
let mut ks = KeepaliveState::new(true);
File diff suppressed because it is too large. Load diff
+103 -10
View File
@@ -4,6 +4,11 @@ use std::time::{Duration, Instant};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RequestState {
Sent,
/// The request body itself is still being delivered as a Resource.
///
/// Resource transfer watchdogs own the send timeout in this state. The
/// response timeout starts only after the Resource proof arrives.
SendingResource,
/// Response is arriving as a resource transfer rather than a single packet.
Receiving,
Delivered,
@@ -59,7 +64,10 @@ impl RequestReceipt {
/// Record a response payload, transition to `Delivered`, and fire the response callback.
pub fn deliver(&mut self, response: Vec<u8>) {
if self.state == RequestState::Sent || self.state == RequestState::Receiving {
if matches!(
self.state,
RequestState::Sent | RequestState::SendingResource | RequestState::Receiving
) {
self.rtt = Some(self.sent_at.elapsed());
self.response = Some(response);
self.state = RequestState::Delivered;
@@ -72,7 +80,10 @@ impl RequestReceipt {
/// Transition to `Failed` and fire the failure callback.
pub fn fail(&mut self) {
if self.state == RequestState::Sent || self.state == RequestState::Receiving {
if matches!(
self.state,
RequestState::Sent | RequestState::SendingResource | RequestState::Receiving
) {
self.state = RequestState::Failed;
if let Some(cb) = self.callbacks.failed.take() {
cb(self);
@@ -81,11 +92,15 @@ impl RequestReceipt {
}
pub fn is_timed_out(&self) -> bool {
self.state == RequestState::Sent && self.sent_at.elapsed() > self.timeout
matches!(self.state, RequestState::Sent | RequestState::Receiving)
&& self.sent_at.elapsed() >= self.timeout
}
pub fn is_pending(&self) -> bool {
self.state == RequestState::Sent
matches!(
self.state,
RequestState::Sent | RequestState::SendingResource | RequestState::Receiving
)
}
/// Store the response payload and advance to `ResponseReceived`.
@@ -93,10 +108,20 @@ impl RequestReceipt {
/// Distinct from `deliver()`: `receive_response` can fire after `mark_delivered()`
/// for protocols that ack then stream the payload.
pub fn receive_response(&mut self, data: Vec<u8>) {
if self.state == RequestState::Sent || self.state == RequestState::Delivered {
if matches!(
self.state,
RequestState::Sent
| RequestState::SendingResource
| RequestState::Receiving
| RequestState::Delivered
) {
self.rtt = Some(self.sent_at.elapsed());
self.response = Some(data);
self.state = RequestState::ResponseReceived;
self.progress = 1.0;
if let Some(cb) = self.callbacks.response.take() {
cb(self);
}
}
}
@@ -109,11 +134,30 @@ impl RequestReceipt {
/// Transition to `Failed` without firing the failure callback.
pub fn mark_failed(&mut self) {
if self.state == RequestState::Sent {
if matches!(
self.state,
RequestState::Sent | RequestState::SendingResource | RequestState::Receiving
) {
self.state = RequestState::Failed;
}
}
/// Suspend the response deadline while the request body is sent as a
/// Resource. The Resource transfer has its own watchdog.
pub fn mark_resource_sending(&mut self) {
if self.state == RequestState::Sent {
self.state = RequestState::SendingResource;
}
}
/// Start the response deadline after a request Resource is proved.
pub fn mark_resource_sent(&mut self) {
if self.state == RequestState::SendingResource {
self.state = RequestState::Sent;
self.sent_at = Instant::now();
}
}
/// True once the request has reached a terminal state (delivered, failed, or response received).
pub fn concluded(&self) -> bool {
matches!(
@@ -152,10 +196,7 @@ impl RequestReceipt {
/// Expire the request if past its deadline, firing the failure callback. Returns `true` if expired.
pub fn check_timeout(&mut self) -> bool {
if self.is_timed_out() {
self.state = RequestState::Failed;
if let Some(cb) = self.callbacks.failed.take() {
cb(self);
}
self.fail();
true
} else {
false
@@ -236,6 +277,19 @@ mod tests {
assert!(!receipt.is_pending());
}
#[test]
fn resource_send_suspends_and_restarts_response_timeout() {
let mut receipt = RequestReceipt::new([0x12; 32], [0x34; 16], Duration::ZERO);
receipt.mark_resource_sending();
assert_eq!(receipt.state, RequestState::SendingResource);
assert!(!receipt.is_timed_out());
receipt.mark_resource_sent();
assert_eq!(receipt.state, RequestState::Sent);
assert!(receipt.is_timed_out());
}
#[test]
fn test_cannot_receive_response_after_fail() {
let mut receipt = RequestReceipt::new([0x33; 32], [0x44; 16], Duration::from_secs(10));
@@ -245,4 +299,43 @@ mod tests {
assert_eq!(receipt.state, RequestState::Failed);
assert!(receipt.response.is_none());
}
#[test]
fn test_receive_response_fires_callback_from_receiving_state() {
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
let fired = Arc::new(AtomicBool::new(false));
let callback_fired = fired.clone();
let mut receipt = RequestReceipt::new([0x55; 32], [0x66; 16], Duration::from_secs(10));
receipt.state = RequestState::Receiving;
receipt.set_response_callback(move |receipt| {
assert_eq!(receipt.state, RequestState::ResponseReceived);
callback_fired.store(true, Ordering::SeqCst);
});
receipt.receive_response(b"resource response".to_vec());
assert!(fired.load(Ordering::SeqCst));
assert_eq!(receipt.get_progress(), 1.0);
}
#[test]
fn test_receiving_request_times_out_and_fires_failure_callback() {
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
let fired = Arc::new(AtomicBool::new(false));
let callback_fired = fired.clone();
let mut receipt = RequestReceipt::new([0x77; 32], [0x88; 16], Duration::ZERO);
receipt.state = RequestState::Receiving;
receipt.set_failed_callback(move |receipt| {
assert_eq!(receipt.state, RequestState::Failed);
callback_fired.store(true, Ordering::SeqCst);
});
assert!(receipt.check_timeout());
assert!(fired.load(Ordering::SeqCst));
assert!(!receipt.is_pending());
}
}
+1
View File
@@ -3,6 +3,7 @@ name = "rns-protocol"
description = "Resource, Channel, and Buffer protocols for Reticulum"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[dependencies]
+260 -21
View File
@@ -208,6 +208,10 @@ impl ChannelWindow {
/// (subsequent handlers are skipped) or `false` to fall through.
pub type MessageCallback = Box<dyn Fn(u16, &[u8]) -> bool + Send>;
/// Opaque token for removing one registered message handler.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct HandlerId(u64);
/// Sequenced, reliable message pipe over a Reticulum link.
///
/// The channel is passive: the owning runtime calls `send`/`receive`/
@@ -221,12 +225,13 @@ pub struct Channel {
rx_ring: VecDeque<Envelope>,
pub window: ChannelWindow,
pub active: bool,
initial_rtt: f64,
current_rtt: f64,
/// When non-empty, only these types are accepted on `receive`.
registered_types: Vec<u16>,
/// Called in registration order on each delivered message; the first
/// handler that returns `true` stops the chain.
message_handlers: Vec<MessageCallback>,
message_handlers: Vec<(HandlerId, MessageCallback)>,
next_handler_id: u64,
}
impl Channel {
@@ -238,9 +243,10 @@ impl Channel {
rx_ring: VecDeque::new(),
window: ChannelWindow::new(rtt),
active: true,
initial_rtt: rtt,
current_rtt: rtt,
registered_types: Vec::new(),
message_handlers: Vec::new(),
next_handler_id: 0,
}
}
@@ -265,9 +271,26 @@ impl Channel {
}
}
/// Append `handler` to the end of the callback chain.
pub fn add_message_handler(&mut self, handler: MessageCallback) {
self.message_handlers.push(handler);
/// Append `handler` to the end of the callback chain and return its token.
pub fn add_message_handler(&mut self, handler: MessageCallback) -> HandlerId {
let id = HandlerId(self.next_handler_id);
self.next_handler_id = self.next_handler_id.wrapping_add(1);
self.message_handlers.push((id, handler));
id
}
/// Remove exactly one previously registered handler.
pub fn remove_message_handler(&mut self, id: HandlerId) -> bool {
let Some(index) = self
.message_handlers
.iter()
.position(|(candidate, _)| *candidate == id)
else {
return false;
};
let (_id, handler) = self.message_handlers.remove(index);
drop(handler);
true
}
pub fn clear_message_handlers(&mut self) {
@@ -275,19 +298,24 @@ impl Channel {
}
fn run_callbacks(&self, msg_type: u16, payload: &[u8]) -> bool {
for handler in &self.message_handlers {
if handler(msg_type, payload) {
for (_, handler) in &self.message_handlers {
// Application callbacks must not prevent the channel from
// advancing its receive sequence or starve handlers registered
// after them. The process panic hook still reports the failure;
// this boundary only isolates unwinding builds.
let consumed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
handler(msg_type, payload)
}))
.unwrap_or(false);
if consumed {
return true;
}
}
false
}
/// Empty registration list means "accept anything", matching the
/// permissive behaviour of the Python reference before type filters were
/// added.
fn is_type_registered(&self, msg_type: u16) -> bool {
self.registered_types.is_empty() || self.registered_types.contains(&msg_type)
self.registered_types.contains(&msg_type)
}
/// True when the channel has window headroom to accept a new outbound message.
@@ -303,6 +331,11 @@ impl Channel {
outstanding < self.window.window
}
/// True when every outbound envelope has been acknowledged and removed.
pub fn is_drained(&self) -> bool {
self.tx_ring.is_empty()
}
/// Pack `msg`, push it onto the TX ring, and return the raw envelope for
/// the transport to send. Fails when the channel is closed or its window
/// is already saturated.
@@ -312,6 +345,14 @@ impl Channel {
/// As [`Self::send`], but also returns the assigned sequence number.
pub fn send_tracked(&mut self, msg: &dyn MessageBase) -> Result<(u16, Vec<u8>), ChannelError> {
self.send_tracked_with_max_envelope(msg, None)
}
fn send_tracked_with_max_envelope(
&mut self,
msg: &dyn MessageBase,
max_envelope_size: Option<usize>,
) -> Result<(u16, Vec<u8>), ChannelError> {
if !self.active {
return Err(ChannelError::ChannelClosed);
}
@@ -320,9 +361,16 @@ impl Channel {
}
let seq = self.next_tx_sequence;
self.next_tx_sequence = ((self.next_tx_sequence as u32 + 1) % SEQ_MODULUS) as u16;
let mut envelope = Envelope::pack(msg, seq);
if let Some(max) = max_envelope_size {
if envelope.raw.len() > max {
return Err(ChannelError::MessageTooLarge {
actual: envelope.raw.len(),
max,
});
}
}
self.next_tx_sequence = ((self.next_tx_sequence as u32 + 1) % SEQ_MODULUS) as u16;
envelope.state = MessageState::Sent;
envelope.tries = 1;
envelope.last_sent = Some(Instant::now());
@@ -397,6 +445,9 @@ impl Channel {
/// legitimate. Out-of-range or duplicate sequence numbers are silently
/// dropped; registered callbacks fire in order on each delivered message.
pub fn receive(&mut self, raw: &[u8]) -> Result<Vec<(u16, Vec<u8>)>, ChannelError> {
if !self.active {
return Err(ChannelError::ChannelClosed);
}
let envelope = Envelope::unpack(raw).map_err(|_| ChannelError::InvalidEnvelope)?;
if !self.is_type_registered(envelope.msg_type) {
@@ -477,10 +528,10 @@ impl Channel {
.count()
}
/// Retransmit timeout: `1.5^(tries - 1) * max(rtt * 2.5, MIN_TIMEOUT_BASE)
/// * (outstanding + 1.5)` seconds, using the RTT captured at construction.
/// Retransmit timeout uses the Python-compatible exponential backoff,
/// based on the latest Link RTT supplied by the owning runtime.
pub fn compute_timeout(&self, tries: usize) -> f64 {
let rtt = self.initial_rtt;
let rtt = self.current_rtt;
let backoff = 1.5_f64.powi(tries.saturating_sub(1) as i32);
let base = (rtt * 2.5).max(MIN_TIMEOUT_BASE);
let outstanding = self.outstanding_count() as f64 + 1.5;
@@ -491,6 +542,13 @@ impl Channel {
Duration::from_secs_f64(self.compute_timeout(tries).max(MIN_TIMEOUT_BASE))
}
/// Update the live Link RTT used by subsequent retransmit deadlines.
pub fn update_rtt(&mut self, rtt: f64) {
if rtt.is_finite() && rtt >= 0.0 {
self.current_rtt = rtt;
}
}
/// Mark the channel inactive and drop every buffered envelope and
/// handler. Idempotent.
pub fn shutdown(&mut self) {
@@ -522,6 +580,8 @@ pub enum ChannelError {
UnknownMessageType(u16),
#[error("invalid message type: 0x{0:04X} (reserved for system use)")]
InvalidMessageType(u16),
#[error("packed channel message is {actual} bytes; Link MDU is {max}")]
MessageTooLarge { actual: usize, max: usize },
}
/// A [`Channel`] paired with its link ID and (optionally) link session keys,
@@ -530,6 +590,7 @@ pub enum ChannelError {
pub struct LinkChannel {
channel: Channel,
link_id: [u8; 16],
link_mdu: usize,
session_keys: Option<rns_link::key_derivation::LinkKeys>,
outbound_packet_hashes: HashMap<[u8; 32], u16>,
}
@@ -543,9 +604,15 @@ pub struct PreparedChannelData {
impl LinkChannel {
/// Plain-text channel (no transport-side encryption).
pub fn new(link_id: [u8; 16], rtt: f64) -> Self {
Self::new_with_mdu(link_id, rtt, rns_wire::constants::LINK_MDU)
}
/// Plain-text channel with an explicit Link MDU.
pub fn new_with_mdu(link_id: [u8; 16], rtt: f64, link_mdu: usize) -> Self {
Self {
channel: Channel::new(rtt),
link_id,
link_mdu,
session_keys: None,
outbound_packet_hashes: HashMap::new(),
}
@@ -557,10 +624,21 @@ impl LinkChannel {
link_id: [u8; 16],
rtt: f64,
keys: rns_link::key_derivation::LinkKeys,
) -> Self {
Self::new_encrypted_with_mdu(link_id, rtt, rns_wire::constants::LINK_MDU, keys)
}
/// Encrypted channel with an explicit Link MDU.
pub fn new_encrypted_with_mdu(
link_id: [u8; 16],
rtt: f64,
link_mdu: usize,
keys: rns_link::key_derivation::LinkKeys,
) -> Self {
Self {
channel: Channel::new(rtt),
link_id,
link_mdu,
session_keys: Some(keys),
outbound_packet_hashes: HashMap::new(),
}
@@ -578,7 +656,9 @@ impl LinkChannel {
&mut self,
msg: &dyn MessageBase,
) -> Result<PreparedChannelData, ChannelError> {
let (sequence, raw) = self.channel.send_tracked(msg)?;
let (sequence, raw) = self
.channel
.send_tracked_with_max_envelope(msg, Some(self.link_mdu))?;
if let Some(ref keys) = self.session_keys {
let data = rns_link::encryption::link_encrypt(keys, &raw)
.map_err(|_| ChannelError::ChannelClosed)?;
@@ -604,6 +684,7 @@ impl LinkChannel {
}
pub fn delivered(&mut self, sequence: u16, rtt: f64) {
self.channel.update_rtt(rtt);
self.channel.delivered(sequence, rtt);
}
@@ -613,6 +694,8 @@ impl LinkChannel {
pub fn delivered_by_packet_hash(&mut self, packet_hash: &[u8; 32], rtt: f64) -> Option<u16> {
let sequence = self.outbound_packet_hashes.remove(packet_hash)?;
self.outbound_packet_hashes
.retain(|_, tracked_sequence| *tracked_sequence != sequence);
self.delivered(sequence, rtt);
Some(sequence)
}
@@ -621,12 +704,42 @@ impl LinkChannel {
self.channel.is_ready_to_send()
}
pub fn is_drained(&self) -> bool {
self.channel.is_drained()
}
/// Maximum payload bytes available to one channel message.
pub fn mdu(&self) -> usize {
Channel::channel_mdu(self.link_mdu)
}
pub fn register_message_type(&mut self, msg_type: u16) -> Result<(), ChannelError> {
self.channel.register_message_type(msg_type)
}
pub fn register_system_type(&mut self, msg_type: u16) {
self.channel.register_system_type(msg_type);
}
pub fn add_message_handler(&mut self, handler: MessageCallback) -> HandlerId {
self.channel.add_message_handler(handler)
}
pub fn remove_message_handler(&mut self, id: HandlerId) -> bool {
self.channel.remove_message_handler(id)
}
pub fn clear_message_handlers(&mut self) {
self.channel.clear_message_handlers();
}
pub fn link_id(&self) -> &[u8; 16] {
&self.link_id
}
pub fn shutdown(&mut self) {
self.channel.shutdown();
self.outbound_packet_hashes.clear();
}
pub fn is_active(&self) -> bool {
@@ -657,6 +770,10 @@ impl LinkChannel {
pub fn next_timeout_duration(&self) -> Option<Duration> {
self.channel.next_timeout_duration()
}
pub fn update_rtt(&mut self, rtt: f64) {
self.channel.update_rtt(rtt);
}
}
#[cfg(test)]
@@ -731,6 +848,7 @@ mod tests {
fn test_channel_send_receive() {
let mut tx_channel = Channel::new(0.1);
let mut rx_channel = Channel::new(0.1);
rx_channel.register_message_type(0x0001).unwrap();
let msg = TestMessage::new(b"hello");
let raw = tx_channel.send(&msg).unwrap();
@@ -745,6 +863,7 @@ mod tests {
fn test_channel_ordering() {
let mut tx = Channel::new(0.1);
let mut rx = Channel::new(0.1);
rx.register_message_type(0x0001).unwrap();
let msg1 = TestMessage::new(b"first");
let msg2 = TestMessage::new(b"second");
@@ -776,6 +895,7 @@ mod tests {
fn test_channel_flow_control() {
let mut ch = Channel::new(0.1);
assert!(ch.is_ready_to_send());
assert!(ch.is_drained());
let msg = TestMessage::new(b"a");
// `WINDOW_INITIAL` = 2 slots, so two sends saturate the window.
@@ -783,9 +903,13 @@ mod tests {
ch.send(&msg).unwrap();
assert!(!ch.is_ready_to_send());
assert!(!ch.is_drained());
ch.delivered(0, 0.1);
assert!(ch.is_ready_to_send());
assert!(!ch.is_drained());
ch.delivered(1, 0.1);
assert!(ch.is_drained());
}
#[test]
@@ -808,6 +932,7 @@ mod tests {
fn test_duplicate_rejection() {
let mut tx = Channel::new(0.1);
let mut rx = Channel::new(0.1);
rx.register_message_type(0x0001).unwrap();
let msg = TestMessage::new(b"once");
let raw = tx.send(&msg).unwrap();
@@ -907,6 +1032,10 @@ mod tests {
ch.shutdown();
assert!(!ch.active);
assert!(ch.send(&msg).is_err());
assert!(matches!(
ch.receive(&Envelope::pack(&msg, 0).raw),
Err(ChannelError::ChannelClosed)
));
}
#[test]
@@ -973,8 +1102,8 @@ mod tests {
}
#[test]
fn test_no_registered_types_allows_all() {
// With an empty registry the channel must not filter inbound frames.
fn test_no_registered_types_rejects_all() {
// Python requires every inbound user or system type to be registered.
let mut ch = Channel::new(0.1);
let mut raw = Vec::new();
@@ -984,7 +1113,10 @@ mod tests {
raw.extend_from_slice(b"test");
let result = ch.receive(&raw);
assert!(result.is_ok());
assert!(matches!(
result,
Err(ChannelError::UnknownMessageType(0x1234))
));
}
#[test]
@@ -1031,6 +1163,7 @@ mod tests {
let raw = ch.send(&msg).unwrap();
let mut rx = Channel::new(0.1);
rx.register_message_type(0x0001).unwrap();
let counter2 = counter.clone();
let c4 = counter2.clone();
rx.add_message_handler(Box::new(move |_msg_type, _payload| {
@@ -1052,11 +1185,76 @@ mod tests {
assert_eq!(counter2.load(Ordering::SeqCst), 11);
}
#[test]
fn panicking_handler_does_not_block_delivery_or_later_handlers() {
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
let mut tx = Channel::new(0.1);
let raw = tx.send(&TestMessage::new(b"isolated")).unwrap();
let mut rx = Channel::new(0.1);
rx.register_message_type(0x0001).unwrap();
rx.add_message_handler(Box::new(|_, _| panic!("consumer failed")));
let later_handler_ran = Arc::new(AtomicBool::new(false));
let observed = later_handler_ran.clone();
rx.add_message_handler(Box::new(move |_, _| {
observed.store(true, Ordering::SeqCst);
false
}));
let delivered = rx.receive(&raw).unwrap();
assert_eq!(delivered, vec![(0x0001, b"isolated".to_vec())]);
assert!(later_handler_ran.load(Ordering::SeqCst));
}
#[test]
fn test_remove_message_handler_removes_only_its_token() {
use std::sync::{
Arc,
atomic::{AtomicU32, Ordering},
};
let mut tx = Channel::new(0.1);
let raw = tx.send(&TestMessage::new(b"handler tokens")).unwrap();
let mut rx = Channel::new(0.1);
rx.register_message_type(0x0001).unwrap();
let counter = Arc::new(AtomicU32::new(0));
let first_counter = counter.clone();
let first = rx.add_message_handler(Box::new(move |_, _| {
first_counter.fetch_add(1, Ordering::SeqCst);
false
}));
let second_counter = counter.clone();
let _second = rx.add_message_handler(Box::new(move |_, _| {
second_counter.fetch_add(10, Ordering::SeqCst);
false
}));
assert!(rx.remove_message_handler(first));
assert!(!rx.remove_message_handler(first));
rx.receive(&raw).unwrap();
assert_eq!(counter.load(Ordering::SeqCst), 10);
}
#[test]
fn test_live_rtt_updates_retransmit_timeout() {
let mut channel = Channel::new(0.1);
channel.send(&TestMessage::new(b"rtt")).unwrap();
let initial = channel.compute_timeout(1);
channel.update_rtt(1.0);
assert!(channel.compute_timeout(1) > initial);
}
#[test]
fn test_link_channel_send_receive() {
let link_id = [0xAA; 16];
let mut tx_lc = LinkChannel::new(link_id, 0.1);
let mut rx_lc = LinkChannel::new(link_id, 0.1);
rx_lc.register_message_type(0x0001).unwrap();
assert_eq!(*tx_lc.link_id(), link_id);
assert!(tx_lc.is_active());
@@ -1076,6 +1274,7 @@ mod tests {
let link_id = [0xBB; 16];
let mut tx_lc = LinkChannel::new(link_id, 0.1);
let mut rx_lc = LinkChannel::new(link_id, 0.1);
rx_lc.register_message_type(0x0001).unwrap();
// Send two messages
let msg1 = TestMessage::new(b"first");
@@ -1095,6 +1294,7 @@ mod tests {
tx_lc.delivered(0, 0.1);
tx_lc.delivered(1, 0.1);
assert_eq!(tx_lc.outstanding_count(), 0);
assert!(tx_lc.is_drained());
}
#[test]
@@ -1123,6 +1323,44 @@ mod tests {
assert!(resend.is_some());
}
#[test]
fn test_channel_delivery_clears_retransmission_hashes_for_sequence() {
let mut channel = LinkChannel::new([0xDF; 16], 0.1);
channel
.prepare_send_tracked(&TestMessage::new(b"tracked"))
.unwrap();
let first_hash = [1u8; 32];
let retry_hash = [2u8; 32];
channel.track_outbound_packet_hash(first_hash, 0);
channel.track_outbound_packet_hash(retry_hash, 0);
assert_eq!(channel.delivered_by_packet_hash(&retry_hash, 0.1), Some(0));
assert!(channel.outbound_packet_hashes.is_empty());
assert_eq!(channel.delivered_by_packet_hash(&first_hash, 0.1), None);
}
#[test]
fn test_link_channel_enforces_message_mdu_without_consuming_sequence() {
let link_id = [0xDE; 16];
let mut channel = LinkChannel::new_with_mdu(link_id, 0.1, 32);
assert_eq!(channel.mdu(), 32 - ENVELOPE_HEADER_SIZE);
let oversized = TestMessage::new(&vec![0u8; channel.mdu() + 1]);
assert!(matches!(
channel.prepare_send_tracked(&oversized),
Err(ChannelError::MessageTooLarge {
actual: 33,
max: 32
})
));
assert_eq!(channel.outstanding_count(), 0);
let prepared = channel
.prepare_send_tracked(&TestMessage::new(b"fits"))
.unwrap();
assert_eq!(prepared.sequence, 0);
}
#[test]
fn test_encrypted_link_channel_roundtrip() {
use rns_crypto::x25519::X25519PrivateKey;
@@ -1140,6 +1378,7 @@ mod tests {
let mut tx_lc = LinkChannel::new_encrypted(link_id, 0.1, keys_a);
let mut rx_lc = LinkChannel::new_encrypted(link_id, 0.1, keys_b);
rx_lc.register_message_type(0x0001).unwrap();
let msg = TestMessage::new(b"encrypted hello");
let raw = tx_lc.prepare_send(&msg).unwrap();
+595 -75
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;
}
}
@@ -562,6 +564,10 @@ impl InboundResource {
initial_map_hashes: Vec<[u8; MAPHASH_LEN]>,
link_sdu: Option<usize>,
) -> Result<Self, ResourceError> {
if total_parts == 0 {
return Err(ResourceError::InvalidAdvertisement);
}
// `total_size` is post-encryption: max plaintext + random_hash +
// TOKEN_OVERHEAD + worst-case PKCS7 pad.
const MAX_AES_BLOCK_PAD: usize = 16;
@@ -571,6 +577,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],
@@ -596,8 +612,8 @@ impl InboundResource {
tracing::trace!(
result = %format!("{:02x}{:02x}{:02x}{:02x}", mh[0], mh[1], mh[2], mh[3]),
data_len = data.len(),
data_first16 = %data.iter().take(16).map(|b| format!("{:02x}", b)).collect::<String>(),
random_hash = %self.random_hash.iter().map(|b| format!("{:02x}", b)).collect::<String>(),
data_first16 = %hex::encode(&data[..data.len().min(16)]),
random_hash = %hex::encode(self.random_hash),
random_len = self.random_hash.len(),
"resource part map hash"
);
@@ -795,6 +811,39 @@ pub struct MultiSegmentOutbound {
pub data_size: usize,
}
/// Sender-side plan that materialises at most one split Resource segment at a
/// time.
///
/// The signed/application payload remains owned by the plan, but plaintext,
/// encrypted parts and hash maps for future segments are not allocated until
/// [`Self::next_segment`] is called. This is the bounded primitive used by
/// large LXMF Direct deliveries; the eager [`MultiSegmentOutbound`] facade is
/// retained for callers that need random access to every segment.
pub struct LazyMultiSegmentOutbound {
data: Vec<u8>,
auto_compress: bool,
metadata: Option<Vec<u8>>,
metadata_wire_size: usize,
request_id: Option<Vec<u8>>,
is_response: bool,
next_offset: usize,
next_segment_index: usize,
pub original_hash: [u8; 32],
pub total_segments: usize,
pub data_size: usize,
}
fn required_segment_count(data_size: usize, metadata_wire_size: usize) -> usize {
if data_size == 0 {
return 1;
}
let first_payload_size = MAX_EFFICIENT_SIZE.saturating_sub(metadata_wire_size);
let first_len = data_size.min(first_payload_size);
1 + data_size
.saturating_sub(first_len)
.div_ceil(MAX_EFFICIENT_SIZE)
}
impl MultiSegmentOutbound {
/// Split `data` into `MAX_EFFICIENT_SIZE`-sized chunks, each wrapped in
/// its own `OutboundResource` with `flags.split = true` and the correct
@@ -824,64 +873,19 @@ impl MultiSegmentOutbound {
is_response: bool,
encrypt_fn: Option<&ResourceEncryptor<'_>>,
) -> Result<Self, ResourceError> {
if data.len() > MAX_RESOURCE_SIZE {
return Err(ResourceError::TooLarge);
}
let data_size = data.len();
// `original_hash` covers the uncompressed concatenated payload so
// the receiver can verify reassembly across all segments.
let random_hash: [u8; RANDOM_HASH_SIZE] =
rns_crypto::random::random_bytes(RANDOM_HASH_SIZE)
.try_into()
.unwrap();
let original_hash = compute_resource_hash(&data, &random_hash);
let metadata_wire_size = metadata.as_ref().map(|m| 3 + m.len()).unwrap_or(0);
if metadata_wire_size > MAX_EFFICIENT_SIZE {
return Err(ResourceError::MetadataTooLarge);
}
let first_payload_max = MAX_EFFICIENT_SIZE - metadata_wire_size;
let mut chunk_specs: Vec<(Vec<u8>, Option<Vec<u8>>)> = Vec::new();
if data.is_empty() {
chunk_specs.push((Vec::new(), metadata.clone()));
} else {
let first_len = data.len().min(first_payload_max);
chunk_specs.push((data[..first_len].to_vec(), metadata.clone()));
let mut offset = first_len;
while offset < data.len() {
let end = (offset + MAX_EFFICIENT_SIZE).min(data.len());
chunk_specs.push((data[offset..end].to_vec(), None));
offset = end;
}
}
let total_segments = chunk_specs.len();
let mut lazy = LazyMultiSegmentOutbound::with_options(
data,
auto_compress,
metadata,
request_id,
is_response,
)?;
let original_hash = lazy.original_hash;
let total_segments = lazy.total_segments;
let data_size = lazy.data_size;
let mut segments = Vec::with_capacity(total_segments);
for (i, (chunk, segment_metadata)) in chunk_specs.into_iter().enumerate() {
let mut resource = OutboundResource::with_options(
chunk,
auto_compress,
segment_metadata,
None,
encrypt_fn,
)?;
resource.flags.split = true;
resource.flags.is_response = is_response;
resource.segment_index = i + 1;
resource.total_segments = total_segments;
resource.request_id = request_id.clone();
resource.advertisement_data_size = data_size + metadata_wire_size;
// Stamps the shared `original_hash` onto each segment so the wire
// ADV (built later via `create_advertisement`) carries the
// coordinator key the receiver needs to reassemble.
resource.original_hash = Some(original_hash);
segments.push(resource);
while let Some(segment) = lazy.next_segment(encrypt_fn)? {
segments.push(segment);
}
Ok(Self {
@@ -930,6 +934,120 @@ impl MultiSegmentOutbound {
}
}
impl LazyMultiSegmentOutbound {
/// Create a sequential split-Resource plan without metadata or request
/// flags.
pub fn new(data: Vec<u8>, auto_compress: bool) -> Result<Self, ResourceError> {
Self::with_options(data, auto_compress, None, None, false)
}
/// Create a sequential split-Resource plan while preserving metadata and
/// request flags. Metadata is moved into the first segment when it is
/// materialised.
pub fn with_options(
data: Vec<u8>,
auto_compress: bool,
metadata: Option<Vec<u8>>,
request_id: Option<Vec<u8>>,
is_response: bool,
) -> Result<Self, ResourceError> {
if data.len() > MAX_RESOURCE_SIZE {
return Err(ResourceError::TooLarge);
}
let data_size = data.len();
let metadata_wire_size = metadata.as_ref().map(|value| 3 + value.len()).unwrap_or(0);
if metadata_wire_size > MAX_EFFICIENT_SIZE {
return Err(ResourceError::MetadataTooLarge);
}
let total_segments = required_segment_count(data_size, metadata_wire_size);
if total_segments > MAX_SEGMENTS {
return Err(ResourceError::TooLarge);
}
// `original_hash` covers the uncompressed concatenated payload so the
// receiver can verify reassembly across all segments.
let random_hash: [u8; RANDOM_HASH_SIZE] =
rns_crypto::random::random_bytes(RANDOM_HASH_SIZE)
.try_into()
.expect("fixed random-hash length");
let original_hash = compute_resource_hash(&data, &random_hash);
Ok(Self {
data,
auto_compress,
metadata,
metadata_wire_size,
request_id,
is_response,
next_offset: 0,
next_segment_index: 1,
original_hash,
total_segments,
data_size,
})
}
/// Number of segments that have not yet been materialised.
pub fn remaining_segments(&self) -> usize {
self.total_segments
.saturating_sub(self.next_segment_index.saturating_sub(1))
}
/// Build the next standalone outbound Resource. The caller owns the
/// returned segment and should request another only after the current one
/// has completed or been terminally discarded.
pub fn next_segment(
&mut self,
encrypt_fn: Option<&ResourceEncryptor<'_>>,
) -> Result<Option<OutboundResource>, ResourceError> {
if self.next_segment_index > self.total_segments {
return Ok(None);
}
let segment_index = self.next_segment_index;
let segment_metadata = if segment_index == 1 {
self.metadata.take()
} else {
None
};
let payload_limit = if segment_index == 1 {
MAX_EFFICIENT_SIZE - self.metadata_wire_size
} else {
MAX_EFFICIENT_SIZE
};
let end = self
.next_offset
.saturating_add(payload_limit)
.min(self.data.len());
let chunk = self.data[self.next_offset..end].to_vec();
let mut resource = OutboundResource::with_options(
chunk,
self.auto_compress,
segment_metadata,
None,
encrypt_fn,
)?;
resource.flags.split = true;
resource.flags.is_response = self.is_response;
resource.segment_index = segment_index;
resource.total_segments = self.total_segments;
resource.request_id = self.request_id.clone();
resource.advertisement_data_size = self.data_size + self.metadata_wire_size;
resource.original_hash = Some(self.original_hash);
self.next_offset = end;
self.next_segment_index += 1;
if self.next_segment_index > self.total_segments {
// The current segment now owns its bytes. Release the complete
// source allocation before it begins transferring.
self.data = Vec::new();
}
Ok(Some(resource))
}
}
/// Inbound multi-segment resource coordinator: collects `InboundResource`
/// segments and reassembles the original payload. Two ingest paths feed
/// `assembled_segments`: `set_segment` + `assemble_segment` (unit tests) and
@@ -1379,6 +1497,34 @@ impl OutboundTransfer {
TransferAction::None
}
/// Sender-side advertisement watchdog for request-driven runtimes.
///
/// An outbound transfer remains `Advertised` until the receiver's first
/// `RESOURCE_REQ` arrives. If that advertisement is lost, resend it up to
/// the Python-compatible retry limit instead of leaving the transfer
/// dormant forever.
pub fn check_timeout(&mut self) -> TransferAction {
if self.resource.state != ResourceState::Advertised {
return TransferAction::None;
}
let timeout = Duration::from_secs_f64(
self.rtt.as_secs_f64() * rns_link::constants::TRAFFIC_TIMEOUT_FACTOR + PROCESSING_GRACE,
);
if self.started_at.elapsed() <= timeout {
return TransferAction::None;
}
if self.retries < MAX_ADV_RETRIES {
self.retries += 1;
self.started_at = Instant::now();
TransferAction::SendAdvertisement(self.create_advertisement())
} else {
self.resource.state = ResourceState::Failed;
TransferAction::Failed("resource advertisement timed out".to_string())
}
}
/// Consume a hashmap-update frame from the receiver.
///
/// Wire layout:
@@ -1539,8 +1685,7 @@ impl OutboundTransfer {
// The collision guard widens the search window so out-of-order
// part requests don't fall outside the scanned range when the
// receiver's consecutive height lags ours.
let guard_size =
crate::resource_adv::collision_guard_size(rns_wire::constants::ENCRYPTED_MDU);
let guard_size = crate::resource_adv::collision_guard_size(rns_wire::constants::LINK_MDU);
let search_start = self.receiver_min_consecutive_height;
let search_end = (search_start + guard_size).min(self.resource.num_parts());
@@ -1587,7 +1732,7 @@ impl OutboundTransfer {
};
let hashmap_max_len =
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU);
crate::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU);
// Python cancels if an exhausted request cursor is not aligned to
// a hashmap segment boundary.
@@ -1611,6 +1756,17 @@ impl OutboundTransfer {
}
}
// An empty hashmap means there is nothing to answer the receiver's
// request with — cancel rather than emit a useless empty HMU (1.3.9).
if hashmap_bytes.is_empty() {
self.resource.state = ResourceState::Failed;
actions.push(TransferAction::SendCancel(
CancelType::Icl,
self.resource.resource_hash,
));
return actions;
}
// HMU wire layout: resource_hash(32) || msgpack([segment, hashmap]).
let hmu_payload = {
use rmpv::Value;
@@ -1672,7 +1828,7 @@ impl OutboundTransfer {
self.resource.random_hash.to_vec(),
self.resource.flags,
&self.resource.map_hashes,
rns_wire::constants::ENCRYPTED_MDU,
rns_wire::constants::LINK_MDU,
);
// `ResourceAdvertisement::new` defaults to single-segment metadata
// (`segment_index = 1`, `total_segments = 1`, `original_hash =
@@ -2108,17 +2264,41 @@ impl InboundTransfer {
return TransferAction::None;
}
// Only process a hashmap update we actually solicited (1.3.9). An
// unsolicited HMU is dropped rather than resetting the retry/activity
// counters or injecting hashmap entries outside the request cycle.
if !self.waiting_for_hmu {
return TransferAction::None;
}
// An empty/degenerate HMU carries no hashes and is invalid — cancel the
// transfer rather than spinning on an unsatisfiable request (1.3.9).
if hashmap_data.len() < MAPHASH_LEN {
return self.cancel();
}
let hashmap_max_len = crate::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU);
let Some(segment_start) = segment.checked_mul(hashmap_max_len) else {
return self.cancel();
};
if segment_start >= self.resource.total_parts {
return self.cancel();
}
self.resource.state = ResourceState::Transferring;
self.last_activity = Instant::now();
self.retries_left = MAX_RETRIES;
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_start.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() {
@@ -2578,6 +2758,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];
@@ -2702,6 +2907,47 @@ mod tests {
assert!(matches!(action, TransferAction::SendPart(0, _)));
}
#[test]
fn test_outbound_advertisement_watchdog_retries() {
let mut transfer = OutboundTransfer::new(
b"retry advertisement".to_vec(),
false,
Duration::from_millis(1),
)
.unwrap();
assert!(matches!(
transfer.tick(),
TransferAction::SendAdvertisement(_)
));
transfer.started_at = Instant::now() - Duration::from_secs(60);
assert!(matches!(
transfer.check_timeout(),
TransferAction::SendAdvertisement(_)
));
assert_eq!(transfer.retries, 1);
assert_eq!(transfer.resource.state, ResourceState::Advertised);
}
#[test]
fn test_outbound_advertisement_watchdog_fails_after_retry_limit() {
let mut transfer = OutboundTransfer::new(
b"failed advertisement".to_vec(),
false,
Duration::from_millis(1),
)
.unwrap();
transfer.tick();
transfer.retries = MAX_ADV_RETRIES;
transfer.started_at = Instant::now() - Duration::from_secs(60);
assert!(matches!(
transfer.check_timeout(),
TransferAction::Failed(_)
));
assert_eq!(transfer.resource.state, ResourceState::Failed);
}
#[test]
fn test_outbound_transfer_hmu_handling() {
let data = b"small data".to_vec();
@@ -2761,6 +3007,65 @@ 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)));
let result = InboundResource::new(
0,
1024,
1000,
[0xAA; RANDOM_HASH_SIZE],
[0xBB; 32],
ResourceFlags::default(),
Vec::new(),
);
assert!(matches!(result, Err(ResourceError::InvalidAdvertisement)));
// 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
@@ -3163,12 +3468,91 @@ mod tests {
assert_eq!(multi.segments[1].data.len(), 1000);
}
#[test]
fn test_lazy_multi_segment_materialises_only_on_demand() {
let data = vec![0xA6; MAX_EFFICIENT_SIZE * 2 + 321];
let mut lazy = LazyMultiSegmentOutbound::new(data.clone(), false).unwrap();
assert_eq!(lazy.total_segments, 3);
assert_eq!(lazy.remaining_segments(), 3);
let first = lazy.next_segment(None).unwrap().unwrap();
assert_eq!(first.segment_index, 1);
assert_eq!(first.total_segments, 3);
assert_eq!(first.data.len(), MAX_EFFICIENT_SIZE);
assert_eq!(lazy.remaining_segments(), 2);
let second = lazy.next_segment(None).unwrap().unwrap();
assert_eq!(second.segment_index, 2);
assert_eq!(second.data.len(), MAX_EFFICIENT_SIZE);
assert_eq!(lazy.remaining_segments(), 1);
let third = lazy.next_segment(None).unwrap().unwrap();
assert_eq!(third.segment_index, 3);
assert_eq!(third.data.len(), 321);
assert_eq!(lazy.remaining_segments(), 0);
assert!(lazy.next_segment(None).unwrap().is_none());
let rebuilt: Vec<u8> = [first, second, third]
.into_iter()
.flat_map(|segment| segment.data)
.collect();
assert_eq!(rebuilt, data);
}
#[test]
fn test_lazy_multi_segment_preserves_metadata_and_request_flags() {
let metadata = b"\x81\xa4name\xa8file.bin".to_vec();
let request_id = vec![0x42; 16];
let data = vec![0x5C; MAX_EFFICIENT_SIZE + 10];
let mut lazy = LazyMultiSegmentOutbound::with_options(
data,
false,
Some(metadata.clone()),
Some(request_id.clone()),
true,
)
.unwrap();
let first = lazy.next_segment(None).unwrap().unwrap();
let second = lazy.next_segment(None).unwrap().unwrap();
assert!(first.flags.has_metadata);
assert!(
first
.metadata
.as_deref()
.is_some_and(|wire| wire.ends_with(&metadata))
);
assert_eq!(first.metadata_size, metadata.len() + 3);
assert!(!second.flags.has_metadata);
assert_eq!(first.request_id, Some(request_id.clone()));
assert_eq!(second.request_id, Some(request_id));
assert!(first.flags.is_response);
assert!(second.flags.is_response);
assert_eq!(first.original_hash, second.original_hash);
assert_eq!(
first.advertisement_data_size,
second.advertisement_data_size
);
}
#[test]
fn test_multi_segment_outbound_too_large() {
let data = vec![0; MAX_RESOURCE_SIZE + 1];
assert!(MultiSegmentOutbound::new(data, false).is_err());
}
#[test]
fn test_multi_segment_plan_caps_metadata_induced_extra_segment() {
let bounded_payload = MAX_EFFICIENT_SIZE * MAX_SEGMENTS;
assert_eq!(required_segment_count(bounded_payload, 0), MAX_SEGMENTS);
assert_eq!(required_segment_count(bounded_payload, 4), MAX_SEGMENTS + 1);
assert_eq!(
required_segment_count(MAX_RESOURCE_SIZE, 0),
MAX_SEGMENTS + 1
);
}
#[test]
fn test_multi_segment_cancel_all_fans_out() {
// Python parity: head-cancel must tear down every follow-on segment.
@@ -3836,7 +4220,7 @@ mod tests {
let mut sender =
OutboundTransfer::new(data.clone(), false, Duration::from_millis(100)).unwrap();
assert!(
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU) > 1,
crate::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU) > 1,
"test requires a multi-entry hashmap segment"
);
@@ -4065,14 +4449,14 @@ mod tests {
assert_eq!(inbound.hashmap_height, initial_height);
// Build hashmap data for segment 0 with additional hashes
let hashmap_max_len =
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU);
let hashmap_max_len = crate::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU);
let mut hashmap_bytes = Vec::new();
let end = outbound.map_hashes.len().min(hashmap_max_len);
for i in 0..end {
hashmap_bytes.extend_from_slice(&outbound.map_hashes[i]);
}
inbound.waiting_for_hmu = true;
let action = inbound.hashmap_update(0, &hashmap_bytes);
// Should have extended map_hashes
@@ -4083,6 +4467,143 @@ mod tests {
assert!(matches!(action, TransferAction::SendRequest(_)));
}
#[test]
fn test_hashmap_update_ignores_unsolicited() {
// 1.3.9: an HMU that was not solicited (waiting_for_hmu == false) is
// dropped without touching transfer state.
let data = vec![0u8; 2000];
let outbound = OutboundResource::new(data.clone(), false, None).unwrap();
let mut inbound = InboundTransfer::from_advertisement(
outbound.num_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();
assert!(!inbound.waiting_for_hmu);
let before = inbound.resource.map_hashes.len();
let action = inbound.hashmap_update(0, &outbound.map_hashes[0]);
assert!(matches!(action, TransferAction::None));
assert_eq!(inbound.resource.map_hashes.len(), before);
assert_ne!(inbound.resource.state, ResourceState::Failed);
}
#[test]
fn test_hashmap_update_empty_cancels() {
// 1.3.9: a solicited but empty/degenerate HMU cancels the transfer and
// emits a receiver cancel (RESOURCE_RCL).
let data = vec![0u8; 2000];
let outbound = OutboundResource::new(data.clone(), false, None).unwrap();
let mut inbound = InboundTransfer::from_advertisement(
outbound.num_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();
inbound.waiting_for_hmu = true;
let action = inbound.hashmap_update(0, &[]);
assert!(matches!(
action,
TransferAction::SendCancel(CancelType::Rcl, _)
));
assert_eq!(inbound.resource.state, ResourceState::Failed);
}
#[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();
for segment in [1_000_000, usize::MAX] {
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 and overflowing segment indices must neither grow the
// hashmap nor refresh the watchdog indefinitely.
inbound.waiting_for_hmu = true;
let action = inbound.hashmap_update(segment, &outbound.map_hashes[0]);
assert!(matches!(
action,
TransferAction::SendCancel(CancelType::Rcl, _)
));
assert_eq!(inbound.resource.map_hashes.len(), 2);
assert_eq!(inbound.resource.state, ResourceState::Failed);
}
}
#[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::LINK_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.waiting_for_hmu = true;
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
@@ -4253,8 +4774,7 @@ mod tests {
let mut request_data = Vec::new();
request_data.push(HASHMAP_IS_EXHAUSTED);
// last_map_hash -- use the hash at hashmap_max_len boundary
let hashmap_max_len =
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU);
let hashmap_max_len = crate::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU);
let boundary_idx = hashmap_max_len.min(sender.resource.num_parts()) - 1;
request_data.extend_from_slice(&sender.resource.map_hashes[boundary_idx]);
request_data.extend_from_slice(&sender.resource.resource_hash);
+2 -2
View File
@@ -289,8 +289,8 @@ mod tests {
#[test]
fn test_default_link_mdu_matches_python_hashmap_capacity() {
assert_eq!(rns_wire::constants::ENCRYPTED_MDU, 431);
assert_eq!(hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU), 74);
assert_eq!(rns_wire::constants::LINK_MDU, 431);
assert_eq!(hashmap_max_len(rns_wire::constants::LINK_MDU), 74);
}
#[test]
+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() {
if 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.
+5
View File
@@ -3,6 +3,7 @@ name = "rns-runtime"
description = "Core runtime, config parsing, and lifecycle for Reticulum"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[features]
@@ -24,6 +25,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"] }
@@ -31,3 +33,6 @@ serde = { workspace = true }
subtle = { workspace = true }
hex = { workspace = true }
nix = { workspace = true }
[dev-dependencies]
tokio = { workspace = true, features = ["test-util"] }
+28
View File
@@ -0,0 +1,28 @@
# Reticulum runtime examples
These examples mirror the application-facing subjects in the upstream Python
Reticulum examples while using explicit Rust runtime ownership.
Most networked examples have `server` and `client` modes:
```console
cargo run -p rns-runtime --example link -- server
cargo run -p rns-runtime --example link -- client <destination-hash> "hello"
```
Pass `--config <directory>` to either mode to select a Reticulum config
directory. Servers print their destination hash and announce once at startup.
The `ratchets` example is a local composition recipe because ratchet files and
identity files are application-owned secrets:
```console
cargo run -p rns-runtime --example ratchets -- identity.key ratchets.bin
```
Use private, access-controlled paths for both files in a real application.
Python's `ExampleInterface.py` demonstrates runtime-loaded Python classes.
Rust instead integrates third-party interfaces at compile time through
`rns_interface::InterfaceHandle` and the runtime's interface factory. This is
an intentional ownership and type-safety difference, not a wire-protocol gap.
+66
View File
@@ -0,0 +1,66 @@
mod support;
use rns_runtime::prelude::*;
use support::*;
use tokio::io::{AsyncBufReadExt, BufReader};
const ASPECT: &str = "example_utilities.announcesample.fruits";
#[tokio::main]
async fn main() -> ExampleResult {
let args = ExampleArgs::parse()?;
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let mut subscription = runtime
.handle
.subscribe_announces(Some(ASPECT.to_string()), false)
.await?;
let destination = register_single(
&runtime.handle,
Identity::new(),
ASPECT,
DestinationRuntimeOptions::default(),
)
.await?;
print_destination(
"Announce destination",
destination.handle.destination_hash(),
);
println!("Press enter to announce with app data; Ctrl-C stops");
let mut lines = BufReader::new(tokio::io::stdin()).lines();
loop {
tokio::select! {
_ = runtime.shutdown.wait() => break,
announce = subscription.recv() => {
let Some(announce) = announce else { break };
println!(
"Observed {} app_data={}",
hex::encode(announce.destination_hash),
announce
.app_data
.as_deref()
.map(String::from_utf8_lossy)
.unwrap_or_default(),
);
}
line = lines.next_line() => {
if line?.is_none() {
break;
}
destination
.handle
.announce(DestinationAnnounceOptions {
app_data: Some(b"Peach".to_vec()),
..DestinationAnnounceOptions::default()
})
.await?;
println!("Announced {}", hex::encode(destination.handle.destination_hash()));
}
}
}
subscription.close().await?;
destination.close().await?;
runtime.stop().await;
Ok(())
}
+37
View File
@@ -0,0 +1,37 @@
mod support;
use rns_runtime::prelude::*;
use support::*;
const ASPECT: &str = "example_utilities.broadcast";
#[tokio::main]
async fn main() -> ExampleResult {
let args = ExampleArgs::parse()?;
let message = args
.positional
.first()
.map_or("Hello Reticulum", String::as_str);
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let destination = Destination::new(None, Direction::Out, DestType::Plain, ASPECT)?;
let sent = runtime
.handle
.send_to(
&destination,
message.as_bytes(),
SendOptions {
create_receipt: false,
..SendOptions::default()
},
)
.await?;
println!(
"Broadcast {} to {}",
hex::encode(sent.packet_hash),
hex::encode(destination.hash)
);
runtime.stop().await;
Ok(())
}
+106
View File
@@ -0,0 +1,106 @@
mod support;
use std::time::Duration;
use rns_protocol::channel_message::{MessageBase, SMT_STREAM_DATA};
use rns_protocol::stream_data::StreamDataMessage;
use rns_runtime::prelude::*;
use support::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
const ASPECT: &str = "example_utilities.bufferexample";
const STREAM_ID: u16 = 0;
#[tokio::main]
async fn main() -> ExampleResult {
let args = ExampleArgs::parse()?;
match args.require(0, "mode: server | client")? {
"server" => server(args).await,
"client" => client(args).await,
other => Err(format!("unknown mode {other}; use server or client").into()),
}
}
async fn server(args: ExampleArgs) -> ExampleResult {
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let mut destination = register_single(
&runtime.handle,
Identity::new(),
ASPECT,
DestinationRuntimeOptions::default(),
)
.await?;
print_destination("Buffer destination", destination.handle.destination_hash());
destination
.handle
.announce(DestinationAnnounceOptions::default())
.await?;
loop {
tokio::select! {
_ = runtime.shutdown.wait() => break,
message = destination.events.channel_messages.recv() => {
let Some(message) = message else { break };
if message.msg_type != SMT_STREAM_DATA {
continue;
}
let mut frame = StreamDataMessage::new(0, Vec::new(), false);
frame.unpack(&message.payload)?;
if frame.eof {
destination
.handle
.send_channel(
message.link_id,
SMT_STREAM_DATA,
StreamDataMessage::new(frame.stream_id, Vec::new(), true).pack(),
)
.await?;
continue;
}
let text = String::from_utf8_lossy(&frame.data);
println!("Received over Buffer: {text}");
let reply = StreamDataMessage::new(
frame.stream_id,
format!("Received: {text}").into_bytes(),
false,
);
destination
.handle
.send_channel(message.link_id, SMT_STREAM_DATA, reply.pack())
.await?;
}
}
}
destination.close().await?;
runtime.stop().await;
Ok(())
}
async fn client(args: ExampleArgs) -> ExampleResult {
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
let message = args
.positional
.get(2)
.map_or("Hello Buffer", String::as_str);
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let session = connect(&runtime.handle, destination_hash, false, "buffer-example").await?;
let mut buffer = session
.handle
.channel()
.create_bidirectional_buffer(STREAM_ID, STREAM_ID)
.await?;
buffer.write_all(message.as_bytes()).await?;
buffer.flush().await?;
let expected_len = "Received: ".len() + message.len();
let mut reply = vec![0; expected_len];
tokio::time::timeout(Duration::from_secs(30), buffer.read_exact(&mut reply)).await??;
println!("Reply: {}", String::from_utf8_lossy(&reply));
buffer.shutdown().await?;
session.handle.close().await;
runtime.stop().await;
Ok(())
}
+93
View File
@@ -0,0 +1,93 @@
mod support;
use std::time::Duration;
use rns_runtime::prelude::*;
use support::*;
const ASPECT: &str = "example_utilities.channelexample";
const STRING_MESSAGE: u16 = 0x0101;
#[tokio::main]
async fn main() -> ExampleResult {
let args = ExampleArgs::parse()?;
match args.require(0, "mode: server | client")? {
"server" => server(args).await,
"client" => client(args).await,
other => Err(format!("unknown mode {other}; use server or client").into()),
}
}
async fn server(args: ExampleArgs) -> ExampleResult {
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let mut destination = register_single(
&runtime.handle,
Identity::new(),
ASPECT,
DestinationRuntimeOptions::default(),
)
.await?;
print_destination("Channel destination", destination.handle.destination_hash());
destination
.handle
.announce(DestinationAnnounceOptions::default())
.await?;
loop {
tokio::select! {
_ = runtime.shutdown.wait() => break,
message = destination.events.channel_messages.recv() => {
let Some(message) = message else { break };
if message.msg_type == STRING_MESSAGE {
println!(
"Received on {}: {}",
hex::encode(message.link_id),
String::from_utf8_lossy(&message.payload),
);
destination
.handle
.send_channel(message.link_id, STRING_MESSAGE, message.payload)
.await?;
}
}
}
}
destination.close().await?;
runtime.stop().await;
Ok(())
}
async fn client(args: ExampleArgs) -> ExampleResult {
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
let message = args
.positional
.get(2)
.map_or("Hello Channel", String::as_str);
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let session = connect(&runtime.handle, destination_hash, false, "channel-example").await?;
let channel = session.handle.channel();
channel.register_message_type(STRING_MESSAGE).await?;
let (reply_tx, mut reply_rx) = tokio::sync::mpsc::channel(1);
let handler = channel
.add_message_handler(move |msg_type, payload| {
if msg_type != STRING_MESSAGE {
return false;
}
let _ = reply_tx.try_send(payload.to_vec());
true
})
.await?;
channel.send_raw(STRING_MESSAGE, message.as_bytes()).await?;
let reply = tokio::time::timeout(Duration::from_secs(30), reply_rx.recv())
.await?
.ok_or("Channel closed before the echo arrived")?;
println!("Reply: {}", String::from_utf8_lossy(&reply));
channel.remove_message_handler(handler).await?;
session.handle.close().await;
runtime.stop().await;
Ok(())
}
+65
View File
@@ -0,0 +1,65 @@
mod support;
use rns_runtime::prelude::*;
use support::*;
const ASPECT: &str = "example_utilities.echo";
#[tokio::main]
async fn main() -> ExampleResult {
let args = ExampleArgs::parse()?;
match args.require(0, "mode: server | client")? {
"server" => server(args).await,
"client" => client(args).await,
other => Err(format!("unknown mode {other}; use server or client").into()),
}
}
async fn server(args: ExampleArgs) -> ExampleResult {
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let mut destination = register_single(
&runtime.handle,
Identity::new(),
ASPECT,
DestinationRuntimeOptions {
proof_strategy: ProofStrategy::ProveAll,
..DestinationRuntimeOptions::default()
},
)
.await?;
print_destination("Echo destination", destination.handle.destination_hash());
destination
.handle
.announce(DestinationAnnounceOptions::default())
.await?;
loop {
tokio::select! {
_ = runtime.shutdown.wait() => break,
packet = destination.events.packets.recv() => {
let Some(packet) = packet else { break };
println!("Proved {} bytes: {}", packet.data.len(), String::from_utf8_lossy(&packet.data));
}
}
}
destination.close().await?;
runtime.stop().await;
Ok(())
}
async fn client(args: ExampleArgs) -> ExampleResult {
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
let message = args.positional.get(2).map_or("Hello echo", String::as_str);
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let destination =
recall_outbound_destination(&runtime.handle, destination_hash, ASPECT).await?;
let sent = runtime
.handle
.send_to(&destination, message.as_bytes(), SendOptions::default())
.await?;
let receipt = sent.receipt.ok_or("echo send did not create a receipt")?;
let rtt = receipt.delivered().await?;
println!("Delivered in {:.3} ms", rtt.as_secs_f64() * 1000.0);
runtime.stop().await;
Ok(())
}
+122
View File
@@ -0,0 +1,122 @@
mod support;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::Path;
use rns_runtime::prelude::*;
use support::*;
const ASPECT: &str = "example_utilities.filetransfer.server";
#[tokio::main]
async fn main() -> ExampleResult {
let args = ExampleArgs::parse()?;
match args.require(0, "mode: server | client")? {
"server" => server(args).await,
"client" => client(args).await,
other => Err(format!("unknown mode {other}; use server or client").into()),
}
}
async fn server(args: ExampleArgs) -> ExampleResult {
let output_path = args.require(1, "new output file")?.to_string();
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let mut destination = register_single(
&runtime.handle,
Identity::new(),
ASPECT,
DestinationRuntimeOptions {
resource_strategy: ResourceStrategy::AcceptAll,
..DestinationRuntimeOptions::default()
},
)
.await?;
print_destination(
"File-transfer destination",
destination.handle.destination_hash(),
);
destination
.handle
.announce(DestinationAnnounceOptions::default())
.await?;
println!("The first completed transfer will be written to {output_path}");
let completed = tokio::select! {
_ = runtime.shutdown.wait() => None,
completed = destination.events.resource_completions.recv() => completed,
};
if let Some(completed) = completed {
let mut output = OpenOptions::new()
.write(true)
.create_new(true)
.open(&output_path)?;
output.write_all(&completed.data)?;
output.sync_all()?;
println!(
"Wrote {} bytes to {} without replacing an existing file",
completed.data.len(),
output_path,
);
}
destination.close().await?;
runtime.stop().await;
Ok(())
}
async fn client(args: ExampleArgs) -> ExampleResult {
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
let input_path = Path::new(args.require(2, "input file")?);
let input = File::open(input_path)?;
let file_name = input_path
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("resource")
.as_bytes()
.to_vec();
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let session = connect(
&runtime.handle,
destination_hash,
false,
"filetransfer-example",
)
.await?;
let transfer = session
.handle
.send_resource(
input,
ResourceOptions {
auto_compress: false,
metadata: Some(file_name),
},
)
.await?;
let mut progress = transfer.progress();
let concluded = transfer.concluded();
tokio::pin!(concluded);
loop {
tokio::select! {
result = &mut concluded => {
let receipt = result?;
println!(
"Transferred {} bytes as {}",
receipt.data_size,
hex::encode(receipt.resource_id),
);
break;
}
changed = progress.changed() => {
changed?;
println!("Progress: {:.1}%", *progress.borrow() * 100.0);
}
}
}
session.handle.close().await;
runtime.stop().await;
Ok(())
}
+70
View File
@@ -0,0 +1,70 @@
mod support;
use rns_runtime::prelude::*;
use support::*;
const ASPECT: &str = "example_utilities.identifyexample";
#[tokio::main]
async fn main() -> ExampleResult {
let args = ExampleArgs::parse()?;
match args.require(0, "mode: server | client")? {
"server" => server(args).await,
"client" => client(args).await,
other => Err(format!("unknown mode {other}; use server or client").into()),
}
}
async fn server(args: ExampleArgs) -> ExampleResult {
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let mut destination = register_single(
&runtime.handle,
Identity::new(),
ASPECT,
DestinationRuntimeOptions::default(),
)
.await?;
print_destination(
"Identification destination",
destination.handle.destination_hash(),
);
destination
.handle
.announce(DestinationAnnounceOptions::default())
.await?;
loop {
tokio::select! {
_ = runtime.shutdown.wait() => break,
established = destination.events.links_established.recv() => {
let Some(link_id) = established else { break };
println!("Link {} established", hex::encode(link_id));
}
identified = destination.events.links_identified.recv() => {
let Some((link_id, identity_hash)) = identified else { break };
println!(
"Link {} identified as {}",
hex::encode(link_id),
hex::encode(identity_hash),
);
}
}
}
destination.close().await?;
runtime.stop().await;
Ok(())
}
async fn client(args: ExampleArgs) -> ExampleResult {
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let session = connect(&runtime.handle, destination_hash, true, "identify-example").await?;
println!(
"Established and identified Link {}",
hex::encode(session.handle.link_id())
);
session.handle.close().await;
runtime.stop().await;
Ok(())
}
+79
View File
@@ -0,0 +1,79 @@
mod support;
use std::time::Duration;
use rns_runtime::prelude::*;
use support::*;
const ASPECT: &str = "example_utilities.linkexample";
#[tokio::main]
async fn main() -> ExampleResult {
let args = ExampleArgs::parse()?;
match args.require(0, "mode: server | client")? {
"server" => server(args).await,
"client" => client(args).await,
other => Err(format!("unknown mode {other}; use server or client").into()),
}
}
async fn server(args: ExampleArgs) -> ExampleResult {
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let mut destination = register_single(
&runtime.handle,
Identity::new(),
ASPECT,
DestinationRuntimeOptions::default(),
)
.await?;
print_destination("Link destination", destination.handle.destination_hash());
destination
.handle
.announce(DestinationAnnounceOptions::default())
.await?;
loop {
tokio::select! {
_ = runtime.shutdown.wait() => break,
packet = destination.events.link_packets.recv() => {
let Some((data, link_id)) = packet else { break };
println!("Received on {}: {}", hex::encode(link_id), String::from_utf8_lossy(&data));
destination
.handle
.send_link_packet(link_id, data)
.await?;
}
}
}
destination.close().await?;
runtime.stop().await;
Ok(())
}
async fn client(args: ExampleArgs) -> ExampleResult {
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
let message = args.positional.get(2).map_or("Hello Link", String::as_str);
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let mut session = connect(&runtime.handle, destination_hash, false, "link-example").await?;
session
.handle
.send_packet(message.as_bytes().to_vec())
.await?;
let reply = tokio::time::timeout(Duration::from_secs(30), async {
while let Some(event) = session.events.recv().await {
if let LinkSessionEvent::Packet { data, .. } = event {
return Some(data);
}
}
None
})
.await?
.ok_or("Link closed before the echo arrived")?;
println!("Reply: {}", String::from_utf8_lossy(&reply));
session.handle.close().await;
runtime.stop().await;
Ok(())
}
+43
View File
@@ -0,0 +1,43 @@
mod support;
use rns_runtime::prelude::*;
use support::*;
const ASPECT: &str = "example_utilities.minimalsample";
#[tokio::main]
async fn main() -> ExampleResult {
let args = ExampleArgs::parse()?;
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let mut destination = register_single(
&runtime.handle,
Identity::new(),
ASPECT,
DestinationRuntimeOptions {
proof_strategy: ProofStrategy::ProveAll,
..DestinationRuntimeOptions::default()
},
)
.await?;
print_destination("Minimal destination", destination.handle.destination_hash());
destination
.handle
.announce(DestinationAnnounceOptions::default())
.await?;
println!("Announced; waiting for packets (Ctrl-C to stop)");
loop {
tokio::select! {
_ = runtime.shutdown.wait() => break,
packet = destination.events.packets.recv() => {
let Some(packet) = packet else { break };
println!("Received: {}", String::from_utf8_lossy(&packet.data));
}
}
}
destination.close().await?;
runtime.stop().await;
Ok(())
}
+73
View File
@@ -0,0 +1,73 @@
mod support;
use std::path::Path;
use rns_runtime::prelude::*;
use support::*;
const ASPECT: &str = "example_utilities.ratchet.echo.request";
fn load_or_create_identity(path: &Path) -> ExampleResult<Identity> {
if path.exists() {
return Ok(Identity::from_file(path)?);
}
let identity = Identity::new();
identity.to_file(path)?;
Ok(identity)
}
fn load_or_create_ring(path: &Path, identity: &Identity) -> ExampleResult<PersistentRatchetRing> {
let mut ring = PersistentRatchetRing::open(path, identity)?;
ring.ensure_current(identity)?;
Ok(ring)
}
fn main() -> ExampleResult {
let args = ExampleArgs::parse()?;
let identity_path = Path::new(args.require(0, "identity file")?);
let ratchet_path = Path::new(args.require(1, "ratchet file")?);
let message = args
.positional
.get(2)
.map_or("Forward-secret message", String::as_str);
let identity = load_or_create_identity(identity_path)?;
let ring = load_or_create_ring(ratchet_path, &identity)?;
let ratchet = ring
.current_public_key()
.ok_or("ratchet ring has no current key")?;
let mut inbound = Destination::new(Some(&identity), Direction::In, DestType::Single, ASPECT)?;
inbound.enable_ratchets(true);
inbound.set_local_ratchet(ratchet);
let announce = inbound.announce_packet(
&identity,
Some(b"ratchet example"),
inbound.get_ratchet_for_announce().as_ref(),
false,
None,
0.0,
)?;
let remote_identity = Identity::from_public_key(&identity.get_public_key())?;
let mut outbound = Destination::new(
Some(&remote_identity),
Direction::Out,
DestType::Single,
ASPECT,
)?;
outbound.set_remote_ratchet(ratchet);
let ciphertext = outbound.encrypt(
message.as_bytes(),
&remote_identity,
outbound.remote_ratchet_pub.as_ref(),
)?;
let plaintext =
inbound.decrypt_with_ratchets(&ciphertext, &identity, Some(ring.private_keys()))?;
println!("Destination: {}", hex::encode(inbound.hash));
println!("Retained ratchets: {}", ring.len());
println!("Signed announce: {} bytes", announce.len());
println!("Decrypted: {}", String::from_utf8_lossy(&plaintext));
Ok(())
}
+85
View File
@@ -0,0 +1,85 @@
mod support;
use std::time::Duration;
use rns_runtime::prelude::*;
use support::*;
const ASPECT: &str = "example_utilities.requestexample";
const REQUEST_PATH: &str = "/echo";
#[tokio::main]
async fn main() -> ExampleResult {
let args = ExampleArgs::parse()?;
match args.require(0, "mode: server | client")? {
"server" => server(args).await,
"client" => client(args).await,
other => Err(format!("unknown mode {other}; use server or client").into()),
}
}
async fn server(args: ExampleArgs) -> ExampleResult {
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let destination = register_single(
&runtime.handle,
Identity::new(),
ASPECT,
DestinationRuntimeOptions::default(),
)
.await?;
destination
.handle
.register_request_handler(
REQUEST_PATH,
AllowPolicy::AllowAll,
Vec::new(),
true,
|request| {
println!(
"{} requested {} bytes on {}",
hex::encode(request.link_id),
request.data.len(),
request.path,
);
RequestOutcome::Reply(request.data)
},
)
.await?;
print_destination("Request destination", destination.handle.destination_hash());
destination
.handle
.announce(DestinationAnnounceOptions::default())
.await?;
runtime.shutdown.wait().await;
destination.close().await?;
runtime.stop().await;
Ok(())
}
async fn client(args: ExampleArgs) -> ExampleResult {
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
let message = args
.positional
.get(2)
.map_or("Hello request", String::as_str);
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let session = connect(&runtime.handle, destination_hash, false, "request-example").await?;
let response = session
.handle
.request(
REQUEST_PATH,
message.as_bytes(),
Some(Duration::from_secs(30)),
)
.await?;
println!(
"Response in {:.3} ms: {}",
response.response_time.as_secs_f64() * 1000.0,
String::from_utf8_lossy(&response.data),
);
session.handle.close().await;
runtime.stop().await;
Ok(())
}
+99
View File
@@ -0,0 +1,99 @@
mod support;
use rns_runtime::prelude::*;
use support::*;
const ASPECT: &str = "example_utilities.resourceexample";
#[tokio::main]
async fn main() -> ExampleResult {
let args = ExampleArgs::parse()?;
match args.require(0, "mode: server | client")? {
"server" => server(args).await,
"client" => client(args).await,
other => Err(format!("unknown mode {other}; use server or client").into()),
}
}
async fn server(args: ExampleArgs) -> ExampleResult {
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let mut destination = register_single(
&runtime.handle,
Identity::new(),
ASPECT,
DestinationRuntimeOptions {
resource_strategy: ResourceStrategy::AcceptAll,
..DestinationRuntimeOptions::default()
},
)
.await?;
print_destination(
"Resource destination",
destination.handle.destination_hash(),
);
destination
.handle
.announce(DestinationAnnounceOptions::default())
.await?;
loop {
tokio::select! {
_ = runtime.shutdown.wait() => break,
completed = destination.events.resource_completions.recv() => {
let Some(completed) = completed else { break };
println!(
"Received {} bytes on {} as {}",
completed.data.len(),
hex::encode(completed.link_id),
hex::encode(completed.resource_hash),
);
}
}
}
destination.close().await?;
runtime.stop().await;
Ok(())
}
async fn client(args: ExampleArgs) -> ExampleResult {
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
let message = args
.positional
.get(2)
.map_or("Hello Resource", String::as_str);
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let session = connect(&runtime.handle, destination_hash, false, "resource-example").await?;
let transfer = session
.handle
.send_resource_bytes(
message.as_bytes().to_vec(),
ResourceOptions {
auto_compress: true,
metadata: None,
},
)
.await?;
let mut progress = transfer.progress();
let concluded = transfer.concluded();
tokio::pin!(concluded);
let receipt = loop {
tokio::select! {
result = &mut concluded => break result?,
changed = progress.changed() => {
changed?;
println!("Progress: {:.1}%", *progress.borrow() * 100.0);
}
}
};
println!(
"Resource {} completed ({} bytes)",
hex::encode(receipt.resource_id),
receipt.data_size,
);
session.handle.close().await;
runtime.stop().await;
Ok(())
}
+99
View File
@@ -0,0 +1,99 @@
mod support;
use std::time::Instant;
use rns_runtime::prelude::*;
use support::*;
const ASPECT: &str = "example_utilities.speedtest";
const DEFAULT_BYTES: usize = 2 * 1024 * 1024;
#[tokio::main]
async fn main() -> ExampleResult {
let args = ExampleArgs::parse()?;
match args.require(0, "mode: server | client")? {
"server" => server(args).await,
"client" => client(args).await,
other => Err(format!("unknown mode {other}; use server or client").into()),
}
}
async fn server(args: ExampleArgs) -> ExampleResult {
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let mut destination = register_single(
&runtime.handle,
Identity::new(),
ASPECT,
DestinationRuntimeOptions::default(),
)
.await?;
print_destination(
"Speed-test destination",
destination.handle.destination_hash(),
);
destination
.handle
.announce(DestinationAnnounceOptions::default())
.await?;
let mut total = 0usize;
let started = Instant::now();
loop {
tokio::select! {
_ = runtime.shutdown.wait() => break,
packet = destination.events.link_packets.recv() => {
let Some((data, _)) = packet else { break };
total = total.saturating_add(data.len());
if total >= DEFAULT_BYTES {
let elapsed = started.elapsed().as_secs_f64();
println!(
"Received {total} bytes at {:.2} Mbit/s",
(total as f64 * 8.0) / elapsed / 1_000_000.0,
);
total = 0;
}
}
}
}
destination.close().await?;
runtime.stop().await;
Ok(())
}
async fn client(args: ExampleArgs) -> ExampleResult {
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
let total_bytes = args
.positional
.get(2)
.map(|value| value.parse::<usize>())
.transpose()?
.unwrap_or(DEFAULT_BYTES);
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
let session = connect(
&runtime.handle,
destination_hash,
false,
"speedtest-example",
)
.await?;
let chunk = vec![0xAA; session.handle.mdu()];
let started = Instant::now();
let mut sent = 0usize;
while sent < total_bytes {
let count = (total_bytes - sent).min(chunk.len());
session.handle.send_packet(chunk[..count].to_vec()).await?;
sent += count;
}
let elapsed = started.elapsed().as_secs_f64();
println!(
"Queued {sent} bytes in {:.3}s ({:.2} Mbit/s)",
elapsed,
(sent as f64 * 8.0) / elapsed / 1_000_000.0,
);
session.handle.close().await;
runtime.stop().await;
Ok(())
}
+137
View File
@@ -0,0 +1,137 @@
#![allow(dead_code)]
use std::error::Error;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::time::Duration;
use rns_runtime::lifecycle::install_signal_handlers;
use rns_runtime::prelude::*;
pub type ExampleResult<T = ()> = Result<T, Box<dyn Error + Send + Sync>>;
pub struct ExampleArgs {
pub config_dir: Option<String>,
pub positional: Vec<String>,
}
impl ExampleArgs {
pub fn parse() -> ExampleResult<Self> {
let mut config_dir = None;
let mut positional = Vec::new();
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
if arg == "--config" {
config_dir = Some(args.next().ok_or("--config requires a directory")?);
} else {
positional.push(arg);
}
}
Ok(Self {
config_dir,
positional,
})
}
pub fn require(&self, index: usize, label: &str) -> ExampleResult<&str> {
self.positional
.get(index)
.map(String::as_str)
.ok_or_else(|| format!("missing {label}").into())
}
}
pub struct ExampleRuntime {
pub handle: ReticulumHandle,
pub shutdown: ShutdownSignal,
}
impl ExampleRuntime {
pub async fn start(config_dir: Option<&str>) -> ExampleResult<Self> {
let shutdown = ShutdownSignal::new();
let _signals = install_signal_handlers(shutdown.clone());
let handle = init(
config_dir,
None,
shutdown.clone(),
Arc::new(AtomicBool::new(true)),
)
.await?;
Ok(Self { handle, shutdown })
}
pub async fn stop(&self) {
self.handle.shutdown_and_wait().await;
}
}
pub fn parse_destination_hash(value: &str) -> ExampleResult<[u8; 16]> {
let bytes = hex::decode(value)?;
bytes
.try_into()
.map_err(|_| "destination hash must contain exactly 32 hexadecimal characters".into())
}
pub async fn recall_outbound_destination(
runtime: &ReticulumHandle,
destination_hash: [u8; 16],
app_name: &str,
) -> ExampleResult<Destination> {
let recalled = match runtime.recall(destination_hash).await? {
Some(recalled) => recalled,
None => {
runtime
.await_path(destination_hash, Duration::from_secs(15))
.await?;
runtime
.recall(destination_hash)
.await?
.ok_or("destination identity was not learned from its announce")?
}
};
let destination = Destination::new(
Some(&recalled.identity),
Direction::Out,
DestType::Single,
app_name,
)?;
if destination.hash != destination_hash {
return Err(format!(
"destination {} does not match application aspect {app_name}",
hex::encode(destination_hash)
)
.into());
}
Ok(destination)
}
pub async fn connect(
runtime: &ReticulumHandle,
destination_hash: [u8; 16],
identify: bool,
label: &str,
) -> ExampleResult<LinkSession> {
let options = LinkConnectOptions {
identify,
client_label: label.to_string(),
..LinkConnectOptions::default()
};
Ok(runtime
.connect_link(destination_hash, Identity::new(), options)
.await?)
}
pub async fn register_single(
runtime: &ReticulumHandle,
identity: Identity,
app_name: &str,
options: DestinationRuntimeOptions,
) -> ExampleResult<RegisteredDestination> {
Ok(runtime
.register_destination(identity, app_name.to_string(), options)
.await?)
}
pub fn print_destination(label: &str, hash: [u8; 16]) {
println!("{label}: {}", hex::encode(hash));
}
+633
View File
@@ -0,0 +1,633 @@
//! Async byte streams carried by a reliable Reticulum Link channel.
//!
//! The protocol framing and compression live in `rns-protocol`; this module
//! wires them to the actor-owned [`LinkSessionChannelHandle`] and presents
//! Tokio [`AsyncRead`] / [`AsyncWrite`] implementations.
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::sync::{Arc, Mutex, Weak};
use std::task::{Context, Poll, Waker};
use std::time::Duration;
use rns_protocol::buffer::{MAX_CHUNK_LEN, StreamReader, StreamWriter};
use rns_protocol::channel::ChannelError;
use rns_protocol::channel_message::{MessageBase, SMT_STREAM_DATA};
use rns_protocol::stream_data::{STREAM_ID_MAX, StreamDataMessage};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use crate::link_session::{LinkSessionChannelError, LinkSessionChannelHandle};
/// Maximum unread data retained by the default channel Buffer reader.
pub const DEFAULT_READER_CAPACITY: usize = 1024 * 1024;
/// Maximum time an orderly writer shutdown waits for channel headroom.
pub const DEFAULT_CLOSE_TIMEOUT: Duration = Duration::from_secs(15);
const CHANNEL_RETRY_INTERVAL: Duration = Duration::from_millis(10);
const STREAM_HEADER_LEN: usize = 2;
type IoFuture = Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'static>>;
#[derive(Debug, thiserror::Error)]
pub enum LinkSessionBufferError {
#[error("stream id {0} exceeds the 14-bit Buffer stream-id range")]
InvalidStreamId(u16),
#[error("reader capacity must be greater than zero")]
InvalidReaderCapacity,
#[error("channel MDU {0} is too small for a Buffer frame")]
ChannelMduTooSmall(usize),
#[error(transparent)]
Channel(#[from] LinkSessionChannelError),
}
#[derive(Debug, Clone, Copy)]
enum ReaderFailure {
InvalidFrame,
CapacityExceeded,
}
impl ReaderFailure {
fn into_io_error(self) -> io::Error {
match self {
Self::InvalidFrame => {
io::Error::new(io::ErrorKind::InvalidData, "invalid channel Buffer frame")
}
Self::CapacityExceeded => io::Error::new(
io::ErrorKind::OutOfMemory,
"channel Buffer reader capacity exceeded",
),
}
}
}
struct ReaderState {
stream_id: u16,
reader: StreamReader,
capacity: usize,
failure: Option<ReaderFailure>,
closed: bool,
waker: Option<Waker>,
}
impl ReaderState {
fn wake(&mut self) -> Option<Waker> {
self.waker.take()
}
fn remember_waker(&mut self, waker: &Waker) {
if self
.waker
.as_ref()
.is_none_or(|current| !current.will_wake(waker))
{
self.waker = Some(waker.clone());
}
}
}
/// Read half of a channel-backed Reticulum Buffer stream.
///
/// Dropping the reader performs best-effort handler deregistration. Call
/// [`Self::close`] when deterministic deregistration is required.
pub struct LinkSessionBufferReader {
channel: LinkSessionChannelHandle,
handler_id: Option<rns_protocol::channel::HandlerId>,
state: Arc<Mutex<ReaderState>>,
}
impl LinkSessionBufferReader {
pub fn stream_id(&self) -> u16 {
self.state.lock().map(|state| state.stream_id).unwrap_or(0)
}
pub fn available(&self) -> usize {
self.state
.lock()
.map(|state| state.reader.available())
.unwrap_or(0)
}
pub fn is_eof(&self) -> bool {
self.state
.lock()
.map(|state| state.reader.is_eof() || state.closed)
.unwrap_or(true)
}
pub async fn close(&mut self) -> Result<(), LinkSessionBufferError> {
mark_reader_closed(&self.state);
if let Some(handler_id) = self.handler_id.take() {
let _ = self.channel.remove_message_handler(handler_id).await?;
}
Ok(())
}
}
impl AsyncRead for LinkSessionBufferReader {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buffer: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let mut state = match self.state.lock() {
Ok(state) => state,
Err(_) => {
return Poll::Ready(Err(io::Error::other(
"channel Buffer reader state is poisoned",
)));
}
};
if let Some(failure) = state.failure {
return Poll::Ready(Err(failure.into_io_error()));
}
if buffer.remaining() == 0 {
return Poll::Ready(Ok(()));
}
if let Some(data) = state.reader.read(buffer.remaining()) {
buffer.put_slice(&data);
return Poll::Ready(Ok(()));
}
if state.closed || state.reader.is_done() {
return Poll::Ready(Ok(()));
}
state.remember_waker(cx.waker());
Poll::Pending
}
}
impl Drop for LinkSessionBufferReader {
fn drop(&mut self) {
mark_reader_closed(&self.state);
if let Some(handler_id) = self.handler_id.take() {
self.channel.try_remove_message_handler(handler_id);
}
}
}
enum WriterState {
Open,
Sending { accepted: usize, future: IoFuture },
Closing { future: IoFuture },
Closed,
Failed(String),
}
/// Write half of a channel-backed Reticulum Buffer stream.
///
/// Writes are split and compressed by the protocol layer. Shutdown queues EOF
/// only after all earlier writer frames have entered the reliable channel
/// sequence and the channel has headroom for EOF.
pub struct LinkSessionBufferWriter {
channel: LinkSessionChannelHandle,
writer: StreamWriter,
state: WriterState,
close_timeout: Duration,
}
impl LinkSessionBufferWriter {
pub fn with_close_timeout(mut self, timeout: Duration) -> Self {
self.close_timeout = timeout;
self
}
pub fn is_closed(&self) -> bool {
matches!(self.state, WriterState::Closed)
}
fn start_write(&mut self, data: &[u8]) -> io::Result<usize> {
let accepted = data.len().min(MAX_CHUNK_LEN);
let messages = self
.writer
.write(&data[..accepted])
.map_err(io::Error::other)?;
self.state = WriterState::Sending {
accepted,
future: send_messages(self.channel.clone(), messages),
};
Ok(accepted)
}
}
impl AsyncWrite for LinkSessionBufferWriter {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buffer: &[u8],
) -> Poll<io::Result<usize>> {
let this = self.get_mut();
loop {
match &mut this.state {
WriterState::Open => {
if buffer.is_empty() {
return Poll::Ready(Ok(0));
}
if let Err(error) = this.start_write(buffer) {
return Poll::Ready(Err(error));
}
}
WriterState::Sending { accepted, future } => {
let accepted = *accepted;
match future.as_mut().poll(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Ok(())) => {
this.state = WriterState::Open;
return Poll::Ready(Ok(accepted));
}
Poll::Ready(Err(error)) => {
let message = error.to_string();
this.state = WriterState::Failed(message);
return Poll::Ready(Err(error));
}
}
}
WriterState::Closing { .. } | WriterState::Closed => {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::BrokenPipe,
"channel Buffer writer is closed",
)));
}
WriterState::Failed(message) => {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::BrokenPipe,
message.clone(),
)));
}
}
}
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let this = self.get_mut();
loop {
match &mut this.state {
WriterState::Sending { future, .. } => match future.as_mut().poll(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Ok(())) => this.state = WriterState::Open,
Poll::Ready(Err(error)) => {
let message = error.to_string();
this.state = WriterState::Failed(message);
return Poll::Ready(Err(error));
}
},
WriterState::Open | WriterState::Closed => return Poll::Ready(Ok(())),
WriterState::Closing { future } => match future.as_mut().poll(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Ok(())) => {
this.state = WriterState::Closed;
return Poll::Ready(Ok(()));
}
Poll::Ready(Err(error)) => {
let message = error.to_string();
this.state = WriterState::Failed(message);
return Poll::Ready(Err(error));
}
},
WriterState::Failed(message) => {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::BrokenPipe,
message.clone(),
)));
}
}
}
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let this = self.get_mut();
loop {
match &mut this.state {
WriterState::Sending { future, .. } => match future.as_mut().poll(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Ok(())) => this.state = WriterState::Open,
Poll::Ready(Err(error)) => {
let message = error.to_string();
this.state = WriterState::Failed(message);
return Poll::Ready(Err(error));
}
},
WriterState::Open => {
let eof = this.writer.close_simple();
this.state = WriterState::Closing {
future: drain_then_send_eof(this.channel.clone(), eof, this.close_timeout),
};
}
WriterState::Closing { future } => match future.as_mut().poll(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Ok(())) => {
this.state = WriterState::Closed;
return Poll::Ready(Ok(()));
}
Poll::Ready(Err(error)) => {
let message = error.to_string();
this.state = WriterState::Failed(message);
return Poll::Ready(Err(error));
}
},
WriterState::Closed => return Poll::Ready(Ok(())),
WriterState::Failed(message) => {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::BrokenPipe,
message.clone(),
)));
}
}
}
}
}
/// Bidirectional channel Buffer with independent receive and send stream IDs.
pub struct LinkSessionBuffer {
reader: LinkSessionBufferReader,
writer: LinkSessionBufferWriter,
}
impl LinkSessionBuffer {
pub fn reader(&self) -> &LinkSessionBufferReader {
&self.reader
}
pub fn writer(&self) -> &LinkSessionBufferWriter {
&self.writer
}
pub async fn close_reader(&mut self) -> Result<(), LinkSessionBufferError> {
self.reader.close().await
}
pub fn into_split(self) -> (LinkSessionBufferReader, LinkSessionBufferWriter) {
(self.reader, self.writer)
}
}
impl AsyncRead for LinkSessionBuffer {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buffer: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
Pin::new(&mut self.get_mut().reader).poll_read(cx, buffer)
}
}
impl AsyncWrite for LinkSessionBuffer {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buffer: &[u8],
) -> Poll<io::Result<usize>> {
Pin::new(&mut self.get_mut().writer).poll_write(cx, buffer)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.get_mut().writer).poll_flush(cx)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.get_mut().writer).poll_shutdown(cx)
}
}
impl LinkSessionChannelHandle {
pub async fn create_reader(
&self,
stream_id: u16,
) -> Result<LinkSessionBufferReader, LinkSessionBufferError> {
self.create_reader_with_capacity(stream_id, DEFAULT_READER_CAPACITY)
.await
}
pub async fn create_reader_with_capacity(
&self,
stream_id: u16,
capacity: usize,
) -> Result<LinkSessionBufferReader, LinkSessionBufferError> {
validate_stream_id(stream_id)?;
if capacity == 0 {
return Err(LinkSessionBufferError::InvalidReaderCapacity);
}
self.register_system_type(SMT_STREAM_DATA).await?;
let state = Arc::new(Mutex::new(ReaderState {
stream_id,
reader: StreamReader::new(stream_id),
capacity,
failure: None,
closed: false,
waker: None,
}));
let weak_state = Arc::downgrade(&state);
let handler_id = self
.add_message_handler(move |msg_type, payload| {
handle_stream_message(&weak_state, stream_id, msg_type, payload)
})
.await?;
Ok(LinkSessionBufferReader {
channel: self.clone(),
handler_id: Some(handler_id),
state,
})
}
pub fn create_writer(
&self,
stream_id: u16,
) -> Result<LinkSessionBufferWriter, LinkSessionBufferError> {
validate_stream_id(stream_id)?;
let max_data_len = self.mdu().saturating_sub(STREAM_HEADER_LEN);
if max_data_len == 0 {
return Err(LinkSessionBufferError::ChannelMduTooSmall(self.mdu()));
}
Ok(LinkSessionBufferWriter {
channel: self.clone(),
writer: StreamWriter::new(stream_id, max_data_len),
state: WriterState::Open,
close_timeout: DEFAULT_CLOSE_TIMEOUT,
})
}
pub async fn create_bidirectional_buffer(
&self,
receive_stream_id: u16,
send_stream_id: u16,
) -> Result<LinkSessionBuffer, LinkSessionBufferError> {
validate_stream_id(receive_stream_id)?;
validate_stream_id(send_stream_id)?;
let reader = self.create_reader(receive_stream_id).await?;
let writer = self.create_writer(send_stream_id)?;
Ok(LinkSessionBuffer { reader, writer })
}
}
fn validate_stream_id(stream_id: u16) -> Result<(), LinkSessionBufferError> {
if stream_id > STREAM_ID_MAX {
return Err(LinkSessionBufferError::InvalidStreamId(stream_id));
}
Ok(())
}
fn mark_reader_closed(state: &Arc<Mutex<ReaderState>>) {
let wake = state.lock().ok().and_then(|mut state| {
state.closed = true;
state.wake()
});
if let Some(waker) = wake {
waker.wake();
}
}
fn handle_stream_message(
weak_state: &Weak<Mutex<ReaderState>>,
stream_id: u16,
msg_type: u16,
payload: &[u8],
) -> bool {
if msg_type != SMT_STREAM_DATA || payload.len() < STREAM_HEADER_LEN {
return false;
}
let encoded_stream_id = u16::from_be_bytes([payload[0], payload[1]]) & STREAM_ID_MAX;
if encoded_stream_id != stream_id {
return false;
}
let Some(state) = weak_state.upgrade() else {
return false;
};
let mut message = StreamDataMessage::new(0, Vec::new(), false);
let decoded = message.unpack(payload);
let wake = match state.lock() {
Ok(mut state) => {
if state.closed {
return false;
}
if state.failure.is_some() {
return true;
} else if decoded.is_err() {
state.failure = Some(ReaderFailure::InvalidFrame);
} else if message.data.len() > state.capacity.saturating_sub(state.reader.available()) {
state.failure = Some(ReaderFailure::CapacityExceeded);
} else {
state.reader.feed(&message);
}
state.wake()
}
Err(_) => return true,
};
if let Some(waker) = wake {
waker.wake();
}
true
}
fn send_messages(channel: LinkSessionChannelHandle, messages: Vec<StreamDataMessage>) -> IoFuture {
Box::pin(async move {
for message in messages {
let msg_type = message.msg_type();
let payload = message.pack();
loop {
match channel.send_raw(msg_type, payload.clone()).await {
Ok(_) => break,
Err(LinkSessionChannelError::Channel(ChannelError::NotReady)) => {
tokio::time::sleep(CHANNEL_RETRY_INTERVAL).await;
}
Err(error) => return Err(io::Error::other(error)),
}
}
}
Ok(())
})
}
fn drain_then_send_eof(
channel: LinkSessionChannelHandle,
eof: StreamDataMessage,
close_timeout: Duration,
) -> IoFuture {
Box::pin(async move {
tokio::time::timeout(close_timeout, send_messages(channel, vec![eof]))
.await
.map_err(|_| {
io::Error::new(
io::ErrorKind::TimedOut,
"timed out draining channel Buffer writer",
)
})?
})
}
#[cfg(test)]
mod tests {
use super::*;
fn reader_state(stream_id: u16, capacity: usize) -> Arc<Mutex<ReaderState>> {
Arc::new(Mutex::new(ReaderState {
stream_id,
reader: StreamReader::new(stream_id),
capacity,
failure: None,
closed: false,
waker: None,
}))
}
#[test]
fn handler_routes_only_the_matching_stream() {
let state = reader_state(7, 128);
let weak = Arc::downgrade(&state);
let wrong = StreamDataMessage::new(8, b"wrong".to_vec(), false).pack();
assert!(!handle_stream_message(&weak, 7, SMT_STREAM_DATA, &wrong));
assert_eq!(state.lock().unwrap().reader.available(), 0);
let matching = StreamDataMessage::new(7, b"hello".to_vec(), true).pack();
assert!(handle_stream_message(&weak, 7, SMT_STREAM_DATA, &matching));
let mut state = state.lock().unwrap();
assert_eq!(state.reader.read_all().unwrap(), b"hello");
assert!(state.reader.is_done());
}
#[test]
fn handler_fails_closed_at_reader_capacity() {
let state = reader_state(1, 4);
let weak = Arc::downgrade(&state);
let oversized = StreamDataMessage::new(1, b"12345".to_vec(), false).pack();
assert!(handle_stream_message(&weak, 1, SMT_STREAM_DATA, &oversized));
let state = state.lock().unwrap();
assert!(matches!(
state.failure,
Some(ReaderFailure::CapacityExceeded)
));
assert_eq!(state.reader.available(), 0);
}
#[test]
fn handler_reports_invalid_compressed_payload() {
let state = reader_state(2, 128);
let weak = Arc::downgrade(&state);
let mut malformed = (0x4000_u16 | 2).to_be_bytes().to_vec();
malformed.extend_from_slice(b"not bzip2");
assert!(handle_stream_message(&weak, 2, SMT_STREAM_DATA, &malformed));
assert!(matches!(
state.lock().unwrap().failure,
Some(ReaderFailure::InvalidFrame)
));
}
#[test]
fn validates_the_full_stream_id_range() {
assert!(validate_stream_id(STREAM_ID_MAX).is_ok());
assert!(matches!(
validate_stream_id(STREAM_ID_MAX + 1),
Err(LinkSessionBufferError::InvalidStreamId(_))
));
}
}
@@ -0,0 +1,372 @@
//! Deadline-aware, handler-free destination identity resolution.
//!
//! Python applications resolve finite destinations through validated identity
//! recall and path requests. They do not install temporary announce handlers.
use std::time::Duration;
use rns_transport::messages::{
RecalledDestinationRpcEntry, TransportMessage, TransportQuery, TransportQueryResponse,
};
use tokio::sync::{mpsc, oneshot};
use tokio::time::{Instant, sleep_until, timeout_at};
const RECALL_POLL_INTERVAL: Duration = Duration::from_millis(50);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DestinationResolveOptions {
/// Complete command admission, path request and recall before this budget.
pub timeout: Duration,
/// Remove an existing route before requesting a fresh path response when
/// the validated identity is not already cached.
pub drop_existing_path: bool,
/// Request a path refresh even when validated identity data is cached.
/// The cached identity remains immediately usable, matching upstream
/// applications that refresh routing separately from identity recall.
pub refresh_cached_path: bool,
}
impl DestinationResolveOptions {
pub fn new(timeout: Duration) -> Self {
Self {
timeout,
drop_existing_path: false,
refresh_cached_path: false,
}
}
}
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum DestinationResolveError {
#[error("destination resolution timed out")]
Timeout,
#[error("Reticulum transport is unavailable")]
TransportUnavailable,
#[error("Reticulum transport returned an unexpected response during {0}")]
UnexpectedResponse(&'static str),
}
/// Resolve one validated destination without installing an announce handler.
///
/// A missing identity always emits an explicit path request. This deliberately
/// covers the state where a route exists but its validated announce metadata
/// is absent: `AwaitPath` alone would return immediately and never repair the
/// identity cache.
pub async fn resolve_destination_on_transport(
transport_tx: &mpsc::Sender<TransportMessage>,
destination_hash: [u8; 16],
options: DestinationResolveOptions,
) -> Result<RecalledDestinationRpcEntry, DestinationResolveError> {
let deadline = Instant::now()
.checked_add(options.timeout)
.ok_or(DestinationResolveError::Timeout)?;
if let Some(recalled) = recall_destination(transport_tx, destination_hash, deadline).await? {
if options.refresh_cached_path {
send_before_deadline(
transport_tx,
TransportMessage::RequestPath { destination_hash },
deadline,
)
.await?;
}
return Ok(recalled);
}
if options.drop_existing_path {
match query_before_deadline(
transport_tx,
TransportQuery::DropPath {
dest: destination_hash,
},
deadline,
)
.await?
{
TransportQueryResponse::Ok => {}
_ => return Err(DestinationResolveError::UnexpectedResponse("path drop")),
}
}
send_before_deadline(
transport_tx,
TransportMessage::RequestPath { destination_hash },
deadline,
)
.await?;
loop {
if let Some(recalled) = recall_destination(transport_tx, destination_hash, deadline).await?
{
return Ok(recalled);
}
let now = Instant::now();
if now >= deadline {
return Err(DestinationResolveError::Timeout);
}
sleep_until(std::cmp::min(deadline, now + RECALL_POLL_INTERVAL)).await;
}
}
async fn recall_destination(
transport_tx: &mpsc::Sender<TransportMessage>,
destination_hash: [u8; 16],
deadline: Instant,
) -> Result<Option<RecalledDestinationRpcEntry>, DestinationResolveError> {
match query_before_deadline(
transport_tx,
TransportQuery::RecallDestination {
dest: destination_hash,
},
deadline,
)
.await?
{
TransportQueryResponse::RecalledDestination(Some(recalled))
if recalled.dest_hash != destination_hash =>
{
Err(DestinationResolveError::UnexpectedResponse(
"destination recall",
))
}
TransportQueryResponse::RecalledDestination(recalled) => Ok(recalled),
_ => Err(DestinationResolveError::UnexpectedResponse(
"destination recall",
)),
}
}
async fn query_before_deadline(
transport_tx: &mpsc::Sender<TransportMessage>,
query: TransportQuery,
deadline: Instant,
) -> Result<TransportQueryResponse, DestinationResolveError> {
let (response_tx, response_rx) = oneshot::channel();
send_before_deadline(
transport_tx,
TransportMessage::Rpc { query, response_tx },
deadline,
)
.await?;
timeout_at(deadline, response_rx)
.await
.map_err(|_| DestinationResolveError::Timeout)?
.map_err(|_| DestinationResolveError::TransportUnavailable)
}
async fn send_before_deadline(
transport_tx: &mpsc::Sender<TransportMessage>,
message: TransportMessage,
deadline: Instant,
) -> Result<(), DestinationResolveError> {
timeout_at(deadline, transport_tx.send(message))
.await
.map_err(|_| DestinationResolveError::Timeout)?
.map_err(|_| DestinationResolveError::TransportUnavailable)
}
#[cfg(test)]
mod tests {
use super::*;
fn recalled(destination_hash: [u8; 16], public_key: [u8; 64]) -> RecalledDestinationRpcEntry {
RecalledDestinationRpcEntry {
dest_hash: destination_hash,
public_key,
app_data: None,
ratchet: None,
hops: 2,
timestamp: 1.0,
}
}
#[tokio::test]
async fn cache_hit_returns_without_network_discovery() {
let destination_hash = [0x11; 16];
let public_key = [0x22; 64];
let (transport_tx, mut transport_rx) = mpsc::channel(4);
let responder = tokio::spawn(async move {
let TransportMessage::Rpc { query, response_tx } = transport_rx.recv().await.unwrap()
else {
panic!("expected destination recall");
};
assert!(
matches!(query, TransportQuery::RecallDestination { dest } if dest == destination_hash)
);
response_tx
.send(TransportQueryResponse::RecalledDestination(Some(recalled(
destination_hash,
public_key,
))))
.unwrap();
assert!(transport_rx.try_recv().is_err());
});
let resolved = resolve_destination_on_transport(
&transport_tx,
destination_hash,
DestinationResolveOptions::new(Duration::from_secs(1)),
)
.await
.unwrap();
assert_eq!(resolved.public_key, public_key);
responder.await.unwrap();
}
#[tokio::test]
async fn missing_identity_requests_path_without_announce_registration() {
let destination_hash = [0x33; 16];
let public_key = [0x44; 64];
let (transport_tx, mut transport_rx) = mpsc::channel(8);
let responder = tokio::spawn(async move {
let mut recalls = 0;
while let Some(message) = transport_rx.recv().await {
match message {
TransportMessage::Rpc { query, response_tx } => {
assert!(
matches!(query, TransportQuery::RecallDestination { dest } if dest == destination_hash)
);
recalls += 1;
let result = if recalls >= 2 {
Some(recalled(destination_hash, public_key))
} else {
None
};
response_tx
.send(TransportQueryResponse::RecalledDestination(result))
.unwrap();
if recalls >= 2 {
break;
}
}
TransportMessage::RequestPath {
destination_hash: dest,
} => {
assert_eq!(dest, destination_hash);
}
other => panic!("unexpected finite discovery message: {other:?}"),
}
}
});
let resolved = resolve_destination_on_transport(
&transport_tx,
destination_hash,
DestinationResolveOptions::new(Duration::from_secs(1)),
)
.await
.unwrap();
assert_eq!(resolved.public_key, public_key);
responder.await.unwrap();
}
#[tokio::test]
async fn cached_identity_can_refresh_path_without_waiting_for_announce() {
let destination_hash = [0x45; 16];
let public_key = [0x46; 64];
let (transport_tx, mut transport_rx) = mpsc::channel(4);
let responder = tokio::spawn(async move {
let TransportMessage::Rpc { query, response_tx } = transport_rx.recv().await.unwrap()
else {
panic!("expected destination recall");
};
assert!(matches!(query, TransportQuery::RecallDestination { .. }));
response_tx
.send(TransportQueryResponse::RecalledDestination(Some(recalled(
destination_hash,
public_key,
))))
.unwrap();
assert!(matches!(
transport_rx.recv().await.unwrap(),
TransportMessage::RequestPath { destination_hash: dest } if dest == destination_hash
));
});
let resolved = resolve_destination_on_transport(
&transport_tx,
destination_hash,
DestinationResolveOptions {
timeout: Duration::from_secs(1),
drop_existing_path: false,
refresh_cached_path: true,
},
)
.await
.unwrap();
assert_eq!(resolved.public_key, public_key);
responder.await.unwrap();
}
#[tokio::test]
async fn telephony_policy_drops_stale_path_before_request() {
let destination_hash = [0x55; 16];
let public_key = [0x66; 64];
let (transport_tx, mut transport_rx) = mpsc::channel(8);
let responder = tokio::spawn(async move {
let TransportMessage::Rpc { query, response_tx } = transport_rx.recv().await.unwrap()
else {
panic!("expected initial recall");
};
assert!(matches!(query, TransportQuery::RecallDestination { .. }));
response_tx
.send(TransportQueryResponse::RecalledDestination(None))
.unwrap();
let TransportMessage::Rpc { query, response_tx } = transport_rx.recv().await.unwrap()
else {
panic!("expected path drop");
};
assert!(matches!(query, TransportQuery::DropPath { dest } if dest == destination_hash));
response_tx.send(TransportQueryResponse::Ok).unwrap();
assert!(matches!(
transport_rx.recv().await.unwrap(),
TransportMessage::RequestPath { destination_hash: dest } if dest == destination_hash
));
let TransportMessage::Rpc { query, response_tx } = transport_rx.recv().await.unwrap()
else {
panic!("expected recall after path request");
};
assert!(matches!(query, TransportQuery::RecallDestination { .. }));
response_tx
.send(TransportQueryResponse::RecalledDestination(Some(recalled(
destination_hash,
public_key,
))))
.unwrap();
});
let resolved = resolve_destination_on_transport(
&transport_tx,
destination_hash,
DestinationResolveOptions {
timeout: Duration::from_secs(1),
drop_existing_path: true,
refresh_cached_path: true,
},
)
.await
.unwrap();
assert_eq!(resolved.public_key, public_key);
responder.await.unwrap();
}
#[tokio::test]
async fn one_deadline_bounds_blocked_command_admission() {
let destination_hash = [0x77; 16];
let (transport_tx, _transport_rx) = mpsc::channel(1);
transport_tx
.send(TransportMessage::RequestPath { destination_hash })
.await
.unwrap();
let error = resolve_destination_on_transport(
&transport_tx,
destination_hash,
DestinationResolveOptions::new(Duration::from_millis(5)),
)
.await
.unwrap_err();
assert_eq!(error, DestinationResolveError::Timeout);
}
}
@@ -0,0 +1,935 @@
//! App-facing ownership for an inbound SINGLE destination.
//!
//! Python binds Destination construction, transport registration, Link
//! handling, and callbacks to process-global state. This facade keeps those
//! responsibilities explicit: one registration owns one responder
//! [`LinkManager`], exposes bounded event receivers, and deregisters when
//! closed.
use rns_identity::destination::{
AllowPolicy, DefaultAppData, DestType, Destination, DestinationError, Direction, ProofStrategy,
};
use rns_identity::identity::Identity;
use rns_link::link::{CloseReason, ResourceStrategy};
use rns_protocol::channel::ChannelError;
use rns_protocol::channel_message::{ChannelMessageError, MessageBase};
use rns_protocol::resource_adv::ResourceAdvertisement;
use rns_transport::messages::TransportMessage;
use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::{mpsc, oneshot};
use crate::link_manager::{
ChannelSendError, ChannelSendReceipt, DestinationAnnounceOptions, DestinationControlError,
DestinationRequest, LinkChannelMessage, LinkManager, LinkManagerCommand, LinkPacketProof,
LinkPacketSendReceipt, LinkPayloadSendReceipt, LinkResourceEvent, LinkResourceProof,
LinkResourceSendReceipt, LinkSendError, RequestOutcome, ResourceCompletion,
};
const DEFAULT_EVENT_CAPACITY: usize = 128;
const COMMAND_CAPACITY: usize = 256;
type ResourceAcceptCallback = dyn Fn([u8; 16], &ResourceAdvertisement) -> bool + Send + Sync;
#[derive(Debug, Clone)]
pub struct DestinationRuntimeOptions {
pub proof_strategy: ProofStrategy,
pub accepts_links: bool,
pub resource_strategy: ResourceStrategy,
pub event_capacity: usize,
/// Announce app data used whenever an announce (including a path
/// response) carries none explicitly.
pub default_app_data: Option<Vec<u8>>,
/// Per-advertisement acceptance policy consulted when
/// `resource_strategy` is `AcceptApp`.
pub resource_accept: Option<ResourceAcceptPolicy>,
/// Synchronous LinkIdentify gate; returning false closes the link.
pub identity_gate: Option<IdentityGatePolicy>,
/// User Channel message types registered before the manager starts.
pub channel_message_types: Vec<u16>,
}
impl Default for DestinationRuntimeOptions {
fn default() -> Self {
Self {
proof_strategy: ProofStrategy::ProveNone,
accepts_links: true,
resource_strategy: ResourceStrategy::AcceptNone,
event_capacity: DEFAULT_EVENT_CAPACITY,
default_app_data: None,
resource_accept: None,
identity_gate: None,
channel_message_types: Vec::new(),
}
}
}
/// Clonable per-advertisement inbound Resource acceptance policy.
#[derive(Clone)]
pub struct ResourceAcceptPolicy(Arc<ResourceAcceptCallback>);
impl ResourceAcceptPolicy {
pub fn new(
policy: impl Fn([u8; 16], &ResourceAdvertisement) -> bool + Send + Sync + 'static,
) -> Self {
Self(Arc::new(policy))
}
}
impl fmt::Debug for ResourceAcceptPolicy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("ResourceAcceptPolicy")
}
}
/// Clonable synchronous LinkIdentify gate, consulted before any later
/// resource advertisement can race the admission decision.
#[derive(Clone)]
pub struct IdentityGatePolicy(Arc<dyn Fn([u8; 16], [u8; 16]) -> bool + Send + Sync>);
impl IdentityGatePolicy {
pub fn new(gate: impl Fn([u8; 16], [u8; 16]) -> bool + Send + Sync + 'static) -> Self {
Self(Arc::new(gate))
}
}
impl fmt::Debug for IdentityGatePolicy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("IdentityGatePolicy")
}
}
/// Persistent forward-secrecy settings for a live inbound destination.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DestinationRatchetOptions {
/// Signed Python-compatible ratchet-ring file.
pub path: PathBuf,
/// Reject packets encrypted only to the base identity key.
pub enforce: bool,
}
impl DestinationRatchetOptions {
/// Use `path` with ratchet enforcement disabled.
pub fn new(path: impl Into<PathBuf>) -> Self {
Self {
path: path.into(),
enforce: false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DestinationPacket {
pub data: Vec<u8>,
pub raw: Vec<u8>,
}
/// Event receivers owned by one registered destination. All are bounded by
/// `event_capacity` except `link_packets`: inbound link data is proved to the
/// peer on receipt, so its local delivery is lossless and must be drained.
pub struct DestinationEvents {
pub packets: mpsc::Receiver<DestinationPacket>,
pub links_established: mpsc::Receiver<[u8; 16]>,
pub links_identified: mpsc::Receiver<([u8; 16], [u8; 16])>,
pub link_packets: mpsc::UnboundedReceiver<(Vec<u8>, [u8; 16])>,
pub link_packet_proofs: mpsc::Receiver<LinkPacketProof>,
pub resource_completions: mpsc::Receiver<ResourceCompletion>,
pub resource_proofs: mpsc::Receiver<LinkResourceProof>,
pub resource_events: mpsc::Receiver<LinkResourceEvent>,
pub channel_messages: mpsc::Receiver<LinkChannelMessage>,
pub links_closed: mpsc::Receiver<[u8; 16]>,
}
#[derive(Debug, thiserror::Error)]
pub enum DestinationRuntimeError {
#[error(transparent)]
Destination(#[from] DestinationError),
#[error(transparent)]
Control(#[from] DestinationControlError),
#[error(transparent)]
LinkSend(#[from] LinkSendError),
#[error(transparent)]
ChannelSend(#[from] ChannelSendError),
#[error(transparent)]
Channel(#[from] ChannelError),
#[error("destination event capacity must be greater than zero")]
InvalidEventCapacity,
#[error("destination manager is no longer available")]
ManagerUnavailable,
}
#[derive(Clone)]
pub struct DestinationHandle {
destination_hash: [u8; 16],
app_name: String,
command_tx: mpsc::Sender<LinkManagerCommand>,
}
impl DestinationHandle {
pub fn destination_hash(&self) -> [u8; 16] {
self.destination_hash
}
pub fn app_name(&self) -> &str {
&self.app_name
}
pub async fn announce(
&self,
options: DestinationAnnounceOptions,
) -> Result<(), DestinationRuntimeError> {
let (result_tx, result_rx) = oneshot::channel();
self.command_tx
.send(LinkManagerCommand::AnnounceWith {
options,
result_tx: Some(result_tx),
})
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
result_rx
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??;
Ok(())
}
pub async fn set_accepts_links(&self, accepts: bool) -> Result<(), DestinationRuntimeError> {
let (result_tx, result_rx) = oneshot::channel();
self.command_tx
.send(LinkManagerCommand::SetAcceptsLinks {
accepts,
result_tx: Some(result_tx),
})
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
result_rx
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??;
Ok(())
}
/// Set or clear the default app data used whenever an announce (including
/// a path response) carries none explicitly.
pub async fn set_default_app_data(
&self,
app_data: Option<Vec<u8>>,
) -> Result<(), DestinationRuntimeError> {
let (result_tx, result_rx) = oneshot::channel();
self.command_tx
.send(LinkManagerCommand::SetDefaultAppData {
app_data,
result_tx: Some(result_tx),
})
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
result_rx
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??;
Ok(())
}
pub async fn register_request_handler<F>(
&self,
path: impl Into<String>,
allow: AllowPolicy,
allowed_list: Vec<[u8; 16]>,
auto_compress: bool,
handler: F,
) -> Result<bool, DestinationRuntimeError>
where
F: Fn(DestinationRequest) -> RequestOutcome + Send + 'static,
{
let (result_tx, result_rx) = oneshot::channel();
self.command_tx
.send(LinkManagerCommand::RegisterRequestHandler {
path: path.into(),
allow,
allowed_list,
auto_compress,
handler: Box::new(handler),
result_tx: Some(result_tx),
})
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
result_rx
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)
}
pub async fn deregister_request_handler(
&self,
path: impl Into<String>,
) -> Result<bool, DestinationRuntimeError> {
let (result_tx, result_rx) = oneshot::channel();
self.command_tx
.send(LinkManagerCommand::DeregisterRequestHandler {
path: path.into(),
result_tx: Some(result_tx),
})
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
result_rx
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)
}
pub async fn send_link_packet(
&self,
link_id: [u8; 16],
payload: impl Into<Vec<u8>>,
) -> Result<LinkPacketSendReceipt, DestinationRuntimeError> {
let (result_tx, result_rx) = oneshot::channel();
self.command_tx
.send(LinkManagerCommand::SendLinkPacket {
link_id,
payload: payload.into(),
result_tx: Some(result_tx),
})
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
Ok(result_rx
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??)
}
pub async fn send_link_resource(
&self,
link_id: [u8; 16],
payload: impl Into<Vec<u8>>,
auto_compress: bool,
) -> Result<LinkResourceSendReceipt, DestinationRuntimeError> {
let (result_tx, result_rx) = oneshot::channel();
self.command_tx
.send(LinkManagerCommand::SendLinkResource {
link_id,
payload: payload.into(),
auto_compress,
result_tx: Some(result_tx),
})
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
Ok(result_rx
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??)
}
pub async fn send_link_payload(
&self,
link_id: [u8; 16],
payload: impl Into<Vec<u8>>,
auto_compress: bool,
) -> Result<LinkPayloadSendReceipt, DestinationRuntimeError> {
let (result_tx, result_rx) = oneshot::channel();
self.command_tx
.send(LinkManagerCommand::SendLinkPayload {
link_id,
payload: payload.into(),
auto_compress,
result_tx: Some(result_tx),
})
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
Ok(result_rx
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??)
}
pub async fn send_channel(
&self,
link_id: [u8; 16],
msg_type: u16,
payload: impl Into<Vec<u8>>,
) -> Result<ChannelSendReceipt, DestinationRuntimeError> {
let (result_tx, result_rx) = oneshot::channel();
self.command_tx
.send(LinkManagerCommand::SendChannelMessage {
link_id,
message: Box::new(RawChannelMessage {
msg_type,
payload: payload.into(),
}),
result_tx: Some(result_tx),
})
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
Ok(result_rx
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??)
}
pub async fn close_link(
&self,
link_id: [u8; 16],
reason: CloseReason,
send_teardown: bool,
) -> Result<(), DestinationRuntimeError> {
self.command_tx
.send(LinkManagerCommand::CloseLink {
link_id,
reason,
send_teardown,
})
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)
}
pub async fn shutdown(&self) -> Result<(), DestinationRuntimeError> {
self.command_tx
.send(LinkManagerCommand::Shutdown)
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)
}
}
/// Owns one live inbound destination and its responder Link manager.
pub struct RegisteredDestination {
pub handle: DestinationHandle,
pub events: DestinationEvents,
stopped_rx: Option<oneshot::Receiver<()>>,
}
impl RegisteredDestination {
pub async fn register(
transport_tx: mpsc::Sender<TransportMessage>,
identity: Identity,
app_name: impl Into<String>,
options: DestinationRuntimeOptions,
) -> Result<Self, DestinationRuntimeError> {
Self::register_inner(transport_tx, identity, app_name, options, None).await
}
/// Register a live destination whose announce rotation and inbound
/// decryption are backed by one verified persistent ratchet ring.
pub async fn register_ratcheted(
transport_tx: mpsc::Sender<TransportMessage>,
identity: Identity,
app_name: impl Into<String>,
options: DestinationRuntimeOptions,
ratchet_options: DestinationRatchetOptions,
) -> Result<Self, DestinationRuntimeError> {
Self::register_inner(
transport_tx,
identity,
app_name,
options,
Some(ratchet_options),
)
.await
}
async fn register_inner(
transport_tx: mpsc::Sender<TransportMessage>,
identity: Identity,
app_name: impl Into<String>,
options: DestinationRuntimeOptions,
ratchet_options: Option<DestinationRatchetOptions>,
) -> Result<Self, DestinationRuntimeError> {
if options.event_capacity == 0 {
return Err(DestinationRuntimeError::InvalidEventCapacity);
}
let app_name = app_name.into();
let destination =
Destination::new(Some(&identity), Direction::In, DestType::Single, &app_name)?;
let destination_hash = destination.hash;
let (delivery_tx, delivery_rx) = mpsc::channel(options.event_capacity);
let mut manager = LinkManager::with_destination(
transport_tx.clone(),
delivery_rx,
&identity,
&app_name,
identity.get_signing_key(),
);
if let Some(ratchet_options) = ratchet_options {
manager.enable_persistent_ratchets(ratchet_options.path, ratchet_options.enforce)?;
}
manager.set_resource_strategy(options.resource_strategy);
manager.set_use_implicit_proof(true);
if let Some(policy) = options.resource_accept.clone() {
manager.set_resource_accept_handler(move |link_id, adv| (policy.0)(link_id, adv));
}
if let Some(gate) = options.identity_gate.clone() {
manager.set_link_identity_gate(move |link_id, identity| (gate.0)(link_id, identity));
}
for msg_type in &options.channel_message_types {
manager.register_channel_message_type(*msg_type)?;
}
let owned_destination = manager
.destination_mut()
.ok_or(DestinationControlError::DestinationUnavailable)?;
owned_destination.set_proof_strategy(options.proof_strategy);
owned_destination.set_accepts_links(options.accepts_links);
if let Some(app_data) = options.default_app_data.clone() {
owned_destination.set_default_app_data(DefaultAppData::Static(app_data));
}
transport_tx
.send(TransportMessage::RegisterDestination {
hash: destination_hash,
app_name: app_name.clone(),
delivery_tx: Some(delivery_tx),
})
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
let capacity = options.event_capacity;
let (packet_tx, packets) = mpsc::channel(capacity);
owned_destination.set_packet_callback(Box::new(move |data, raw| {
let _ = packet_tx.try_send(DestinationPacket {
data: data.to_vec(),
raw: raw.to_vec(),
});
}));
let (links_established_tx, links_established) = mpsc::channel(capacity);
let (links_identified_tx, links_identified) = mpsc::channel(capacity);
let (link_packets_tx, link_packets) = mpsc::unbounded_channel();
let (link_packet_proofs_tx, link_packet_proofs) = mpsc::channel(capacity);
let (resource_completions_tx, resource_completions) = mpsc::channel(capacity);
let (resource_proofs_tx, resource_proofs) = mpsc::channel(capacity);
let (resource_events_tx, resource_events) = mpsc::channel(capacity);
let (channel_messages_tx, channel_messages) = mpsc::channel(capacity);
let (links_closed_tx, links_closed) = mpsc::channel(capacity);
manager.set_link_established_channel(links_established_tx);
manager.set_link_identified_channel(links_identified_tx);
manager.set_link_packet_channel(link_packets_tx);
manager.set_link_packet_proof_channel(link_packet_proofs_tx);
manager.set_resource_completion_channel(resource_completions_tx);
manager.set_outbound_resource_proof_channel(resource_proofs_tx);
manager.set_resource_event_channel(resource_events_tx);
manager.set_channel_message_channel(channel_messages_tx);
manager.set_link_closed_channel(links_closed_tx);
let (command_tx, command_rx) = mpsc::channel(COMMAND_CAPACITY);
let (stopped_tx, stopped_rx) = oneshot::channel();
let manager_transport_tx = transport_tx;
tokio::spawn(async move {
manager.run_with_commands(command_rx).await;
let _ = manager_transport_tx
.send(TransportMessage::DeregisterDestination {
hash: destination_hash,
})
.await;
let _ = stopped_tx.send(());
});
Ok(Self {
handle: DestinationHandle {
destination_hash,
app_name,
command_tx,
},
events: DestinationEvents {
packets,
links_established,
links_identified,
link_packets,
link_packet_proofs,
resource_completions,
resource_proofs,
resource_events,
channel_messages,
links_closed,
},
stopped_rx: Some(stopped_rx),
})
}
pub async fn close(mut self) -> Result<(), DestinationRuntimeError> {
self.handle.shutdown().await?;
if let Some(stopped_rx) = self.stopped_rx.take() {
stopped_rx
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
}
Ok(())
}
}
impl Drop for RegisteredDestination {
fn drop(&mut self) {
let command = LinkManagerCommand::Shutdown;
match self.handle.command_tx.try_send(command) {
Ok(()) | Err(mpsc::error::TrySendError::Closed(_)) => {}
Err(mpsc::error::TrySendError::Full(command)) => {
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
let command_tx = self.handle.command_tx.clone();
runtime.spawn(async move {
let _ = command_tx.send(command).await;
});
}
}
}
}
}
struct RawChannelMessage {
msg_type: u16,
payload: Vec<u8>,
}
impl MessageBase for RawChannelMessage {
fn msg_type(&self) -> u16 {
self.msg_type
}
fn pack(&self) -> Vec<u8> {
self.payload.clone()
}
fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError> {
self.payload = raw.to_vec();
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::link_session::{LinkSession, LinkSessionConfig, LinkSessionEvent};
use rns_protocol::channel_message::SYSTEM_MESSAGE_TYPE_MIN;
use rns_transport::actor::TransportActor;
use rns_transport::messages::TransportMessage;
use std::time::Duration;
#[tokio::test]
async fn register_applies_policy_options_and_rejects_reserved_channel_types() {
let identity = Identity::new();
let (transport_tx, mut transport_rx) = mpsc::channel(16);
let reserved = RegisteredDestination::register(
transport_tx.clone(),
identity.clone(),
"example.runtime.policies",
DestinationRuntimeOptions {
channel_message_types: vec![SYSTEM_MESSAGE_TYPE_MIN],
..DestinationRuntimeOptions::default()
},
)
.await;
assert!(matches!(reserved, Err(DestinationRuntimeError::Channel(_))));
assert!(
transport_rx.try_recv().is_err(),
"a reserved channel type must fail before transport registration"
);
let registration = RegisteredDestination::register(
transport_tx,
identity,
"example.runtime.policies",
DestinationRuntimeOptions {
resource_strategy: ResourceStrategy::AcceptApp,
resource_accept: Some(ResourceAcceptPolicy::new(|_, _| false)),
identity_gate: Some(IdentityGatePolicy::new(|_, _| true)),
channel_message_types: vec![0x0100],
default_app_data: Some(b"policy app data".to_vec()),
..DestinationRuntimeOptions::default()
},
)
.await
.expect("valid policy options must register");
registration.close().await.unwrap();
}
#[tokio::test]
async fn registration_announces_and_deregisters_exact_destination() {
let identity = Identity::new();
let (transport_tx, mut transport_rx) = mpsc::channel(16);
let registration = RegisteredDestination::register(
transport_tx,
identity,
"example.runtime",
DestinationRuntimeOptions::default(),
)
.await
.unwrap();
let destination_hash = registration.handle.destination_hash();
assert!(matches!(
transport_rx.recv().await,
Some(TransportMessage::RegisterDestination { hash, .. }) if hash == destination_hash
));
registration
.handle
.announce(DestinationAnnounceOptions {
app_data: Some(b"hello".to_vec()),
..DestinationAnnounceOptions::default()
})
.await
.unwrap();
assert!(matches!(
transport_rx.recv().await,
Some(TransportMessage::Outbound(_)) | Some(TransportMessage::OutboundAttached { .. })
));
registration.close().await.unwrap();
assert!(matches!(
transport_rx.recv().await,
Some(TransportMessage::DeregisterDestination { hash }) if hash == destination_hash
));
}
#[tokio::test]
async fn link_session_connects_to_destination_on_same_transport_actor() {
let (actor, transport_tx) = TransportActor::new();
let actor_task = tokio::spawn(actor.run());
let server_identity = Identity::new();
let server_public_key = server_identity.get_public_key();
let mut registration = RegisteredDestination::register(
transport_tx.clone(),
server_identity,
"example.runtime.loopback",
DestinationRuntimeOptions::default(),
)
.await
.unwrap();
let destination_hash = registration.handle.destination_hash();
let client_identity = Identity::new();
let expected_client = client_identity.hash;
let mut session = tokio::time::timeout(
Duration::from_secs(3),
LinkSession::connect(
transport_tx.clone(),
client_identity,
LinkSessionConfig {
destination_hash,
remote_public_key: server_public_key,
hops: 1,
establishment_timeout: Duration::from_secs(2),
client_label: "test.same-actor-link".into(),
identify: true,
track_phy_stats: false,
},
),
)
.await
.expect("same-actor Link establishment timed out")
.expect("same-actor Link establishment failed");
let link_id = session.handle.link_id();
assert_eq!(
tokio::time::timeout(
Duration::from_secs(1),
registration.events.links_established.recv()
)
.await
.unwrap(),
Some(link_id)
);
assert_eq!(
tokio::time::timeout(
Duration::from_secs(1),
registration.events.links_identified.recv()
)
.await
.unwrap(),
Some((link_id, expected_client))
);
session
.handle
.send_packet(b"client to server".to_vec())
.await
.unwrap();
assert_eq!(
tokio::time::timeout(
Duration::from_secs(1),
registration.events.link_packets.recv()
)
.await
.unwrap(),
Some((b"client to server".to_vec(), link_id))
);
registration
.handle
.send_link_packet(link_id, b"server to client".to_vec())
.await
.unwrap();
let received = tokio::time::timeout(Duration::from_secs(1), async {
loop {
if let Some(LinkSessionEvent::Packet { data, .. }) = session.events.recv().await {
break data;
}
}
})
.await
.unwrap();
assert_eq!(received, b"server to client");
session.handle.close().await;
registration.close().await.unwrap();
transport_tx.send(TransportMessage::Shutdown).await.unwrap();
actor_task.await.unwrap();
}
#[tokio::test]
async fn ratcheted_registration_advertises_and_decrypts_owned_ring() {
let identity = Identity::new();
let app_name = "example.runtime.ratcheted";
let dir =
std::env::temp_dir().join(format!("reticulum_runtime_ratchets_{}", identity.hexhash()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let ratchet_path = dir.join("ratchets");
let (transport_tx, mut transport_rx) = mpsc::channel(16);
let mut registration = RegisteredDestination::register_ratcheted(
transport_tx,
identity.clone(),
app_name,
DestinationRuntimeOptions::default(),
DestinationRatchetOptions {
path: ratchet_path.clone(),
enforce: true,
},
)
.await
.unwrap();
let destination_hash = registration.handle.destination_hash();
let delivery_tx = match transport_rx.recv().await.unwrap() {
TransportMessage::RegisterDestination {
hash,
delivery_tx: Some(delivery_tx),
..
} => {
assert_eq!(hash, destination_hash);
delivery_tx
}
other => panic!("expected destination registration, got {other:?}"),
};
registration
.handle
.announce(DestinationAnnounceOptions::default())
.await
.unwrap();
let announce_raw = match transport_rx.recv().await.unwrap() {
TransportMessage::Outbound(request) => request.raw,
TransportMessage::OutboundAttached { request, .. } => request.raw,
other => panic!("expected ratcheted announce, got {other:?}"),
};
let (announce_header, _) = rns_wire::header::PacketHeader::unpack(&announce_raw).unwrap();
assert_eq!(
announce_header.flags.packet_type,
rns_wire::flags::PacketType::Announce
);
assert!(announce_header.flags.context_flag);
let ratchet = rns_identity::ratchet::RatchetRing::load_verified(&ratchet_path, &identity)
.unwrap()
.ring()
.current_public_key()
.unwrap();
let mut wrong_ratchet = ratchet;
wrong_ratchet[0] ^= 0xFF;
assert!(matches!(
registration
.handle
.announce(DestinationAnnounceOptions {
ratchet: Some(wrong_ratchet),
..DestinationAnnounceOptions::default()
})
.await,
Err(DestinationRuntimeError::Control(
DestinationControlError::ManagedRatchetMismatch
))
));
assert!(
transport_rx.try_recv().is_err(),
"a mismatched managed ratchet must not be advertised"
);
let public_identity = Identity::from_public_key(&identity.get_public_key()).unwrap();
let mut outbound = Destination::new(
Some(&public_identity),
Direction::Out,
DestType::Single,
app_name,
)
.unwrap();
outbound.set_remote_ratchet(ratchet);
let ciphertext = outbound
.encrypt(
b"forward secret",
&public_identity,
outbound.remote_ratchet_pub.as_ref(),
)
.unwrap();
let packet = rns_wire::packet::Packet::new(
rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Single,
packet_type: rns_wire::flags::PacketType::Data,
},
hops: 0,
transport_id: None,
destination_hash,
context: rns_wire::context::PacketContext::None,
},
ciphertext,
)
.unwrap();
delivery_tx
.send(
rns_transport::link_messages::DestinationEvent::InboundPacket {
raw: bytes::Bytes::from(packet.raw),
interface_id: 1,
metrics: rns_transport::link_messages::PacketMetrics::default(),
},
)
.await
.unwrap();
let delivered = tokio::time::timeout(
std::time::Duration::from_secs(1),
registration.events.packets.recv(),
)
.await
.unwrap()
.unwrap();
assert_eq!(delivered.data, b"forward secret");
registration.close().await.unwrap();
assert!(matches!(
transport_rx.recv().await,
Some(TransportMessage::DeregisterDestination { hash }) if hash == destination_hash
));
std::fs::remove_dir_all(dir).unwrap();
}
#[tokio::test]
async fn failed_ratchet_setup_does_not_leak_transport_registration() {
let identity = Identity::new();
let root = std::env::temp_dir().join(format!(
"reticulum_runtime_missing_ratchets_{}",
identity.hexhash()
));
let _ = std::fs::remove_dir_all(&root);
let ratchet_path = root.join("missing").join("ratchets");
let (transport_tx, mut transport_rx) = mpsc::channel(4);
let result = RegisteredDestination::register_ratcheted(
transport_tx,
identity,
"example.runtime.ratchet-failure",
DestinationRuntimeOptions::default(),
DestinationRatchetOptions::new(ratchet_path),
)
.await;
assert!(matches!(
result,
Err(DestinationRuntimeError::Control(
DestinationControlError::RatchetPersistence(_)
))
));
assert!(
transport_rx.try_recv().is_err(),
"failed local setup must not register a destination with transport"
);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+50
View File
@@ -1,19 +1,69 @@
//! Reticulum runtime: config, lifecycle, RPC, and the [`reticulum::ReticulumHandle`]
//! that user code holds. Python reference: `RNS/Reticulum.py`.
pub mod buffer_stream;
pub mod config;
pub mod constants;
pub mod destination_resolver;
pub mod destination_runtime;
pub mod interface_factory;
mod interface_registry;
pub mod jobs;
pub mod lifecycle;
pub mod link_client;
mod link_endpoint;
pub mod link_manager;
pub mod link_session;
pub mod platform;
pub mod probe;
pub mod remote_management;
pub mod remote_management_schema;
pub mod resource_source;
pub mod reticulum;
pub mod rncp;
pub mod rnsh;
pub mod rpc;
pub mod rpc_server;
/// Common application-facing types for Reticulum programs.
///
/// This is additive convenience; module-qualified paths remain supported.
pub mod prelude {
pub use crate::destination_resolver::{
DestinationResolveError, DestinationResolveOptions, resolve_destination_on_transport,
};
pub use crate::destination_runtime::{
DestinationEvents, DestinationHandle, DestinationPacket, DestinationRatchetOptions,
DestinationRuntimeError, DestinationRuntimeOptions, IdentityGatePolicy,
RegisteredDestination, ResourceAcceptPolicy,
};
pub use crate::lifecycle::ShutdownSignal;
pub use crate::link_manager::{DestinationAnnounceOptions, DestinationRequest, RequestOutcome};
pub use crate::link_session::{
LinkSession, LinkSessionChannelError, LinkSessionChannelHandle, LinkSessionCloseReason,
LinkSessionError, LinkSessionEvent, LinkSessionHandle, LinkSessionResourceError,
LinkSessionResourceOffer, LinkSessionResponse,
};
pub use crate::resource_source::{ResourceOptions, ResourceSource};
pub use crate::reticulum::{
AnnounceSubscription, ControlError, InitOptions, InterfaceStats, LinkConnectError,
LinkConnectOptions, OutboundPacket, PacketReceiptHandle, PacketReceiptStatus,
RNodeReadinessError, RNodeRuntimeLookupError, RNodeRuntimeObserver, RNodeRuntimeSpawnError,
RecalledDestination, ReceiptError, ReticulumError, ReticulumHandle, SendError, SendOptions,
SendResult, SpawnedRNodeRuntime, StartupRNodeRuntime, init, init_with_options,
init_with_options_and_rnode_startup_options,
};
pub use rns_identity::destination::{
AllowPolicy, DestType, Destination, DestinationPacketError, DestinationPacketOptions,
Direction, PackedDestinationPacket, ProofStrategy,
};
pub use rns_identity::identity::Identity;
pub use rns_identity::ratchet::PersistentRatchetRing;
pub use rns_interface::rnode::{
RNodeCapabilityAdmissionError, RNodeCapabilityAdmissionFailureClass, RNodeCapabilityState,
RNodeConfigurationState, RNodeDetectionState, RNodeFirmwareCompatibility,
RNodeObservedRadioState, RNodeRuntimePhase, RNodeRuntimeReason, RNodeRuntimeSnapshot,
RNodeSpawnError, RNodeStartupOptions, RNodeTransmitFlowState, RNodeTransportClass,
};
pub use rns_link::link::{CloseReason, ResourceStrategy};
}
+71 -13
View File
@@ -32,10 +32,15 @@ impl ShutdownSignal {
}
pub async fn wait(&self) {
if self.is_triggered() {
return;
loop {
let notified = self.notify.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if self.is_triggered() {
return;
}
notified.await;
}
self.notify.notified().await;
}
}
@@ -75,23 +80,67 @@ impl Default for ExitHandler {
}
}
/// Install Ctrl-C / SIGTERM handlers that trip `shutdown`. Returned receiver
/// yields once on signal for await-based callers.
/// Install process-signal handlers that trip `shutdown`. On Unix this covers
/// both SIGINT and SIGTERM; other platforms use the runtime's Ctrl-C handler.
/// The returned receiver yields once on the first 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 a signal 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)]
{
let shutdown_clone = shutdown.clone();
let tx_clone = tx.clone();
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_clone, "SIGINT");
});
}
Err(e) => {
tracing::warn!(error = %e, "SIGINT registration failed; falling back to ctrl_c");
spawn_ctrl_c_handler(shutdown.clone(), tx.clone());
}
}
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
Ok(mut sigterm) => {
tokio::spawn(async move {
sigterm.recv().await;
signal_shutdown(shutdown, tx, "SIGTERM");
});
}
Err(e) => {
tracing::warn!(error = %e, "SIGTERM registration failed");
}
}
}
#[cfg(not(unix))]
spawn_ctrl_c_handler(shutdown, 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, "Ctrl-C");
});
}
fn signal_shutdown(shutdown: ShutdownSignal, tx: mpsc::Sender<()>, signal: &'static str) {
tracing::info!(signal, "received shutdown signal");
shutdown.trigger();
let _ = tx.try_send(());
}
#[cfg(test)]
mod tests {
use super::*;
@@ -144,4 +193,13 @@ mod tests {
signal.wait().await;
assert!(signal.is_triggered());
}
#[tokio::test]
async fn test_shutdown_wait_after_trigger() {
let signal = ShutdownSignal::new();
signal.trigger();
tokio::time::timeout(std::time::Duration::from_millis(50), signal.wait())
.await
.expect("pre-triggered shutdown wait must return");
}
}
+173 -139
View File
@@ -17,7 +17,13 @@ use rns_link::link::{CloseReason, Link};
use rns_protocol::resource::{InboundTransfer, TransferAction};
use rns_protocol::resource_adv::ResourceAdvertisement;
use rns_transport::link_messages::DestinationEvent;
use rns_transport::messages::{AnnounceHandlerEvent, OutboundRequest, TransportMessage};
use rns_transport::messages::{
InterfaceId, LinkEndpointLifecycleEvent, LinkEndpointRole, OutboundRequest, TransportMessage,
};
use crate::destination_resolver::{
DestinationResolveError, DestinationResolveOptions, resolve_destination_on_transport,
};
#[derive(Debug, thiserror::Error)]
pub enum LinkClientError {
@@ -45,6 +51,12 @@ pub struct LinkClient {
identity: Arc<Identity>,
}
struct LinkClientEndpoint<'a> {
delivery_rx: &'a mut mpsc::Receiver<DestinationEvent>,
lifecycle_rx: &'a mut mpsc::UnboundedReceiver<LinkEndpointLifecycleEvent>,
attached_interface: InterfaceId,
}
impl LinkClient {
pub fn new(transport_tx: mpsc::Sender<TransportMessage>, identity: Identity) -> Self {
Self {
@@ -70,27 +82,14 @@ impl LinkClient {
let dest_hash =
Destination::hash_from_name_and_identity(app_name, Some(&remote_transport_hash));
// Register the handler before the path request so the answering
// announce (carrying the pubkey) is observed.
let (ann_tx, mut ann_rx) = mpsc::channel::<AnnounceHandlerEvent>(64);
self.send_msg(TransportMessage::RegisterAnnounceHandler {
aspect_filter: Some(app_name.to_string()),
receive_path_responses: true,
callback_tx: ann_tx,
})
.await?;
self.send_msg(TransportMessage::RequestPath {
destination_hash: dest_hash,
})
.await?;
let pubkey = wait_for_pubkey(&mut ann_rx, dest_hash, time_remaining(deadline)?).await?;
let _ = self
.transport_tx
.try_send(TransportMessage::DeregisterAnnounceHandler {
aspect_filter: Some(app_name.to_string()),
});
let pubkey = resolve_destination_on_transport(
&self.transport_tx,
dest_hash,
DestinationResolveOptions::new(time_remaining(deadline)?),
)
.await
.map_err(map_destination_resolve_error)?
.public_key;
let (mut link, request_data) = Link::new_initiator(dest_hash, hops);
let link_id = link.link_id;
@@ -104,6 +103,11 @@ impl LinkClient {
delivery_tx: Some(dest_tx),
})
.await?;
let mut registration = crate::link_endpoint::LinkEndpointCleanupGuard::new(
self.transport_tx.clone(),
link_id,
LinkEndpointRole::Initiator,
);
let req_pkt = build_link_request_packet(dest_hash, &request_data);
self.send_msg(TransportMessage::Outbound(OutboundRequest {
@@ -112,25 +116,51 @@ impl LinkClient {
}))
.await?;
let proof_data = wait_for_proof(&mut dest_rx, link_id, time_remaining(deadline)?).await?;
let identity_ed25519_pub: [u8; 32] = pubkey[32..64].try_into().map_err(|_| {
LinkClientError::ProofInvalid("remote public key is not 64 bytes".into())
})?;
let identity_verify_key = Ed25519PublicKey::from_bytes(&identity_ed25519_pub)
.map_err(|e| LinkClientError::ProofInvalid(format!("verify key: {e}")))?;
let proof = timeout(
time_remaining(deadline)?,
crate::link_endpoint::wait_for_valid_proof(
&mut dest_rx,
&mut link,
&identity_verify_key,
&identity_ed25519_pub,
),
)
.await
.map_err(|_| LinkClientError::Timeout("link proof"))?
.map_err(|error| match error {
crate::link_endpoint::LinkProofWaitError::LinkClosed => {
LinkClientError::HandshakeFailed("link closed".into())
}
crate::link_endpoint::LinkProofWaitError::DeliveryClosed => {
LinkClientError::HandshakeFailed("destination channel closed".into())
}
})?;
let attached_interface = proof.interface_id;
let rtt_data = proof.rtt_data;
let rtt_data = link
.validate_proof(&proof_data, &identity_verify_key, &identity_ed25519_pub)
.map_err(|e| LinkClientError::ProofInvalid(format!("{e:?}")))?;
let mut endpoint_lifecycle_rx = crate::link_endpoint::bind(
&self.transport_tx,
link_id,
attached_interface,
LinkEndpointRole::Initiator,
)
.await
.map_err(|_| LinkClientError::TransportUnavailable)?;
registration.endpoint_bound();
let mut endpoint = LinkClientEndpoint {
delivery_rx: &mut dest_rx,
lifecycle_rx: &mut endpoint_lifecycle_rx,
attached_interface,
};
let rtt_pkt =
build_data_packet(link_id, rns_wire::context::PacketContext::Lrrtt, &rtt_data);
self.send_msg(TransportMessage::Outbound(OutboundRequest {
raw: rtt_pkt,
destination_hash: link_id,
}))
.await?;
self.send_link_packet(link_id, rtt_pkt).await?;
let our_pub = self.identity.get_public_key();
let our_priv = self
@@ -145,11 +175,7 @@ impl LinkClient {
rns_wire::context::PacketContext::LinkIdentify,
&identify_data,
);
self.send_msg(TransportMessage::Outbound(OutboundRequest {
raw: identify_pkt,
destination_hash: link_id,
}))
.await?;
self.send_link_packet(link_id, identify_pkt).await?;
let req_timeout = Duration::from_secs(5);
let (encrypted_req, request_id) = link
@@ -165,15 +191,11 @@ impl LinkClient {
rns_wire::flags::HeaderType::Header1,
);
link.update_pending_request_id(&request_id, packet_request_id);
self.send_msg(TransportMessage::Outbound(OutboundRequest {
raw: request_pkt,
destination_hash: link_id,
}))
.await?;
self.send_link_packet(link_id, request_pkt).await?;
let response = wait_for_response(
&self.transport_tx,
&mut dest_rx,
&mut endpoint,
&mut link,
link_id,
packet_request_id,
@@ -182,10 +204,12 @@ impl LinkClient {
.await;
// Tear down even on failure so the remote doesn't keep link state.
let _ = self.send_close(&mut link).await;
let _ = self
.transport_tx
.try_send(TransportMessage::DeregisterDestination { hash: link_id });
let endpoint_closing = self.send_close(&mut link).await.unwrap_or(false);
if !endpoint_closing {
let _ = registration.cleanup().await;
} else {
registration.disarm();
}
response
}
@@ -197,21 +221,36 @@ impl LinkClient {
.map_err(|_| LinkClientError::TransportUnavailable)
}
async fn send_close(&self, link: &mut Link) -> Result<(), LinkClientError> {
async fn send_link_packet(&self, link_id: [u8; 16], raw: Bytes) -> Result<(), LinkClientError> {
crate::link_endpoint::send(
&self.transport_tx,
link_id,
LinkEndpointRole::Initiator,
raw,
)
.await
.map_err(|_| LinkClientError::TransportUnavailable)
}
async fn send_close(&self, link: &mut Link) -> Result<bool, LinkClientError> {
let link_id = link.link_id;
let Some(teardown_data) = link.teardown(CloseReason::InitiatorClosed) else {
return Ok(());
return Ok(false);
};
let close_pkt = build_data_packet(
link_id,
rns_wire::context::PacketContext::LinkClose,
&teardown_data,
);
self.send_msg(TransportMessage::Outbound(OutboundRequest {
raw: close_pkt,
destination_hash: link_id,
}))
crate::link_endpoint::send_and_unbind(
&self.transport_tx,
link_id,
LinkEndpointRole::Initiator,
close_pkt,
)
.await
.map(|()| true)
.map_err(|_| LinkClientError::TransportUnavailable)
}
}
@@ -224,63 +263,19 @@ fn time_remaining(deadline: Instant) -> Result<Duration, LinkClientError> {
}
}
async fn wait_for_pubkey(
rx: &mut mpsc::Receiver<AnnounceHandlerEvent>,
target_dest_hash: [u8; 16],
deadline: Duration,
) -> Result<[u8; 64], LinkClientError> {
let fut = async {
while let Some(ev) = rx.recv().await {
if ev.destination_hash == target_dest_hash {
if let Some(pk) = ev.public_key {
return Ok(pk);
}
}
fn map_destination_resolve_error(error: DestinationResolveError) -> LinkClientError {
match error {
DestinationResolveError::Timeout => LinkClientError::Timeout("destination resolution"),
DestinationResolveError::TransportUnavailable => LinkClientError::TransportUnavailable,
DestinationResolveError::UnexpectedResponse(operation) => {
LinkClientError::UnexpectedResponse(operation.to_string())
}
Err(LinkClientError::PubkeyNotDiscovered)
};
timeout(deadline, fut)
.await
.map_err(|_| LinkClientError::Timeout("path/announce discovery"))?
}
async fn wait_for_proof(
rx: &mut mpsc::Receiver<DestinationEvent>,
link_id: [u8; 16],
deadline: Duration,
) -> Result<Vec<u8>, LinkClientError> {
let fut = async {
while let Some(ev) = rx.recv().await {
match ev {
DestinationEvent::LinkClosed { link_id: closed_id } if closed_id == link_id => {
return Err(LinkClientError::HandshakeFailed("link closed".into()));
}
DestinationEvent::InboundPacket { raw, .. } => {
let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) {
Ok(h) => h,
Err(_) => continue,
};
let is_proof = header.flags.packet_type == rns_wire::flags::PacketType::Proof
&& header.destination_hash == link_id;
if is_proof && raw.len() > data_offset {
return Ok(raw[data_offset..].to_vec());
}
}
_ => {}
}
}
Err(LinkClientError::HandshakeFailed(
"destination channel closed".into(),
))
};
timeout(deadline, fut)
.await
.map_err(|_| LinkClientError::Timeout("link proof"))?
}
}
async fn wait_for_response(
transport_tx: &mpsc::Sender<TransportMessage>,
rx: &mut mpsc::Receiver<DestinationEvent>,
endpoint: &mut LinkClientEndpoint<'_>,
link: &mut Link,
link_id: [u8; 16],
request_id: [u8; 16],
@@ -289,12 +284,27 @@ async fn wait_for_response(
let fut = async {
let mut inbound_resources: HashMap<[u8; 32], InboundTransfer> = HashMap::new();
while let Some(ev) = rx.recv().await {
loop {
let ev = tokio::select! {
event = endpoint.delivery_rx.recv() => event.ok_or_else(|| LinkClientError::HandshakeFailed(
"destination channel closed".into(),
))?,
terminal = endpoint.lifecycle_rx.recv() => {
return Err(LinkClientError::HandshakeFailed(format!(
"link endpoint terminated: {terminal:?}"
)));
}
};
match ev {
DestinationEvent::LinkClosed { link_id: closed_id } if closed_id == link_id => {
return Err(LinkClientError::HandshakeFailed("link closed".into()));
}
DestinationEvent::InboundPacket { raw, .. } => {
DestinationEvent::InboundPacket {
raw, interface_id, ..
} => {
if interface_id != endpoint.attached_interface {
continue;
}
let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) {
Ok(h) => h,
Err(_) => continue,
@@ -365,7 +375,8 @@ async fn wait_for_response(
rns_wire::context::PacketContext::ResourceReq,
&req,
true,
)?;
)
.await?;
}
inbound_resources.insert(adv.resource_hash, transfer);
@@ -416,7 +427,8 @@ async fn wait_for_response(
context,
&payload,
true,
)?;
)
.await?;
}
if let Some(rh) = completed_rh {
@@ -446,7 +458,7 @@ async fn wait_for_response(
})?
};
send_link_proof(transport_tx, link_id, &proof)?;
send_link_proof(transport_tx, link_id, &proof).await?;
inbound_resources.remove(&rh);
match link.handle_response_plaintext(&assembled) {
Ok((id, response_data)) => {
@@ -479,17 +491,39 @@ async fn wait_for_response(
let Some(transfer) = inbound_resources.get_mut(&rh) else {
continue;
};
if let TransferAction::SendRequest(req) =
transfer.hashmap_update(segment, &hashmap)
{
send_link_data(
transport_tx,
link,
link_id,
rns_wire::context::PacketContext::ResourceReq,
&req,
true,
)?;
match transfer.hashmap_update(segment, &hashmap) {
TransferAction::SendRequest(req) => {
send_link_data(
transport_tx,
link,
link_id,
rns_wire::context::PacketContext::ResourceReq,
&req,
true,
)
.await?;
}
// Empty/invalid HMU cancels the transfer (RESOURCE_RCL, 1.3.9).
TransferAction::SendCancel(cancel_type, resource_hash) => {
let context = match cancel_type {
rns_protocol::resource::CancelType::Icl => {
rns_wire::context::PacketContext::ResourceIcl
}
rns_protocol::resource::CancelType::Rcl => {
rns_wire::context::PacketContext::ResourceRcl
}
};
send_link_data(
transport_tx,
link,
link_id,
context,
&resource_hash,
true,
)
.await?;
}
_ => {}
}
}
rns_wire::context::PacketContext::LinkClose
@@ -505,18 +539,15 @@ async fn wait_for_response(
_ => {}
}
}
Err(LinkClientError::HandshakeFailed(
"destination channel closed".into(),
))
};
timeout(deadline, fut)
.await
.map_err(|_| LinkClientError::Timeout("response"))?
}
fn send_link_data(
async fn send_link_data(
transport_tx: &mpsc::Sender<TransportMessage>,
link: &Link,
link: &mut Link,
link_id: [u8; 16],
context: rns_wire::context::PacketContext,
body: &[u8],
@@ -529,15 +560,12 @@ fn send_link_data(
body.to_vec()
};
let packet = build_data_packet(link_id, context, &payload);
transport_tx
.try_send(TransportMessage::Outbound(OutboundRequest {
raw: packet,
destination_hash: link_id,
}))
crate::link_endpoint::send(transport_tx, link_id, LinkEndpointRole::Initiator, packet)
.await
.map_err(|_| LinkClientError::TransportUnavailable)
}
fn send_link_proof(
async fn send_link_proof(
transport_tx: &mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
proof: &[u8],
@@ -547,11 +575,8 @@ fn send_link_proof(
rns_wire::context::PacketContext::ResourcePrf,
proof,
);
transport_tx
.try_send(TransportMessage::Outbound(OutboundRequest {
raw: packet,
destination_hash: link_id,
}))
crate::link_endpoint::send(transport_tx, link_id, LinkEndpointRole::Initiator, packet)
.await
.map_err(|_| LinkClientError::TransportUnavailable)
}
@@ -668,13 +693,22 @@ mod tests {
let (transport_tx, mut transport_rx) = mpsc::channel(4);
let client = LinkClient::new(transport_tx, Identity::new());
client.send_close(&mut initiator).await.unwrap();
let close = tokio::spawn(async move { client.send_close(&mut initiator).await });
let TransportMessage::Outbound(request) = transport_rx.try_recv().unwrap() else {
let TransportMessage::SendLinkEndpointAndUnbind {
role,
request,
result_tx,
..
} = transport_rx.recv().await.unwrap()
else {
panic!("expected outbound close packet");
};
assert_eq!(role, LinkEndpointRole::Initiator);
let (header, offset) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
assert_eq!(header.context, rns_wire::context::PacketContext::LinkClose);
assert!(responder.receive_teardown(&request.raw[offset..]));
let _ = result_tx.send(rns_transport::messages::LinkEndpointSendResult::Sent);
assert!(close.await.unwrap().unwrap());
}
}
+649
View File
@@ -0,0 +1,649 @@
use bytes::Bytes;
use tokio::sync::{mpsc, oneshot};
use rns_crypto::ed25519::Ed25519PublicKey;
use rns_link::link::Link;
use rns_transport::link_messages::{DestinationEvent, PacketMetrics};
use rns_transport::messages::{
InterfaceId, LinkEndpointBindResult, LinkEndpointBinding, LinkEndpointLifecycleEvent,
LinkEndpointRole, LinkEndpointSendResult, LinkEndpointUnbindResult, OutboundRequest,
TransportMessage,
};
#[derive(Debug, thiserror::Error)]
pub(crate) enum LinkEndpointError {
#[error("transport channel is unavailable")]
TransportUnavailable,
#[error("Link endpoint could not be bound: {0:?}")]
Bind(LinkEndpointBindResult),
#[error("Link endpoint rejected outbound packet: {0:?}")]
Send(LinkEndpointSendResult),
#[error("Link endpoint cleanup was rejected: {0:?}")]
Unbind(LinkEndpointUnbindResult),
}
/// Owns cleanup for a temporary initiator Link destination until ownership is
/// transferred to a long-lived actor or an atomic final send succeeds.
///
/// Cancellation cannot use `try_send`: a full transport ingress queue is a
/// normal transient condition. Drop therefore transfers cleanup to a retained
/// task which waits for admission, verifies typed endpoint ownership, and only
/// then deregisters the temporary destination.
pub(crate) struct LinkEndpointCleanupGuard {
transport_tx: mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
role: LinkEndpointRole,
endpoint_bound: bool,
armed: bool,
}
impl LinkEndpointCleanupGuard {
pub(crate) fn new(
transport_tx: mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
role: LinkEndpointRole,
) -> Self {
Self {
transport_tx,
link_id,
role,
endpoint_bound: false,
armed: true,
}
}
pub(crate) fn endpoint_bound(&mut self) {
self.endpoint_bound = true;
}
pub(crate) fn disarm(&mut self) {
self.armed = false;
}
pub(crate) async fn cleanup(&mut self) -> Result<(), LinkEndpointError> {
cleanup_registered_link(
&self.transport_tx,
self.link_id,
self.role,
self.endpoint_bound,
)
.await?;
self.endpoint_bound = false;
self.armed = false;
Ok(())
}
}
impl Drop for LinkEndpointCleanupGuard {
fn drop(&mut self) {
if !self.armed {
return;
}
let transport_tx = self.transport_tx.clone();
let link_id = self.link_id;
let role = self.role;
let endpoint_bound = self.endpoint_bound;
let Ok(runtime) = tokio::runtime::Handle::try_current() else {
tracing::error!(
link_id = %hex::encode(link_id),
role = ?role,
"cannot retain Link endpoint cleanup without a Tokio runtime"
);
return;
};
runtime.spawn(async move {
if let Err(error) =
cleanup_registered_link(&transport_tx, link_id, role, endpoint_bound).await
{
tracing::error!(
link_id = %hex::encode(link_id),
role = ?role,
error = %error,
"retained Link endpoint cleanup failed"
);
}
});
}
}
pub(crate) struct PendingLinkEndpointSend {
pub(crate) link_id: [u8; 16],
pub(crate) role: LinkEndpointRole,
pub(crate) final_unbind: bool,
pub(crate) result_rx: oneshot::Receiver<LinkEndpointSendResult>,
}
struct AtomicFinalSendGuard {
transport_tx: mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
role: LinkEndpointRole,
result_rx: Option<oneshot::Receiver<LinkEndpointSendResult>>,
}
impl AtomicFinalSendGuard {
async fn result(&mut self) -> Result<LinkEndpointSendResult, LinkEndpointError> {
let result = self
.result_rx
.as_mut()
.expect("atomic final-send result receiver")
.await;
self.result_rx = None;
result.map_err(|_| LinkEndpointError::TransportUnavailable)
}
}
impl Drop for AtomicFinalSendGuard {
fn drop(&mut self) {
let Some(result_rx) = self.result_rx.take() else {
return;
};
let transport_tx = self.transport_tx.clone();
let link_id = self.link_id;
let role = self.role;
let Ok(runtime) = tokio::runtime::Handle::try_current() else {
tracing::error!(
link_id = %hex::encode(link_id),
role = ?role,
"cannot retain atomic Link close result without a Tokio runtime"
);
return;
};
runtime.spawn(async move {
match result_rx.await {
Ok(LinkEndpointSendResult::Sent | LinkEndpointSendResult::Queued { .. }) => {}
Ok(_) | Err(_) => {
let _ = cleanup_registered_link(&transport_tx, link_id, role, true).await;
}
}
});
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LinkProofWaitError {
LinkClosed,
DeliveryClosed,
}
pub(crate) struct ValidatedLinkProof {
pub(crate) rtt_data: Vec<u8>,
pub(crate) interface_id: InterfaceId,
pub(crate) metrics: PacketMetrics,
}
/// Wait for the first cryptographically valid LRPROOF while the Link remains
/// pending. Invalid candidates are unauthenticated input and cannot terminate
/// establishment or select the endpoint interface.
pub(crate) async fn wait_for_valid_proof(
delivery_rx: &mut mpsc::Receiver<DestinationEvent>,
link: &mut Link,
identity_verify_key: &Ed25519PublicKey,
identity_ed25519_pub_bytes: &[u8; 32],
) -> Result<ValidatedLinkProof, LinkProofWaitError> {
let link_id = link.link_id;
while let Some(event) = delivery_rx.recv().await {
match event {
DestinationEvent::LinkClosed { link_id: closed } if closed == link_id => {
return Err(LinkProofWaitError::LinkClosed);
}
DestinationEvent::InboundPacket {
raw,
interface_id,
metrics,
} => {
let Ok((header, data_offset)) = rns_wire::header::PacketHeader::unpack(&raw) else {
continue;
};
if header.destination_hash != link_id
|| header.flags.packet_type != rns_wire::flags::PacketType::Proof
|| raw.len() <= data_offset
{
continue;
}
match link.validate_proof(
&raw[data_offset..],
identity_verify_key,
identity_ed25519_pub_bytes,
) {
Ok(rtt_data) => {
return Ok(ValidatedLinkProof {
rtt_data,
interface_id,
metrics,
});
}
Err(error) => {
tracing::debug!(
link_id = %hex::encode(link_id),
interface_id,
error = ?error,
"ignoring unauthenticated LRPROOF candidate"
);
}
}
}
_ => {}
}
}
Err(LinkProofWaitError::DeliveryClosed)
}
pub(crate) async fn bind(
transport_tx: &mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
interface_id: InterfaceId,
role: LinkEndpointRole,
) -> Result<mpsc::UnboundedReceiver<LinkEndpointLifecycleEvent>, LinkEndpointError> {
let (lifecycle_tx, lifecycle_rx) = mpsc::unbounded_channel();
let (result_tx, result_rx) = oneshot::channel();
transport_tx
.send(TransportMessage::BindLinkEndpoint {
binding: LinkEndpointBinding {
link_id,
interface_id,
role,
},
lifecycle_tx,
result_tx,
})
.await
.map_err(|_| LinkEndpointError::TransportUnavailable)?;
match result_rx
.await
.map_err(|_| LinkEndpointError::TransportUnavailable)?
{
// A successful fresh bind transfers this lifecycle sender into the
// transport actor. `AlreadyBound` retains the original sender, so the
// newly-created receiver would never observe terminal events and must
// fail closed instead of pretending to own the endpoint.
LinkEndpointBindResult::Bound => Ok(lifecycle_rx),
result => Err(LinkEndpointError::Bind(result)),
}
}
pub(crate) async fn send_best_effort(
transport_tx: &mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
role: LinkEndpointRole,
raw: Bytes,
) -> Result<LinkEndpointSendResult, LinkEndpointError> {
let (result_tx, result_rx) = oneshot::channel();
transport_tx
.send(TransportMessage::SendLinkEndpointBestEffort {
link_id,
role,
request: OutboundRequest {
raw,
destination_hash: link_id,
},
result_tx,
})
.await
.map_err(|_| LinkEndpointError::TransportUnavailable)?;
result_rx
.await
.map_err(|_| LinkEndpointError::TransportUnavailable)
}
pub(crate) async fn send_and_unbind(
transport_tx: &mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
role: LinkEndpointRole,
raw: Bytes,
) -> Result<(), LinkEndpointError> {
let (result_tx, result_rx) = oneshot::channel();
transport_tx
.send(TransportMessage::SendLinkEndpointAndUnbind {
link_id,
role,
request: OutboundRequest {
raw,
destination_hash: link_id,
},
result_tx,
})
.await
.map_err(|_| LinkEndpointError::TransportUnavailable)?;
// Once admitted, retain ownership of the typed result across caller
// cancellation. A successful atomic operation owns the final FIFO drain;
// a rejected one falls back to ordered explicit cleanup.
let mut final_send = AtomicFinalSendGuard {
transport_tx: transport_tx.clone(),
link_id,
role,
result_rx: Some(result_rx),
};
match final_send.result().await? {
LinkEndpointSendResult::Sent | LinkEndpointSendResult::Queued { .. } => Ok(()),
result => Err(LinkEndpointError::Send(result)),
}
}
pub(crate) async fn send(
transport_tx: &mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
role: LinkEndpointRole,
raw: Bytes,
) -> Result<(), LinkEndpointError> {
let (result_tx, result_rx) = oneshot::channel();
transport_tx
.send(TransportMessage::SendLinkEndpoint {
link_id,
role,
request: OutboundRequest {
raw,
destination_hash: link_id,
},
result_tx,
})
.await
.map_err(|_| LinkEndpointError::TransportUnavailable)?;
match result_rx
.await
.map_err(|_| LinkEndpointError::TransportUnavailable)?
{
LinkEndpointSendResult::Sent | LinkEndpointSendResult::Queued { .. } => Ok(()),
result => Err(LinkEndpointError::Send(result)),
}
}
pub(crate) async fn unbind(
transport_tx: &mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
role: LinkEndpointRole,
) -> Result<LinkEndpointUnbindResult, LinkEndpointError> {
let (result_tx, result_rx) = oneshot::channel();
transport_tx
.send(TransportMessage::UnbindLinkEndpoint {
link_id,
role,
result_tx,
})
.await
.map_err(|_| LinkEndpointError::TransportUnavailable)?;
result_rx
.await
.map_err(|_| LinkEndpointError::TransportUnavailable)
}
async fn cleanup_registered_link(
transport_tx: &mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
role: LinkEndpointRole,
endpoint_bound: bool,
) -> Result<(), LinkEndpointError> {
if endpoint_bound {
match unbind(transport_tx, link_id, role).await? {
LinkEndpointUnbindResult::Unbound | LinkEndpointUnbindResult::NotBound => {}
result @ LinkEndpointUnbindResult::RoleMismatch => {
return Err(LinkEndpointError::Unbind(result));
}
}
}
transport_tx
.send(TransportMessage::DeregisterDestination { hash: link_id })
.await
.map_err(|_| LinkEndpointError::TransportUnavailable)
}
pub(crate) fn send_message(
link_id: [u8; 16],
role: LinkEndpointRole,
raw: Bytes,
) -> (TransportMessage, PendingLinkEndpointSend) {
let (result_tx, result_rx) = oneshot::channel();
(
TransportMessage::SendLinkEndpoint {
link_id,
role,
request: OutboundRequest {
raw,
destination_hash: link_id,
},
result_tx,
},
PendingLinkEndpointSend {
link_id,
role,
final_unbind: false,
result_rx,
},
)
}
pub(crate) fn send_and_unbind_message(
link_id: [u8; 16],
role: LinkEndpointRole,
raw: Bytes,
) -> (TransportMessage, PendingLinkEndpointSend) {
let (result_tx, result_rx) = oneshot::channel();
(
TransportMessage::SendLinkEndpointAndUnbind {
link_id,
role,
request: OutboundRequest {
raw,
destination_hash: link_id,
},
result_tx,
},
PendingLinkEndpointSend {
link_id,
role,
final_unbind: true,
result_rx,
},
)
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use rns_crypto::ed25519::Ed25519PrivateKey;
use rns_link::link::{Link, LinkState};
use super::*;
fn proof_packet(link_id: [u8; 16], proof: &[u8]) -> Bytes {
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Proof,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context: rns_wire::context::PacketContext::None,
};
let mut raw = header.pack();
raw.extend_from_slice(proof);
raw.into()
}
#[tokio::test]
async fn invalid_proof_does_not_win_interface_race_before_valid_proof() {
let destination_hash = [0xA4; 16];
let signing_key = Ed25519PrivateKey::generate();
let verify_key = signing_key.public_key();
let (mut initiator, request_data) = Link::new_initiator(destination_hash, 1);
let (_responder, proof) =
Link::new_responder(&request_data, &signing_key, destination_hash, 1).unwrap();
let mut invalid = proof.clone();
invalid[0] ^= 0x80;
let link_id = initiator.link_id;
let (event_tx, mut event_rx) = mpsc::channel(2);
event_tx
.send(DestinationEvent::InboundPacket {
raw: proof_packet(link_id, &invalid),
interface_id: 41,
metrics: PacketMetrics {
rssi: Some(-10.0),
..Default::default()
},
})
.await
.unwrap();
event_tx
.send(DestinationEvent::InboundPacket {
raw: proof_packet(link_id, &proof),
interface_id: 42,
metrics: PacketMetrics {
rssi: Some(-80.0),
..Default::default()
},
})
.await
.unwrap();
let validated = wait_for_valid_proof(
&mut event_rx,
&mut initiator,
&verify_key,
&verify_key.to_bytes(),
)
.await
.unwrap();
assert_eq!(validated.interface_id, 42);
assert_eq!(validated.metrics.rssi, Some(-80.0));
assert!(matches!(
initiator.state,
LinkState::Handshake | LinkState::Active
));
assert!(initiator.session_keys().is_some());
}
#[tokio::test]
async fn invalid_proof_only_waits_for_original_timeout() {
let destination_hash = [0xA5; 16];
let signing_key = Ed25519PrivateKey::generate();
let verify_key = signing_key.public_key();
let (mut initiator, request_data) = Link::new_initiator(destination_hash, 1);
let (_responder, mut proof) =
Link::new_responder(&request_data, &signing_key, destination_hash, 1).unwrap();
proof[0] ^= 0x80;
let link_id = initiator.link_id;
let (event_tx, mut event_rx) = mpsc::channel(1);
event_tx
.send(DestinationEvent::InboundPacket {
raw: proof_packet(link_id, &proof),
interface_id: 99,
metrics: PacketMetrics::default(),
})
.await
.unwrap();
assert!(
tokio::time::timeout(
Duration::from_millis(20),
wait_for_valid_proof(
&mut event_rx,
&mut initiator,
&verify_key,
&verify_key.to_bytes(),
),
)
.await
.is_err()
);
assert_eq!(initiator.state, LinkState::Pending);
drop(event_tx);
}
#[tokio::test]
async fn dropped_cleanup_guard_survives_transport_ingress_backpressure() {
let link_id = [0xC1; 16];
let (transport_tx, mut transport_rx) = mpsc::channel(1);
transport_tx.send(TransportMessage::Shutdown).await.unwrap();
let mut guard =
LinkEndpointCleanupGuard::new(transport_tx, link_id, LinkEndpointRole::Initiator);
guard.endpoint_bound();
drop(guard);
assert!(matches!(
transport_rx.recv().await,
Some(TransportMessage::Shutdown)
));
let Some(TransportMessage::UnbindLinkEndpoint {
link_id: unbound,
role,
result_tx,
}) = transport_rx.recv().await
else {
panic!("retained cleanup must enqueue typed unbind after capacity returns");
};
assert_eq!(unbound, link_id);
assert_eq!(role, LinkEndpointRole::Initiator);
assert!(
tokio::time::timeout(Duration::from_millis(10), transport_rx.recv())
.await
.is_err(),
"destination deregistration must wait for the typed unbind result"
);
let _ = result_tx.send(LinkEndpointUnbindResult::Unbound);
assert!(matches!(
transport_rx.recv().await,
Some(TransportMessage::DeregisterDestination { hash }) if hash == link_id
));
}
#[tokio::test]
async fn role_mismatch_never_deregisters_another_endpoint_owner() {
let link_id = [0xC2; 16];
let (transport_tx, mut transport_rx) = mpsc::channel(2);
let cleanup = tokio::spawn(async move {
cleanup_registered_link(&transport_tx, link_id, LinkEndpointRole::Initiator, true).await
});
let Some(TransportMessage::UnbindLinkEndpoint { result_tx, .. }) =
transport_rx.recv().await
else {
panic!("expected typed unbind");
};
let _ = result_tx.send(LinkEndpointUnbindResult::RoleMismatch);
assert!(matches!(
cleanup.await.unwrap(),
Err(LinkEndpointError::Unbind(
LinkEndpointUnbindResult::RoleMismatch
))
));
assert!(
transport_rx.try_recv().is_err(),
"role mismatch must not deregister the foreign Link destination"
);
}
#[tokio::test]
async fn cancelled_atomic_close_retains_queued_fifo_ownership() {
let link_id = [0xC3; 16];
let (transport_tx, mut transport_rx) = mpsc::channel(2);
let call_tx = transport_tx.clone();
let close = tokio::spawn(async move {
send_and_unbind(
&call_tx,
link_id,
LinkEndpointRole::Initiator,
proof_packet(link_id, b"final"),
)
.await
});
let Some(TransportMessage::SendLinkEndpointAndUnbind { result_tx, .. }) =
transport_rx.recv().await
else {
panic!("expected atomic final send");
};
close.abort();
let _ = close.await;
let _ = result_tx.send(LinkEndpointSendResult::Queued { depth: 1 });
tokio::task::yield_now().await;
tokio::task::yield_now().await;
assert!(
transport_rx.try_recv().is_err(),
"accepted atomic close owns FIFO drain; cancellation must not preempt it"
);
drop(transport_tx);
}
}
File diff suppressed because it is too large. Load diff
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff. Show more